diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 663a7d4bf8a..49caa62ada9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,11 +6,10 @@ name: "Continuous Integration" on: push: branches: [ master, develop, v1.x-develop, v1.X ] - pull_request: + pull_request_target: branches: [ develop, v1.x-develop ] -permissions: - contents: read # to fetch code (actions/checkout) +permissions: read-all jobs: ci: @@ -21,16 +20,20 @@ jobs: java: [8] steps: - name: "Cache Maven Repos" - uses: actions/cache@v3 + uses: actions/cache@v4 with: path: ~/.m2/repository key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} restore-keys: | ${{ runner.os }}-maven- + - if: github.event_name == 'pull_request_target' + run: echo "REF=refs/pull/${{ github.event.number }}/merge" >> "$GITHUB_ENV" - name: "Checkout" - uses: actions/checkout@v3 + uses: actions/checkout@v4 + with: + ref: ${{ env.REF }} - name: "Set up JDK ${{ matrix.java }}" - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: java-version: ${{ matrix.java }} distribution: 'zulu' @@ -44,6 +47,11 @@ jobs: - name: "Test With Maven" run: mvn -Prelease-nacos clean test -DtrimStackTrace=false -e -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn - name: "Codecov" - uses: codecov/codecov-action@v3.1.0 + uses: codecov/codecov-action@v4.2.0 + env: + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} with: + verbose: true + fail_ci_if_error: true files: ./address/target/site/jacoco/jacoco.xml,./api/target/site/jacoco/jacoco.xml,./auth/target/site/jacoco/jacoco.xml,./client/target/site/jacoco/jacoco.xml,./common/target/site/jacoco/jacoco.xml,./config/target/site/jacoco/jacoco.xml,./consistency/target/site/jacoco/jacoco.xml,./console/target/site/jacoco/jacoco.xml,./core/target/site/jacoco/jacoco.xml,./logger-adapter-impl/log4j2-adapter/target/site/jacoco/jacoco.xml,./logger-adapter-impl/logback-adapter-12/target/site/jacoco/jacoco.xml,./naming/target/site/jacoco/jacoco.xml,./persistence/target/site/jacoco/jacoco.xml,./plugin-default-impl/nacos-default-auth-plugin/target/site/jacoco/jacoco.xml,./plugin-default-impl/nacos-default-control-plugin/target/site/jacoco/jacoco.xml,./plugin/auth/target/site/jacoco/jacoco.xml,./plugin/config/target/site/jacoco/jacoco.xml,./plugin/control/target/site/jacoco/jacoco.xml,./plugin/datasource/target/site/jacoco/jacoco.xml,./plugin/encryption/target/site/jacoco/jacoco.xml,./plugin/environment/target/site/jacoco/jacoco.xml,./plugin/trace/target/site/jacoco/jacoco.xml,./prometheus/target/site/jacoco/jacoco.xml,./sys/target/site/jacoco/jacoco.xml + token: ${{ secrets.CODECOV_TOKEN }} \ No newline at end of file diff --git a/.gitignore b/.gitignore index 6aa4d54cba5..ae9ec88aad6 100644 --- a/.gitignore +++ b/.gitignore @@ -18,3 +18,4 @@ test/logs derby.log yarn.lock .flattened-pom.xml +lefthook.yml diff --git a/README.md b/README.md index 972a68e3a00..625eb068440 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,7 @@ You can view the full documentation from the [Nacos website](https://nacos.io/en You can also read this online eBook from the [NACOS ARCHITECTURE & PRINCIPLES](https://www.yuque.com/nacos/ebook/kbyo6n). -All the latest and long-term notice can also be found here from [Github notice issue](https://github.com/alibaba/nacos/labels/notice). +All the latest and long-term notice can also be found here from [GitHub notice issue](https://github.com/alibaba/nacos/labels/notice). ## Contributing @@ -134,7 +134,7 @@ https://cn.aliyun.com/product/aliware/mse?spm=nacos-website.topbar.0.0.0 ## Download - [Nacos Official Website](https://nacos.io/download/nacos-server) -- [Github Release](https://github.com/alibaba/nacos/releases) +- [GitHub Release](https://github.com/alibaba/nacos/releases) ## Who is using diff --git a/address/pom.xml b/address/pom.xml index 2dfb65afa09..36c69ca77e0 100644 --- a/address/pom.xml +++ b/address/pom.xml @@ -41,8 +41,8 @@ - org.springframework.boot - spring-boot-starter-test + org.springframework + spring-test test diff --git a/address/src/test/java/com/alibaba/nacos/address/component/AddressServerGeneratorManagerTest.java b/address/src/test/java/com/alibaba/nacos/address/component/AddressServerGeneratorManagerTest.java index 497c94dea2a..95e15e3c97a 100644 --- a/address/src/test/java/com/alibaba/nacos/address/component/AddressServerGeneratorManagerTest.java +++ b/address/src/test/java/com/alibaba/nacos/address/component/AddressServerGeneratorManagerTest.java @@ -18,55 +18,59 @@ import com.alibaba.nacos.address.constant.AddressServerConstants; 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 AddressServerGeneratorManagerTest { - +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.assertTrue; + +class AddressServerGeneratorManagerTest { + @Test - public void testGenerateProductName() { + void testGenerateProductName() { AddressServerGeneratorManager manager = new AddressServerGeneratorManager(); final String blankName = manager.generateProductName(""); - Assert.assertEquals(AddressServerConstants.ALIWARE_NACOS_DEFAULT_PRODUCT_NAME, blankName); + assertEquals(AddressServerConstants.ALIWARE_NACOS_DEFAULT_PRODUCT_NAME, blankName); final String defaultName = manager.generateProductName(AddressServerConstants.DEFAULT_PRODUCT); - Assert.assertEquals(AddressServerConstants.ALIWARE_NACOS_DEFAULT_PRODUCT_NAME, defaultName); + assertEquals(AddressServerConstants.ALIWARE_NACOS_DEFAULT_PRODUCT_NAME, defaultName); final String testName = manager.generateProductName("test"); - Assert.assertEquals("nacos.as.test", testName); + assertEquals("nacos.as.test", testName); } - + @Test - public void testGenerateInstancesByIps() { + void testGenerateInstancesByIps() { AddressServerGeneratorManager manager = new AddressServerGeneratorManager(); final List empty = manager.generateInstancesByIps(null, null, null, null); - Assert.assertNotNull(empty); - Assert.assertTrue(empty.isEmpty()); + assertNotNull(empty); + assertTrue(empty.isEmpty()); String[] ipArray = new String[]{"192.168.3.1:8848", "192.168.3.2:8848", "192.168.3.3:8848"}; final List instanceList = manager.generateInstancesByIps("DEFAULT_GROUP@@nacos.as.test", "test", "test", ipArray); - Assert.assertNotNull(instanceList); - Assert.assertFalse(instanceList.isEmpty()); - Assert.assertEquals(3, instanceList.size()); + assertNotNull(instanceList); + assertFalse(instanceList.isEmpty()); + assertEquals(3, instanceList.size()); final Instance instance1 = instanceList.get(0); - Assert.assertEquals("192.168.3.1", instance1.getIp()); + assertEquals("192.168.3.1", instance1.getIp()); final Instance instance2 = instanceList.get(1); - Assert.assertEquals("192.168.3.2", instance2.getIp()); + assertEquals("192.168.3.2", instance2.getIp()); final Instance instance3 = instanceList.get(2); - Assert.assertEquals("192.168.3.3", instance3.getIp()); + assertEquals("192.168.3.3", instance3.getIp()); } - + @Test - public void testGenerateResponseIps() { + void testGenerateResponseIps() { final List instanceList = new ArrayList<>(); Instance instance1 = new Instance(); instance1.setIp("192.168.3.1"); @@ -92,19 +96,19 @@ public void testGenerateResponseIps() { .append("192.168.3.1:8848").append('\n') .append("192.168.3.2:8848").append('\n') .append("192.168.3.3:8848").append('\n'); - Assert.assertEquals(ret.toString(), ipListStr); + assertEquals(ret.toString(), ipListStr); } - + @Test - public void testGenerateNacosServiceName() { + void testGenerateNacosServiceName() { AddressServerGeneratorManager manager = new AddressServerGeneratorManager(); final String containDefault = manager.generateNacosServiceName("DEFAULT_GROUP@@test"); - Assert.assertEquals("DEFAULT_GROUP@@test", containDefault); + assertEquals("DEFAULT_GROUP@@test", containDefault); final String product = manager.generateNacosServiceName("product"); - Assert.assertEquals("DEFAULT_GROUP@@product", product); + assertEquals("DEFAULT_GROUP@@product", product); } } diff --git a/address/src/test/java/com/alibaba/nacos/address/component/AddressServerManagerTests.java b/address/src/test/java/com/alibaba/nacos/address/component/AddressServerManagerTests.java index 25c6441dbb2..af22fd03d39 100644 --- a/address/src/test/java/com/alibaba/nacos/address/component/AddressServerManagerTests.java +++ b/address/src/test/java/com/alibaba/nacos/address/component/AddressServerManagerTests.java @@ -17,38 +17,38 @@ package com.alibaba.nacos.address.component; import com.alibaba.nacos.address.constant.AddressServerConstants; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class AddressServerManagerTests { +class AddressServerManagerTests { private static final AddressServerManager ADDRESS_SERVER_MANAGER = new AddressServerManager(); - + @Test - public void getRawProductName() { + void getRawProductName() { assertEquals(AddressServerConstants.DEFAULT_PRODUCT, ADDRESS_SERVER_MANAGER.getRawProductName("")); assertEquals(AddressServerConstants.DEFAULT_PRODUCT, ADDRESS_SERVER_MANAGER.getRawProductName(AddressServerConstants.DEFAULT_PRODUCT)); assertEquals("otherProduct", ADDRESS_SERVER_MANAGER.getRawProductName("otherProduct")); } - + @Test - public void getDefaultClusterNameIfEmpty() { + void getDefaultClusterNameIfEmpty() { assertEquals(AddressServerConstants.DEFAULT_GET_CLUSTER, ADDRESS_SERVER_MANAGER.getDefaultClusterNameIfEmpty("")); assertEquals(AddressServerConstants.DEFAULT_GET_CLUSTER, ADDRESS_SERVER_MANAGER.getDefaultClusterNameIfEmpty(AddressServerConstants.DEFAULT_GET_CLUSTER)); assertEquals("otherServerList", ADDRESS_SERVER_MANAGER.getDefaultClusterNameIfEmpty("otherServerList")); } - + @Test - public void testGetRawClusterName() { + void testGetRawClusterName() { assertEquals("serverList", ADDRESS_SERVER_MANAGER.getRawClusterName("serverList")); assertEquals(AddressServerConstants.DEFAULT_GET_CLUSTER, ADDRESS_SERVER_MANAGER.getRawClusterName("")); } - + @Test - public void testSplitIps() { + void testSplitIps() { final String[] emptyArr = ADDRESS_SERVER_MANAGER.splitIps(""); assertEquals(0, emptyArr.length); final String[] one = ADDRESS_SERVER_MANAGER.splitIps("192.168.1.12:8848"); diff --git a/address/src/test/java/com/alibaba/nacos/address/controller/AddressServerClusterControllerTest.java b/address/src/test/java/com/alibaba/nacos/address/controller/AddressServerClusterControllerTest.java index aa7f8eddba0..132f56c98a6 100644 --- a/address/src/test/java/com/alibaba/nacos/address/controller/AddressServerClusterControllerTest.java +++ b/address/src/test/java/com/alibaba/nacos/address/controller/AddressServerClusterControllerTest.java @@ -26,13 +26,13 @@ import com.alibaba.nacos.naming.core.v2.ServiceManager; import com.alibaba.nacos.naming.core.v2.metadata.NamingMetadataManager; import com.alibaba.nacos.naming.core.v2.pojo.Service; -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.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @@ -40,8 +40,8 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -@RunWith(MockitoJUnitRunner.class) -public class AddressServerClusterControllerTest { +@ExtendWith(MockitoExtension.class) +class AddressServerClusterControllerTest { @Mock private InstanceOperator instanceOperator; @@ -53,9 +53,9 @@ public class AddressServerClusterControllerTest { private ClusterOperator clusterOperator; private MockMvc mockMvc; - - @Before - public void before() { + + @BeforeEach + void before() { mockMvc = MockMvcBuilders.standaloneSetup( new AddressServerClusterController(instanceOperator, metadataManager, clusterOperator, new AddressServerManager(), new AddressServerGeneratorManager())).build(); @@ -63,30 +63,30 @@ public void before() { .newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "nacos.as.default", false); ServiceManager.getInstance().getSingleton(service); } - - @After - public void tearDown() { + + @AfterEach + void tearDown() { Service service = Service .newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "nacos.as.default", false); ServiceManager.getInstance().removeSingleton(service); } - + @Test - public void testPostCluster() throws Exception { + void testPostCluster() throws Exception { mockMvc.perform(post("/nacos/v1/as/nodes").param("product", "default").param("cluster", "serverList") .param("ips", "192.168.3.1,192.168.3.2")).andExpect(status().isOk()); } - + @Test - public void testPostClusterWithErrorIps() throws Exception { + void testPostClusterWithErrorIps() throws Exception { mockMvc.perform(post("/nacos/v1/as/nodes").param("product", "default").param("cluster", "serverList") .param("ips", "192.168.1")).andExpect(status().isBadRequest()); } - + @Test - public void testPostClusterThrowException() throws Exception { + void testPostClusterThrowException() throws Exception { Mockito.doThrow(new NacosException(500, "create service error")).when(clusterOperator) .updateClusterMetadata(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID), Mockito.eq( @@ -97,34 +97,34 @@ public void testPostClusterThrowException() throws Exception { .param("ips", "192.168.1")).andExpect(status().isInternalServerError()); } - + @Test - public void testDeleteCluster() throws Exception { + void testDeleteCluster() throws Exception { mockMvc.perform(delete("/nacos/v1/as/nodes").param("product", "default").param("cluster", "serverList") .param("ips", "192.168.3.1,192.168.3.2")).andExpect(status().isOk()); } - + @Test - public void testDeleteClusterCannotFindService() throws Exception { + void testDeleteClusterCannotFindService() throws Exception { tearDown(); mockMvc.perform(delete("/nacos/v1/as/nodes").param("product", "default").param("cluster", "serverList") .param("ips", "192.168.3.1,192.168.3.2")).andExpect(status().isNotFound()); } - + @Test - public void testDeleteClusterEmptyIps() throws Exception { + void testDeleteClusterEmptyIps() throws Exception { mockMvc.perform(delete("/nacos/v1/as/nodes").param("product", "default").param("cluster", "serverList") .param("ips", "")).andExpect(status().isBadRequest()); } - + @Test - public void testDeleteClusterErrorIps() throws Exception { + void testDeleteClusterErrorIps() throws Exception { mockMvc.perform(delete("/nacos/v1/as/nodes").param("product", "default").param("cluster", "serverList") .param("ips", "192.168.1")).andExpect(status().isBadRequest()); } - + @Test - public void testDeleteClusterThrowException() throws Exception { + void testDeleteClusterThrowException() throws Exception { Mockito.doThrow(new NacosException(500, "remove service error")).when(instanceOperator) .removeInstance(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID), Mockito.eq( Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"), diff --git a/address/src/test/java/com/alibaba/nacos/address/controller/ServerListControllerTest.java b/address/src/test/java/com/alibaba/nacos/address/controller/ServerListControllerTest.java index 44c27b3db40..70250483276 100644 --- a/address/src/test/java/com/alibaba/nacos/address/controller/ServerListControllerTest.java +++ b/address/src/test/java/com/alibaba/nacos/address/controller/ServerListControllerTest.java @@ -26,12 +26,12 @@ import com.alibaba.nacos.naming.core.v2.metadata.NamingMetadataManager; import com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata; import com.alibaba.nacos.naming.core.v2.pojo.Service; -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 org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @@ -43,8 +43,8 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -@RunWith(MockitoJUnitRunner.class) -public class ServerListControllerTest { +@ExtendWith(MockitoExtension.class) +class ServerListControllerTest { @Mock private NamingMetadataManager metadataManager; @@ -55,23 +55,23 @@ public class ServerListControllerTest { private Service service; private MockMvc mockMvc; - - @Before - public void before() { + + @BeforeEach + void before() { this.mockMvc = MockMvcBuilders.standaloneSetup( new ServerListController(new AddressServerGeneratorManager(), metadataManager, serviceStorage)).build(); service = Service .newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "nacos.as.default", false); ServiceManager.getInstance().getSingleton(service); } - - @After - public void tearDown() { + + @AfterEach + void tearDown() { ServiceManager.getInstance().removeSingleton(service); } - + @Test - public void testGetCluster() throws Exception { + void testGetCluster() throws Exception { final Service service = Service .newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "nacos.as.default", false); @@ -86,16 +86,16 @@ public void testGetCluster() throws Exception { when(serviceStorage.getData(service)).thenReturn(serviceInfo); mockMvc.perform(get("/nacos/serverList")).andExpect(status().isOk()); } - + @Test - public void testGetClusterCannotFindService() throws Exception { + void testGetClusterCannotFindService() throws Exception { tearDown(); mockMvc.perform(get("/default/serverList")).andExpect(status().isNotFound()); } - + @Test - public void testGetClusterCannotFindCluster() throws Exception { + void testGetClusterCannotFindCluster() throws Exception { mockMvc.perform(get("/nacos/serverList")).andExpect(status().isNotFound()); } diff --git a/api/pom.xml b/api/pom.xml index 63505fc473c..45b3ae08302 100644 --- a/api/pom.xml +++ b/api/pom.xml @@ -63,11 +63,6 @@ com.fasterxml.jackson.core jackson-databind - - junit - junit - test - org.springframework spring-test @@ -85,6 +80,10 @@ io.grpc grpc-stub + + io.grpc + grpc-util + com.google.api.grpc proto-google-common-protos diff --git a/api/src/main/java/com/alibaba/nacos/api/PropertyKeyConst.java b/api/src/main/java/com/alibaba/nacos/api/PropertyKeyConst.java index 9a1f4368971..fe27f27ca7b 100644 --- a/api/src/main/java/com/alibaba/nacos/api/PropertyKeyConst.java +++ b/api/src/main/java/com/alibaba/nacos/api/PropertyKeyConst.java @@ -35,6 +35,8 @@ public class PropertyKeyConst { public static final String ENDPOINT_CONTEXT_PATH = "endpointContextPath"; + public static final String ENDPOINT_CLUSTER_NAME = "endpointClusterName"; + public static final String SERVER_NAME = "serverName"; public static final String NAMESPACE = "namespace"; @@ -62,7 +64,7 @@ public class PropertyKeyConst { public static final String CONFIG_RETRY_TIME = "configRetryTime"; public static final String CLIENT_WORKER_MAX_THREAD_COUNT = "clientWorkerMaxThreadCount"; - + public static final String CLIENT_WORKER_THREAD_COUNT = "clientWorkerThreadCount"; public static final String MAX_RETRY = "maxRetry"; @@ -89,6 +91,15 @@ public class PropertyKeyConst { public static final String REDO_DELAY_THREAD_COUNT = "redoDelayThreadCount"; + public static final String SIGNATURE_REGION_ID = "signatureRegionId"; + + public static final String LOG_ALL_PROPERTIES = "logAllProperties"; + + /** + * Since 2.3.3, For some situation like java agent using nacos-client which can't use env ram info. + */ + public static final String IS_USE_RAM_INFO_PARSING = "isUseRamInfoParsing"; + /** * Get the key value of some variable value from the system property. */ diff --git a/api/src/main/java/com/alibaba/nacos/api/SystemPropertyKeyConst.java b/api/src/main/java/com/alibaba/nacos/api/SystemPropertyKeyConst.java index 3eac8aaa1f6..f24138dafa6 100644 --- a/api/src/main/java/com/alibaba/nacos/api/SystemPropertyKeyConst.java +++ b/api/src/main/java/com/alibaba/nacos/api/SystemPropertyKeyConst.java @@ -46,4 +46,9 @@ public interface SystemPropertyKeyConst { * It is also supported by the -D parameter. */ String IS_USE_ENDPOINT_PARSING_RULE = "nacos.use.endpoint.parsing.rule"; + + /** + * Since 2.3.3, For some situation like java agent using nacos-client which can't use env ram info. + */ + String IS_USE_RAM_INFO_PARSING = "nacos.use.ram.info.parsing"; } diff --git a/api/src/main/java/com/alibaba/nacos/api/common/Constants.java b/api/src/main/java/com/alibaba/nacos/api/common/Constants.java index 0d9b6a1ac69..0bb32558b11 100644 --- a/api/src/main/java/com/alibaba/nacos/api/common/Constants.java +++ b/api/src/main/java/com/alibaba/nacos/api/common/Constants.java @@ -43,10 +43,14 @@ public class Constants { public static final String NULL = ""; - public static final String DATAID = "dataId"; - + public static final String DATA_ID = "dataId"; + + public static final String TENANT = "tenant"; + public static final String GROUP = "group"; - + + public static final String NAMESPACE_ID = "namespaceId"; + public static final String LAST_MODIFIED = "Last-Modified"; public static final String ACCEPT_ENCODING = "Accept-Encoding"; @@ -243,6 +247,11 @@ public class Constants { public static final String CONFIG_GRAY_LABEL = "nacos.config.gray.label"; + /** + * Since 2.3.3, For some situation like java agent using nacos-client which can't use env ram info. + */ + public static final String DEFAULT_USE_RAM_INFO_PARSING = "true"; + /** * The constants in config directory. */ diff --git a/api/src/main/java/com/alibaba/nacos/api/naming/NamingService.java b/api/src/main/java/com/alibaba/nacos/api/naming/NamingService.java index e0cbb83d3aa..f10c25d3029 100644 --- a/api/src/main/java/com/alibaba/nacos/api/naming/NamingService.java +++ b/api/src/main/java/com/alibaba/nacos/api/naming/NamingService.java @@ -21,6 +21,7 @@ import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; import com.alibaba.nacos.api.naming.pojo.ServiceInfo; +import com.alibaba.nacos.api.naming.selector.NamingSelector; import com.alibaba.nacos.api.selector.AbstractSelector; import java.util.List; @@ -491,6 +492,28 @@ Instance selectOneHealthyInstance(String serviceName, String groupName, List clusters, EventListener listener) throws NacosException; + /** + * Subscribe service to receive events of instances alteration. + * + * @param serviceName name of service + * @param selector selector of instances + * @param listener event listener + * @throws NacosException nacos exception + */ + void subscribe(String serviceName, NamingSelector selector, EventListener listener) throws NacosException; + + /** + * Subscribe service to receive events of instances alteration. + * + * @param serviceName name of service + * @param groupName group of service + * @param selector selector of instances + * @param listener event listener + * @throws NacosException nacos exception + */ + void subscribe(String serviceName, String groupName, NamingSelector selector, EventListener listener) + throws NacosException; + /** * Unsubscribe event listener of service. * @@ -532,6 +555,28 @@ void subscribe(String serviceName, String groupName, List clusters, Even void unsubscribe(String serviceName, String groupName, List clusters, EventListener listener) throws NacosException; + /** + * Unsubscribe event listener of service. + * + * @param serviceName name of service + * @param selector selector of instances + * @param listener event listener + * @throws NacosException nacos exception + */ + void unsubscribe(String serviceName, NamingSelector selector, EventListener listener) throws NacosException; + + /** + * Unsubscribe event listener of service. + * + * @param serviceName name of service + * @param groupName group of service + * @param selector selector of instances + * @param listener event listener + * @throws NacosException nacos exception + */ + void unsubscribe(String serviceName, String groupName, NamingSelector selector, EventListener listener) + throws NacosException; + /** * Get all service names from server. * diff --git a/api/src/main/java/com/alibaba/nacos/api/naming/selector/NamingContext.java b/api/src/main/java/com/alibaba/nacos/api/naming/selector/NamingContext.java new file mode 100644 index 00000000000..ae94a890216 --- /dev/null +++ b/api/src/main/java/com/alibaba/nacos/api/naming/selector/NamingContext.java @@ -0,0 +1,57 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.api.naming.selector; + +import com.alibaba.nacos.api.naming.pojo.Instance; + +import java.util.List; + +/** + * Naming selector context. + * + * @author lideyou + */ +public interface NamingContext { + + /** + * Get service name. + * + * @return service name + */ + String getServiceName(); + + /** + * Get group name. + * + * @return group name + */ + String getGroupName(); + + /** + * Get clusters. + * + * @return clusters + */ + String getClusters(); + + /** + * Get current instances. + * + * @return current instances + */ + List getInstances(); +} diff --git a/api/src/main/java/com/alibaba/nacos/api/naming/selector/NamingResult.java b/api/src/main/java/com/alibaba/nacos/api/naming/selector/NamingResult.java new file mode 100644 index 00000000000..3706167751c --- /dev/null +++ b/api/src/main/java/com/alibaba/nacos/api/naming/selector/NamingResult.java @@ -0,0 +1,31 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.api.naming.selector; + +import com.alibaba.nacos.api.naming.pojo.Instance; +import com.alibaba.nacos.api.selector.client.SelectResult; + +import java.util.List; + +/** + * Naming select result. + * + * @author lideyou + */ +public interface NamingResult extends SelectResult> { + +} diff --git a/api/src/main/java/com/alibaba/nacos/api/naming/selector/NamingSelector.java b/api/src/main/java/com/alibaba/nacos/api/naming/selector/NamingSelector.java new file mode 100644 index 00000000000..252a56977af --- /dev/null +++ b/api/src/main/java/com/alibaba/nacos/api/naming/selector/NamingSelector.java @@ -0,0 +1,28 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.api.naming.selector; + +import com.alibaba.nacos.api.selector.client.Selector; + +/** + * Naming selector. + * + * @author lideyou + */ +public interface NamingSelector extends Selector { + +} diff --git a/api/src/main/java/com/alibaba/nacos/api/selector/client/SelectResult.java b/api/src/main/java/com/alibaba/nacos/api/selector/client/SelectResult.java new file mode 100644 index 00000000000..951f69bd607 --- /dev/null +++ b/api/src/main/java/com/alibaba/nacos/api/selector/client/SelectResult.java @@ -0,0 +1,33 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.api.selector.client; + +/** + * Select result. + * + * @param the type of result + * @author lideyou + */ +public interface SelectResult { + + /** + * Get select result. + * + * @return select result + */ + T getResult(); +} diff --git a/api/src/main/java/com/alibaba/nacos/api/selector/client/Selector.java b/api/src/main/java/com/alibaba/nacos/api/selector/client/Selector.java new file mode 100644 index 00000000000..131e777b04a --- /dev/null +++ b/api/src/main/java/com/alibaba/nacos/api/selector/client/Selector.java @@ -0,0 +1,35 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.api.selector.client; + +/** + * Client selector. + * + * @param the type of selector context + * @param the type of select result + * @author lideyou + */ +public interface Selector { + + /** + * select the target result. + * + * @param context selector context + * @return select result + */ + E select(C context); +} diff --git a/api/src/test/java/com/alibaba/nacos/api/ability/ClientAbilitiesTest.java b/api/src/test/java/com/alibaba/nacos/api/ability/ClientAbilitiesTest.java index 7510c1e82fd..b15c83dcde4 100644 --- a/api/src/test/java/com/alibaba/nacos/api/ability/ClientAbilitiesTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/ability/ClientAbilitiesTest.java @@ -20,25 +20,25 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ClientAbilitiesTest { +class ClientAbilitiesTest { private static ObjectMapper mapper; - @BeforeClass - public static void setUp() throws Exception { + @BeforeAll + static void setUp() throws Exception { mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } @Test - public void testSerialize() throws JsonProcessingException { + void testSerialize() throws JsonProcessingException { ClientAbilities abilities = new ClientAbilities(); String json = mapper.writeValueAsString(abilities); assertTrue(json.contains("\"remoteAbility\":{")); @@ -47,7 +47,7 @@ public void testSerialize() throws JsonProcessingException { } @Test - public void testDeserialize() throws JsonProcessingException { + void testDeserialize() throws JsonProcessingException { String json = "{\"remoteAbility\":{\"supportRemoteConnection\":false}," + "\"configAbility\":{\"supportRemoteMetrics\":false},\"namingAbility\":{\"supportDeltaPush\":false," + "\"supportRemoteMetric\":false}}"; diff --git a/api/src/test/java/com/alibaba/nacos/api/ability/ServerAbilitiesTest.java b/api/src/test/java/com/alibaba/nacos/api/ability/ServerAbilitiesTest.java index 69ba2aca886..1b9785cfe3c 100644 --- a/api/src/test/java/com/alibaba/nacos/api/ability/ServerAbilitiesTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/ability/ServerAbilitiesTest.java @@ -20,35 +20,35 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ServerAbilitiesTest { +class ServerAbilitiesTest { private static ObjectMapper mapper; private ServerAbilities serverAbilities; - @BeforeClass - public static void setUpBeforeClass() throws Exception { + @BeforeAll + static void setUpBeforeClass() throws Exception { mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { serverAbilities = new ServerAbilities(); } @Test - public void testSerialize() throws JsonProcessingException { + void testSerialize() throws JsonProcessingException { serverAbilities = new ServerAbilities(); String json = mapper.writeValueAsString(serverAbilities); assertTrue(json.contains("\"remoteAbility\":{")); @@ -57,7 +57,7 @@ public void testSerialize() throws JsonProcessingException { } @Test - public void testDeserialize() throws JsonProcessingException { + void testDeserialize() throws JsonProcessingException { String json = "{\"remoteAbility\":{\"supportRemoteConnection\":false}," + "\"configAbility\":{\"supportRemoteMetrics\":false},\"namingAbility\":{\"supportDeltaPush\":false," + "\"supportRemoteMetric\":false}}"; @@ -68,10 +68,10 @@ public void testDeserialize() throws JsonProcessingException { } @Test - public void testEqualsAndHashCode() { + void testEqualsAndHashCode() { assertEquals(serverAbilities, serverAbilities); assertEquals(serverAbilities.hashCode(), serverAbilities.hashCode()); - assertNotEquals(serverAbilities, null); + assertNotEquals(null, serverAbilities); assertNotEquals(serverAbilities, new ClientAbilities()); ServerAbilities test = new ServerAbilities(); assertEquals(serverAbilities, test); diff --git a/api/src/test/java/com/alibaba/nacos/api/ability/register/impl/ClusterClientAbilitiesTest.java b/api/src/test/java/com/alibaba/nacos/api/ability/register/impl/ClusterClientAbilitiesTest.java index b6ec8a54e66..e7db88cc8c3 100644 --- a/api/src/test/java/com/alibaba/nacos/api/ability/register/impl/ClusterClientAbilitiesTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/ability/register/impl/ClusterClientAbilitiesTest.java @@ -16,14 +16,14 @@ package com.alibaba.nacos.api.ability.register.impl; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ClusterClientAbilitiesTest { +class ClusterClientAbilitiesTest { @Test - public void testGetStaticAbilities() { + void testGetStaticAbilities() { // TODO add the cluster client abilities. assertTrue(ClusterClientAbilities.getStaticAbilities().isEmpty()); } diff --git a/api/src/test/java/com/alibaba/nacos/api/ability/register/impl/SdkClientAbilitiesTest.java b/api/src/test/java/com/alibaba/nacos/api/ability/register/impl/SdkClientAbilitiesTest.java index ea9cabd4653..36a6db496bd 100644 --- a/api/src/test/java/com/alibaba/nacos/api/ability/register/impl/SdkClientAbilitiesTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/ability/register/impl/SdkClientAbilitiesTest.java @@ -16,14 +16,14 @@ package com.alibaba.nacos.api.ability.register.impl; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class SdkClientAbilitiesTest { +class SdkClientAbilitiesTest { @Test - public void testGetStaticAbilities() { + void testGetStaticAbilities() { // TODO add the sdk client abilities. assertTrue(SdkClientAbilities.getStaticAbilities().isEmpty()); } diff --git a/api/src/test/java/com/alibaba/nacos/api/ability/register/impl/ServerAbilitiesTest.java b/api/src/test/java/com/alibaba/nacos/api/ability/register/impl/ServerAbilitiesTest.java index 2058a353137..79ba5f6e425 100644 --- a/api/src/test/java/com/alibaba/nacos/api/ability/register/impl/ServerAbilitiesTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/ability/register/impl/ServerAbilitiesTest.java @@ -17,20 +17,20 @@ package com.alibaba.nacos.api.ability.register.impl; import com.alibaba.nacos.api.ability.constant.AbilityKey; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ServerAbilitiesTest { +class ServerAbilitiesTest { @Test - public void testGetStaticAbilities() { + void testGetStaticAbilities() { assertFalse(ServerAbilities.getStaticAbilities().isEmpty()); } - + @Test - public void testSupportPersistentInstanceByGrpcAbilities() { + void testSupportPersistentInstanceByGrpcAbilities() { assertTrue(ServerAbilities.getStaticAbilities().get(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); } } \ No newline at end of file diff --git a/api/src/test/java/com/alibaba/nacos/api/annotation/NacosPropertiesTest.java b/api/src/test/java/com/alibaba/nacos/api/annotation/NacosPropertiesTest.java index c0ff4ccee43..1e3885d044a 100644 --- a/api/src/test/java/com/alibaba/nacos/api/annotation/NacosPropertiesTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/annotation/NacosPropertiesTest.java @@ -16,8 +16,7 @@ package com.alibaba.nacos.api.annotation; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.mock.env.MockEnvironment; import static com.alibaba.nacos.api.annotation.NacosProperties.ACCESS_KEY_PLACEHOLDER; @@ -28,23 +27,24 @@ import static com.alibaba.nacos.api.annotation.NacosProperties.NAMESPACE_PLACEHOLDER; import static com.alibaba.nacos.api.annotation.NacosProperties.SECRET_KEY_PLACEHOLDER; import static com.alibaba.nacos.api.annotation.NacosProperties.SERVER_ADDR_PLACEHOLDER; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class NacosPropertiesTest { +class NacosPropertiesTest { @Test - public void testPlaceholders() { - Assert.assertEquals("${nacos.endpoint:}", ENDPOINT_PLACEHOLDER); - Assert.assertEquals("${nacos.namespace:}", NAMESPACE_PLACEHOLDER); - Assert.assertEquals("${nacos.access-key:}", ACCESS_KEY_PLACEHOLDER); - Assert.assertEquals("${nacos.secret-key:}", SECRET_KEY_PLACEHOLDER); - Assert.assertEquals("${nacos.server-addr:}", SERVER_ADDR_PLACEHOLDER); - Assert.assertEquals("${nacos.context-path:}", CONTEXT_PATH_PLACEHOLDER); - Assert.assertEquals("${nacos.cluster-name:}", CLUSTER_NAME_PLACEHOLDER); - Assert.assertEquals("${nacos.encode:UTF-8}", ENCODE_PLACEHOLDER); + void testPlaceholders() { + assertEquals("${nacos.endpoint:}", ENDPOINT_PLACEHOLDER); + assertEquals("${nacos.namespace:}", NAMESPACE_PLACEHOLDER); + assertEquals("${nacos.access-key:}", ACCESS_KEY_PLACEHOLDER); + assertEquals("${nacos.secret-key:}", SECRET_KEY_PLACEHOLDER); + assertEquals("${nacos.server-addr:}", SERVER_ADDR_PLACEHOLDER); + assertEquals("${nacos.context-path:}", CONTEXT_PATH_PLACEHOLDER); + assertEquals("${nacos.cluster-name:}", CLUSTER_NAME_PLACEHOLDER); + assertEquals("${nacos.encode:UTF-8}", ENCODE_PLACEHOLDER); } @Test - public void testResolvePlaceholders() { + void testResolvePlaceholders() { testResolvePlaceholder(ENDPOINT_PLACEHOLDER, "nacos.endpoint", "test-value", "test-value"); testResolvePlaceholder(ENDPOINT_PLACEHOLDER, "", "test-value", ""); @@ -75,11 +75,11 @@ private void testResolvePlaceholder(String placeholder, String propertyName, Str MockEnvironment environment = new MockEnvironment(); environment.setProperty(propertyName, propertyValue); String resolvedValue = environment.resolvePlaceholders(placeholder); - Assert.assertEquals(expectValue, resolvedValue); + assertEquals(expectValue, resolvedValue); } @Test - public void testSort() { + void testSort() { } } diff --git a/api/src/test/java/com/alibaba/nacos/api/cmdb/pojo/EntityEventTest.java b/api/src/test/java/com/alibaba/nacos/api/cmdb/pojo/EntityEventTest.java index cab555aed68..c2e6bd0719b 100644 --- a/api/src/test/java/com/alibaba/nacos/api/cmdb/pojo/EntityEventTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/cmdb/pojo/EntityEventTest.java @@ -20,24 +20,24 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -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 EntityEventTest { +class EntityEventTest { ObjectMapper mapper = new ObjectMapper(); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } @Test - public void testSerialization() throws JsonProcessingException { + void testSerialization() throws JsonProcessingException { EntityEvent entity = new EntityEvent(); entity.setEntityName("test-entity"); entity.setEntityType("CMDB"); @@ -50,7 +50,7 @@ public void testSerialization() throws JsonProcessingException { } @Test - public void testDeserialization() throws JsonProcessingException { + void testDeserialization() throws JsonProcessingException { String json = "{\"type\":\"ENTITY_REMOVE\",\"entityName\":\"test-entity\",\"entityType\":\"CMDB\"}"; EntityEvent entity = mapper.readValue(json, EntityEvent.class); assertEquals("test-entity", entity.getEntityName()); diff --git a/api/src/test/java/com/alibaba/nacos/api/cmdb/pojo/EntityTest.java b/api/src/test/java/com/alibaba/nacos/api/cmdb/pojo/EntityTest.java index 79f05b39a90..5530921e213 100644 --- a/api/src/test/java/com/alibaba/nacos/api/cmdb/pojo/EntityTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/cmdb/pojo/EntityTest.java @@ -20,26 +20,26 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Collections; -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 EntityTest { +class EntityTest { ObjectMapper mapper = new ObjectMapper(); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } @Test - public void testSerialization() throws JsonProcessingException { + void testSerialization() throws JsonProcessingException { Entity entity = new Entity(); entity.setName("test-entity"); entity.setType(PreservedEntityTypes.ip.name()); @@ -51,7 +51,7 @@ public void testSerialization() throws JsonProcessingException { } @Test - public void testDeserialization() throws JsonProcessingException { + void testDeserialization() throws JsonProcessingException { String json = "{\"type\":\"service\",\"name\":\"test-entity\",\"labels\":{\"test-label-key\":\"test-label-value\"}}"; Entity entity = mapper.readValue(json, Entity.class); assertEquals("test-entity", entity.getName()); diff --git a/api/src/test/java/com/alibaba/nacos/api/cmdb/pojo/LabelTest.java b/api/src/test/java/com/alibaba/nacos/api/cmdb/pojo/LabelTest.java index 4a0023a009c..519e5401359 100644 --- a/api/src/test/java/com/alibaba/nacos/api/cmdb/pojo/LabelTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/cmdb/pojo/LabelTest.java @@ -20,26 +20,26 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Collections; -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 LabelTest { +class LabelTest { ObjectMapper mapper = new ObjectMapper(); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } @Test - public void testSerialization() throws JsonProcessingException { + void testSerialization() throws JsonProcessingException { Label label = new Label(); label.setName("test-label"); label.setDescription("CMDB description"); @@ -52,7 +52,7 @@ public void testSerialization() throws JsonProcessingException { } @Test - public void testDeserialization() throws JsonProcessingException { + void testDeserialization() throws JsonProcessingException { String json = "{\"values\":[\"test-value\"],\"name\":\"test-label\",\"description\":\"CMDB description\"}"; Label label = mapper.readValue(json, Label.class); assertEquals("test-label", label.getName()); diff --git a/api/src/test/java/com/alibaba/nacos/api/config/ConfigChangeEventTest.java b/api/src/test/java/com/alibaba/nacos/api/config/ConfigChangeEventTest.java index 3120941f2fb..c7adfac3a4e 100644 --- a/api/src/test/java/com/alibaba/nacos/api/config/ConfigChangeEventTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/config/ConfigChangeEventTest.java @@ -16,18 +16,18 @@ package com.alibaba.nacos.api.config; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; -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; -public class ConfigChangeEventTest { +class ConfigChangeEventTest { @Test - public void testConstructor() { + void testConstructor() { Map mockData = new HashMap<>(); mockData.put("test", new ConfigChangeItem("testKey", null, "testValue")); ConfigChangeEvent event = new ConfigChangeEvent(mockData); diff --git a/api/src/test/java/com/alibaba/nacos/api/config/ConfigChangeItemTest.java b/api/src/test/java/com/alibaba/nacos/api/config/ConfigChangeItemTest.java index cbd28b297b3..6f0ee862187 100644 --- a/api/src/test/java/com/alibaba/nacos/api/config/ConfigChangeItemTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/config/ConfigChangeItemTest.java @@ -16,15 +16,15 @@ package com.alibaba.nacos.api.config; -import org.junit.Test; +import org.junit.jupiter.api.Test; -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; -public class ConfigChangeItemTest { +class ConfigChangeItemTest { @Test - public void testSetNewValue() { + void testSetNewValue() { ConfigChangeItem item = new ConfigChangeItem("testKey", null, "testValue"); item.setType(PropertyChangeType.ADDED); assertEquals("testKey", item.getKey()); @@ -46,7 +46,7 @@ public void testSetNewValue() { } @Test - public void testToString() { + void testToString() { ConfigChangeItem item = new ConfigChangeItem("testKey", null, "testValue"); item.setType(PropertyChangeType.ADDED); assertEquals("ConfigChangeItem{key='testKey', oldValue='null', newValue='testValue', type=ADDED}", diff --git a/api/src/test/java/com/alibaba/nacos/api/config/ConfigTypeTest.java b/api/src/test/java/com/alibaba/nacos/api/config/ConfigTypeTest.java index ca8160f2209..003c21af4fe 100644 --- a/api/src/test/java/com/alibaba/nacos/api/config/ConfigTypeTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/config/ConfigTypeTest.java @@ -16,16 +16,16 @@ package com.alibaba.nacos.api.config; -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.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 ConfigTypeTest { +class ConfigTypeTest { @Test - public void isValidType() { + void isValidType() { assertTrue(ConfigType.isValidType("xml")); assertTrue(ConfigType.isValidType("properties")); assertTrue(ConfigType.isValidType("json")); @@ -38,7 +38,7 @@ public void isValidType() { } @Test - public void testGetDefaultType() { + void testGetDefaultType() { assertEquals("text", ConfigType.getDefaultType().getType()); } } \ No newline at end of file diff --git a/api/src/test/java/com/alibaba/nacos/api/config/ability/ClientRemoteAbilityTest.java b/api/src/test/java/com/alibaba/nacos/api/config/ability/ClientRemoteAbilityTest.java index eb9ab814055..2246fa5196e 100644 --- a/api/src/test/java/com/alibaba/nacos/api/config/ability/ClientRemoteAbilityTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/config/ability/ClientRemoteAbilityTest.java @@ -21,32 +21,32 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -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 ClientRemoteAbilityTest { +class ClientRemoteAbilityTest { private static ObjectMapper mapper; - @BeforeClass - public static void setUp() throws Exception { + @BeforeAll + static void setUp() throws Exception { mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } @Test - public void testSerialize() throws JsonProcessingException { + void testSerialize() throws JsonProcessingException { ClientRemoteAbility abilities = new ClientRemoteAbility(); String json = mapper.writeValueAsString(abilities); assertEquals("{\"supportRemoteConnection\":false}", json); } @Test - public void testDeserialize() throws JsonProcessingException { + void testDeserialize() throws JsonProcessingException { String json = "{\"supportRemoteConnection\":true}"; ClientRemoteAbility abilities = mapper.readValue(json, ClientRemoteAbility.class); assertTrue(abilities.isSupportRemoteConnection()); diff --git a/api/src/test/java/com/alibaba/nacos/api/config/ability/ServerConfigAbilityTest.java b/api/src/test/java/com/alibaba/nacos/api/config/ability/ServerConfigAbilityTest.java index d93e594a218..f20f91a742c 100644 --- a/api/src/test/java/com/alibaba/nacos/api/config/ability/ServerConfigAbilityTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/config/ability/ServerConfigAbilityTest.java @@ -16,21 +16,20 @@ package com.alibaba.nacos.api.config.ability; -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.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; -public class ServerConfigAbilityTest { +class ServerConfigAbilityTest { @Test - public void testEquals() { + void testEquals() { ServerConfigAbility ability = new ServerConfigAbility(); ability.setSupportRemoteMetrics(true); assertEquals(ability, ability); - assertFalse(ability.equals(null)); - assertFalse(ability.equals(new ClientConfigAbility())); + assertNotEquals(null, ability); + assertNotEquals(ability, new ClientConfigAbility()); ServerConfigAbility newOne = new ServerConfigAbility(); assertNotEquals(ability, newOne); newOne.setSupportRemoteMetrics(true); diff --git a/api/src/test/java/com/alibaba/nacos/api/config/ability/ServerRemoteAbilityTest.java b/api/src/test/java/com/alibaba/nacos/api/config/ability/ServerRemoteAbilityTest.java index b25af0f685e..173f82136d9 100644 --- a/api/src/test/java/com/alibaba/nacos/api/config/ability/ServerRemoteAbilityTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/config/ability/ServerRemoteAbilityTest.java @@ -23,35 +23,35 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -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.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ServerRemoteAbilityTest { +class ServerRemoteAbilityTest { private static ObjectMapper mapper; private ServerRemoteAbility serverAbilities; - @BeforeClass - public static void setUpBeforeClass() throws Exception { + @BeforeAll + static void setUpBeforeClass() throws Exception { mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { serverAbilities = new ServerRemoteAbility(); } @Test - public void testSerialize() throws JsonProcessingException { + void testSerialize() throws JsonProcessingException { serverAbilities = new ServerRemoteAbility(); String json = mapper.writeValueAsString(serverAbilities); assertTrue(json.contains("\"supportRemoteConnection\":false")); @@ -59,7 +59,7 @@ public void testSerialize() throws JsonProcessingException { } @Test - public void testDeserialize() throws JsonProcessingException { + void testDeserialize() throws JsonProcessingException { String json = "{\"supportRemoteConnection\":true,\"grpcReportEnabled\":true}"; ServerRemoteAbility abilities = mapper.readValue(json, ServerRemoteAbility.class); assertTrue(abilities.isSupportRemoteConnection()); @@ -67,10 +67,10 @@ public void testDeserialize() throws JsonProcessingException { } @Test - public void testEqualsAndHashCode() { + void testEqualsAndHashCode() { assertEquals(serverAbilities, serverAbilities); assertEquals(serverAbilities.hashCode(), serverAbilities.hashCode()); - assertNotEquals(serverAbilities, null); + assertNotEquals(null, serverAbilities); assertNotEquals(serverAbilities, new ClientAbilities()); ServerRemoteAbility test = new ServerRemoteAbility(); assertEquals(serverAbilities, test); diff --git a/api/src/test/java/com/alibaba/nacos/api/config/listener/AbstractListenerTest.java b/api/src/test/java/com/alibaba/nacos/api/config/listener/AbstractListenerTest.java index cf314884013..c9eadd19a7e 100644 --- a/api/src/test/java/com/alibaba/nacos/api/config/listener/AbstractListenerTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/config/listener/AbstractListenerTest.java @@ -16,14 +16,14 @@ package com.alibaba.nacos.api.config.listener; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNull; -public class AbstractListenerTest { +class AbstractListenerTest { @Test - public void testGetExecutor() { + void testGetExecutor() { // Default listener executor is null. assertNull(new AbstractListener() { @Override diff --git a/api/src/test/java/com/alibaba/nacos/api/config/listener/AbstractSharedListenerTest.java b/api/src/test/java/com/alibaba/nacos/api/config/listener/AbstractSharedListenerTest.java index 8a1fa8d429e..e61ea4e5518 100644 --- a/api/src/test/java/com/alibaba/nacos/api/config/listener/AbstractSharedListenerTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/config/listener/AbstractSharedListenerTest.java @@ -16,28 +16,28 @@ package com.alibaba.nacos.api.config.listener; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; -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; -public class AbstractSharedListenerTest { +class AbstractSharedListenerTest { private static final String CONFIG_CONTENT = "test"; private static Map receivedMap; - @Before - public void setUp() { + @BeforeEach + void setUp() { receivedMap = new HashMap<>(); } @Test - public void testFillContext() { + void testFillContext() { assertEquals(0, receivedMap.size()); MockShardListener listener = new MockShardListener(); listener.receiveConfigInfo(CONFIG_CONTENT); @@ -52,7 +52,7 @@ public void testFillContext() { } @Test - public void getExecutor() { + void getExecutor() { // Default listener executor is null. assertNull(new MockShardListener().getExecutor()); } diff --git a/api/src/test/java/com/alibaba/nacos/api/config/remote/request/BasedConfigRequestTest.java b/api/src/test/java/com/alibaba/nacos/api/config/remote/request/BasedConfigRequestTest.java index 8e4cecea7b3..b50a9209380 100644 --- a/api/src/test/java/com/alibaba/nacos/api/config/remote/request/BasedConfigRequestTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/config/remote/request/BasedConfigRequestTest.java @@ -22,7 +22,7 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.BeforeClass; +import org.junit.jupiter.api.BeforeAll; import java.util.HashMap; import java.util.Map; @@ -30,8 +30,6 @@ public abstract class BasedConfigRequestTest { - protected static ObjectMapper mapper; - protected static final String DATA_ID = "test_data"; protected static final String GROUP = "group"; @@ -52,11 +50,13 @@ public abstract class BasedConfigRequestTest { protected static final String CONTENT = "content"; + protected static ObjectMapper mapper; + static { HEADERS.put(HEADER_KEY, HEADER_VALUE); } - @BeforeClass + @BeforeAll public static void setUp() throws Exception { mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); diff --git a/api/src/test/java/com/alibaba/nacos/api/config/remote/request/ClientConfigMetricRequestTest.java b/api/src/test/java/com/alibaba/nacos/api/config/remote/request/ClientConfigMetricRequestTest.java index 38cf4c63b1b..4b19652f74e 100644 --- a/api/src/test/java/com/alibaba/nacos/api/config/remote/request/ClientConfigMetricRequestTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/config/remote/request/ClientConfigMetricRequestTest.java @@ -18,18 +18,17 @@ import com.alibaba.nacos.api.common.Constants; import com.fasterxml.jackson.core.JsonProcessingException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Objects; import static com.alibaba.nacos.api.config.remote.request.ClientConfigMetricRequest.MetricsKey.CACHE_DATA; import static com.alibaba.nacos.api.config.remote.request.ClientConfigMetricRequest.MetricsKey.SNAPSHOT_DATA; -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; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ClientConfigMetricRequestTest extends BasedConfigRequestTest { +class ClientConfigMetricRequestTest extends BasedConfigRequestTest { @Override @Test @@ -57,35 +56,36 @@ public void testDeserialize() throws JsonProcessingException { + "\"test_data+group+test_tenant\"},{\"type\":\"snapshotData\"," + "\"key\":\"test_data+group+test_tenant\"}],\"module\":\"config\"}"; ClientConfigMetricRequest actual = mapper.readValue(json, ClientConfigMetricRequest.class); - assertEquals(actual.getMetricsKeys().size(), 2); - assertEquals(actual.getModule(), Constants.Config.CONFIG_MODULE); - assertEquals(actual.getHeader(HEADER_KEY), HEADER_VALUE); + assertEquals(2, actual.getMetricsKeys().size()); + assertEquals(Constants.Config.CONFIG_MODULE, actual.getModule()); + assertEquals(HEADER_VALUE, actual.getHeader(HEADER_KEY)); } @Test - public void testMetricsKeysEquals() { + void testMetricsKeysEquals() { String dataKey = String.join("+", KEY); ClientConfigMetricRequest.MetricsKey key = ClientConfigMetricRequest.MetricsKey.build(CACHE_DATA, dataKey); assertEquals(key, key); - assertFalse(key.equals(null)); - assertFalse(key.equals(new ClientConfigMetricRequest())); - ClientConfigMetricRequest.MetricsKey newOne = ClientConfigMetricRequest.MetricsKey - .build(SNAPSHOT_DATA, dataKey); + assertNotEquals(null, key); + assertNotEquals(key, new ClientConfigMetricRequest()); + ClientConfigMetricRequest.MetricsKey newOne = ClientConfigMetricRequest.MetricsKey.build(SNAPSHOT_DATA, + dataKey); assertNotEquals(key, newOne); newOne.setType(CACHE_DATA); assertEquals(key, newOne); } @Test - public void testMetricsHashCode() { + void testMetricsHashCode() { String dataKey = String.join("+", KEY); ClientConfigMetricRequest.MetricsKey key = ClientConfigMetricRequest.MetricsKey.build(CACHE_DATA, dataKey); assertEquals(Objects.hash(CACHE_DATA, dataKey), key.hashCode()); } @Test - public void testMetricsToString() { - ClientConfigMetricRequest.MetricsKey key = ClientConfigMetricRequest.MetricsKey.build(CACHE_DATA, String.join("+", KEY)); + void testMetricsToString() { + ClientConfigMetricRequest.MetricsKey key = ClientConfigMetricRequest.MetricsKey.build(CACHE_DATA, + String.join("+", KEY)); assertEquals("MetricsKey{type='cacheData', key='test_data+group+test_tenant'}", key.toString()); } } diff --git a/api/src/test/java/com/alibaba/nacos/api/config/remote/request/ConfigBatchListenRequestTest.java b/api/src/test/java/com/alibaba/nacos/api/config/remote/request/ConfigBatchListenRequestTest.java index 9c85186d6f1..b40823515e5 100644 --- a/api/src/test/java/com/alibaba/nacos/api/config/remote/request/ConfigBatchListenRequestTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/config/remote/request/ConfigBatchListenRequestTest.java @@ -18,12 +18,12 @@ import com.alibaba.nacos.api.common.Constants; import com.fasterxml.jackson.core.JsonProcessingException; -import org.junit.Test; +import org.junit.jupiter.api.Test; -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 ConfigBatchListenRequestTest extends BasedConfigRequestTest { +class ConfigBatchListenRequestTest extends BasedConfigRequestTest { @Override @Test @@ -47,14 +47,14 @@ public void testDeserialize() throws JsonProcessingException { + "\"configListenContexts\":[{\"group\":\"group\",\"md5\":\"test_MD5\"," + "\"dataId\":\"test_data\",\"tenant\":\"test_tenant\"}],\"module\":\"config\"}"; ConfigBatchListenRequest actual = mapper.readValue(json, ConfigBatchListenRequest.class); - assertEquals(actual.isListen(), true); - assertEquals(actual.getModule(), Constants.Config.CONFIG_MODULE); - assertEquals(actual.getHeader(HEADER_KEY), HEADER_VALUE); - assertEquals(actual.getConfigListenContexts().size(), 1); + assertEquals(true, actual.isListen()); + assertEquals(Constants.Config.CONFIG_MODULE, actual.getModule()); + assertEquals(HEADER_VALUE, actual.getHeader(HEADER_KEY)); + assertEquals(1, actual.getConfigListenContexts().size()); } @Test - public void testConfigListenContextToString() { + void testConfigListenContextToString() { ConfigBatchListenRequest configBatchListenRequest = new ConfigBatchListenRequest(); configBatchListenRequest.addConfigListenContext(GROUP, DATA_ID, TENANT, MD5); assertEquals("ConfigListenContext{group='group', md5='test_MD5', dataId='test_data', tenant='test_tenant'}", diff --git a/api/src/test/java/com/alibaba/nacos/api/config/remote/request/ConfigChangeNotifyRequestTest.java b/api/src/test/java/com/alibaba/nacos/api/config/remote/request/ConfigChangeNotifyRequestTest.java index 2f64d3a83db..370d885eaa5 100644 --- a/api/src/test/java/com/alibaba/nacos/api/config/remote/request/ConfigChangeNotifyRequestTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/config/remote/request/ConfigChangeNotifyRequestTest.java @@ -18,20 +18,20 @@ import com.alibaba.nacos.api.common.Constants; import com.fasterxml.jackson.core.JsonProcessingException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -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 ConfigChangeNotifyRequestTest extends BasedConfigRequestTest { +class ConfigChangeNotifyRequestTest extends BasedConfigRequestTest { ConfigChangeNotifyRequest configChangeNotifyRequest; String requestId; - @Before - public void before() { + @BeforeEach + void before() { configChangeNotifyRequest = ConfigChangeNotifyRequest.build(DATA_ID, GROUP, TENANT); configChangeNotifyRequest.putAllHeader(HEADERS); requestId = injectRequestUuId(configChangeNotifyRequest); @@ -54,10 +54,10 @@ public void testDeserialize() throws JsonProcessingException { String json = "{\"headers\":{\"header1\":\"test_header1\"},\"dataId\":\"test_data\",\"group\":" + "\"group\",\"tenant\":\"test_tenant\",\"module\":\"config\"}"; ConfigChangeNotifyRequest actual = mapper.readValue(json, ConfigChangeNotifyRequest.class); - assertEquals(actual.getDataId(), DATA_ID); - assertEquals(actual.getGroup(), GROUP); - assertEquals(actual.getTenant(), TENANT); - assertEquals(actual.getModule(), Constants.Config.CONFIG_MODULE); - assertEquals(actual.getHeader(HEADER_KEY), HEADER_VALUE); + assertEquals(DATA_ID, actual.getDataId()); + assertEquals(GROUP, actual.getGroup()); + assertEquals(TENANT, actual.getTenant()); + assertEquals(Constants.Config.CONFIG_MODULE, actual.getModule()); + assertEquals(HEADER_VALUE, actual.getHeader(HEADER_KEY)); } } diff --git a/api/src/test/java/com/alibaba/nacos/api/config/remote/request/ConfigPublishRequestTest.java b/api/src/test/java/com/alibaba/nacos/api/config/remote/request/ConfigPublishRequestTest.java index 41e253b60d6..7dc214b7bca 100644 --- a/api/src/test/java/com/alibaba/nacos/api/config/remote/request/ConfigPublishRequestTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/config/remote/request/ConfigPublishRequestTest.java @@ -18,24 +18,24 @@ import com.alibaba.nacos.api.common.Constants; import com.fasterxml.jackson.core.JsonProcessingException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -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 ConfigPublishRequestTest extends BasedConfigRequestTest { - - ConfigPublishRequest configPublishRequest; +class ConfigPublishRequestTest extends BasedConfigRequestTest { private static final String TAG_PARAM = "tag"; private static final String APP_NAME_PARAM = "appName"; + ConfigPublishRequest configPublishRequest; + String requestId; - @Before - public void before() { + @BeforeEach + void before() { configPublishRequest = new ConfigPublishRequest(DATA_ID, GROUP, TENANT, CONTENT); configPublishRequest.putAdditionalParam(TAG_PARAM, TAG_PARAM); configPublishRequest.putAdditionalParam(APP_NAME_PARAM, APP_NAME_PARAM); @@ -64,13 +64,13 @@ public void testDeserialize() throws JsonProcessingException { + "\"tenant\":\"test_tenant\",\"content\":\"content\",\"casMd5\":\"test_MD5\"," + "\"additionMap\":{\"appName\":\"appName\",\"tag\":\"tag\"},\"module\":\"config\"}"; ConfigPublishRequest actual = mapper.readValue(json, ConfigPublishRequest.class); - assertEquals(actual.getDataId(), DATA_ID); - assertEquals(actual.getGroup(), GROUP); - assertEquals(actual.getTenant(), TENANT); - assertEquals(actual.getModule(), Constants.Config.CONFIG_MODULE); - assertEquals(actual.getContent(), CONTENT); - assertEquals(actual.getCasMd5(), MD5); - assertEquals(actual.getAdditionParam(TAG_PARAM), TAG_PARAM); - assertEquals(actual.getAdditionParam(APP_NAME_PARAM), APP_NAME_PARAM); + assertEquals(DATA_ID, actual.getDataId()); + assertEquals(GROUP, actual.getGroup()); + assertEquals(TENANT, actual.getTenant()); + assertEquals(Constants.Config.CONFIG_MODULE, actual.getModule()); + assertEquals(CONTENT, actual.getContent()); + assertEquals(MD5, actual.getCasMd5()); + assertEquals(TAG_PARAM, actual.getAdditionParam(TAG_PARAM)); + assertEquals(APP_NAME_PARAM, actual.getAdditionParam(APP_NAME_PARAM)); } } diff --git a/api/src/test/java/com/alibaba/nacos/api/config/remote/request/ConfigQueryRequestTest.java b/api/src/test/java/com/alibaba/nacos/api/config/remote/request/ConfigQueryRequestTest.java index c8350f11939..9fde8a18fd4 100644 --- a/api/src/test/java/com/alibaba/nacos/api/config/remote/request/ConfigQueryRequestTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/config/remote/request/ConfigQueryRequestTest.java @@ -18,16 +18,16 @@ import com.alibaba.nacos.api.common.Constants; import com.fasterxml.jackson.core.JsonProcessingException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.HashMap; 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 ConfigQueryRequestTest extends BasedConfigRequestTest { +class ConfigQueryRequestTest extends BasedConfigRequestTest { ConfigQueryRequest configQueryRequest; @@ -35,8 +35,8 @@ public class ConfigQueryRequestTest extends BasedConfigRequestTest { String requestId; - @Before - public void before() { + @BeforeEach + void before() { headers.put(Constants.Config.NOTIFY_HEADER, Boolean.TRUE.toString()); configQueryRequest = ConfigQueryRequest.build(DATA_ID, GROUP, TENANT); configQueryRequest.putAllHeader(headers); @@ -45,7 +45,7 @@ public void before() { } @Test - public void testIsNotify() { + void testIsNotify() { assertTrue(configQueryRequest.isNotify()); } @@ -67,10 +67,10 @@ public void testDeserialize() throws JsonProcessingException { String json = "{\"headers\":{\"notify\":\"true\"},\"dataId\":\"test_data\",\"group\":\"group\"," + "\"tenant\":\"test_tenant\",\"notify\":true,\"module\":\"config\",\"tag\":\"tag\"}"; ConfigQueryRequest actual = mapper.readValue(json, ConfigQueryRequest.class); - assertEquals(actual.getDataId(), DATA_ID); - assertEquals(actual.getGroup(), GROUP); - assertEquals(actual.getTenant(), TENANT); - assertEquals(actual.getTag(), TAG); - assertEquals(actual.getModule(), Constants.Config.CONFIG_MODULE); + assertEquals(DATA_ID, actual.getDataId()); + assertEquals(GROUP, actual.getGroup()); + assertEquals(TENANT, actual.getTenant()); + assertEquals(TAG, actual.getTag()); + assertEquals(Constants.Config.CONFIG_MODULE, actual.getModule()); } } diff --git a/api/src/test/java/com/alibaba/nacos/api/config/remote/request/ConfigRemoveRequestTest.java b/api/src/test/java/com/alibaba/nacos/api/config/remote/request/ConfigRemoveRequestTest.java index e5c97ad9f5c..054c5e53860 100644 --- a/api/src/test/java/com/alibaba/nacos/api/config/remote/request/ConfigRemoveRequestTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/config/remote/request/ConfigRemoveRequestTest.java @@ -18,20 +18,20 @@ import com.alibaba.nacos.api.common.Constants; import com.fasterxml.jackson.core.JsonProcessingException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -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 ConfigRemoveRequestTest extends BasedConfigRequestTest { +class ConfigRemoveRequestTest extends BasedConfigRequestTest { ConfigRemoveRequest configRemoveRequest; String requestId; - @Before - public void before() { + @BeforeEach + void before() { configRemoveRequest = new ConfigRemoveRequest(DATA_ID, GROUP, TENANT, TAG); requestId = injectRequestUuId(configRemoveRequest); @@ -56,10 +56,10 @@ public void testDeserialize() throws JsonProcessingException { String json = "{\"headers\":{},\"dataId\":\"test_data\",\"group\":\"group\",\"tenant\":\"test_tenant\"" + ",\"tag\":\"tag\",\"module\":\"config\"}"; ConfigRemoveRequest actual = mapper.readValue(json, ConfigRemoveRequest.class); - assertEquals(actual.getDataId(), DATA_ID); - assertEquals(actual.getGroup(), GROUP); - assertEquals(actual.getTenant(), TENANT); - assertEquals(actual.getModule(), Constants.Config.CONFIG_MODULE); - assertEquals(actual.getTag(), TAG); + assertEquals(DATA_ID, actual.getDataId()); + assertEquals(GROUP, actual.getGroup()); + assertEquals(TENANT, actual.getTenant()); + assertEquals(Constants.Config.CONFIG_MODULE, actual.getModule()); + assertEquals(TAG, actual.getTag()); } } diff --git a/api/src/test/java/com/alibaba/nacos/api/config/remote/request/cluster/ConfigChangeClusterSyncRequestTest.java b/api/src/test/java/com/alibaba/nacos/api/config/remote/request/cluster/ConfigChangeClusterSyncRequestTest.java index 6145eec4a3d..d1055c18c73 100644 --- a/api/src/test/java/com/alibaba/nacos/api/config/remote/request/cluster/ConfigChangeClusterSyncRequestTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/config/remote/request/cluster/ConfigChangeClusterSyncRequestTest.java @@ -19,20 +19,20 @@ import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.config.remote.request.BasedConfigRequestTest; import com.fasterxml.jackson.core.JsonProcessingException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -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 ConfigChangeClusterSyncRequestTest extends BasedConfigRequestTest { +class ConfigChangeClusterSyncRequestTest extends BasedConfigRequestTest { ConfigChangeClusterSyncRequest configChangeClusterSyncRequest; String requestId; - @Before - public void before() { + @BeforeEach + void before() { configChangeClusterSyncRequest = new ConfigChangeClusterSyncRequest(); configChangeClusterSyncRequest.setDataId(DATA_ID); configChangeClusterSyncRequest.setGroup(GROUP); @@ -64,15 +64,16 @@ public void testSerialize() throws JsonProcessingException { @Override @Test public void testDeserialize() throws JsonProcessingException { - String json = "{\"headers\":{\"header1\":\"test_header1\"},\"requestId\":\"ece89111-3c42-4055-aca4-c95e16ec564b\",\"dataId\":\"test_data\"," - + "\"group\":\"group\",\"tenant\":\"test_tenant\"," - + "\"tag\":\"tag\",\"lastModified\":0,\"beta\":true,\"module\":\"config\"}"; + String json = + "{\"headers\":{\"header1\":\"test_header1\"},\"requestId\":\"ece89111-3c42-4055-aca4-c95e16ec564b\",\"dataId\":\"test_data\"," + + "\"group\":\"group\",\"tenant\":\"test_tenant\"," + + "\"tag\":\"tag\",\"lastModified\":0,\"beta\":true,\"module\":\"config\"}"; ConfigChangeClusterSyncRequest actual = mapper.readValue(json, ConfigChangeClusterSyncRequest.class); - assertEquals(actual.getDataId(), DATA_ID); - assertEquals(actual.getGroup(), GROUP); - assertEquals(actual.getTenant(), TENANT); - assertEquals(actual.getModule(), Constants.Config.CONFIG_MODULE); - assertEquals(actual.getLastModified(), 0L); + assertEquals(DATA_ID, actual.getDataId()); + assertEquals(GROUP, actual.getGroup()); + assertEquals(TENANT, actual.getTenant()); + assertEquals(Constants.Config.CONFIG_MODULE, actual.getModule()); + assertEquals(0L, actual.getLastModified()); assertTrue(actual.isBeta()); } } diff --git a/api/src/test/java/com/alibaba/nacos/api/config/remote/response/ClientConfigMetricResponseTest.java b/api/src/test/java/com/alibaba/nacos/api/config/remote/response/ClientConfigMetricResponseTest.java index 66de71c4369..18b86c08a6d 100644 --- a/api/src/test/java/com/alibaba/nacos/api/config/remote/response/ClientConfigMetricResponseTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/config/remote/response/ClientConfigMetricResponseTest.java @@ -18,14 +18,14 @@ import com.alibaba.nacos.api.remote.response.ResponseCode; import com.fasterxml.jackson.core.JsonProcessingException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.HashMap; 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 ClientConfigMetricResponseTest extends BasedConfigResponseTest { @@ -33,8 +33,8 @@ public class ClientConfigMetricResponseTest extends BasedConfigResponseTest { Map metric = new HashMap<>(16); - @Before - public void before() { + @BeforeEach + void before() { metric.put("m1", "v1"); clientConfigMetricResponse = new ClientConfigMetricResponse(); clientConfigMetricResponse.setMetrics(metric); diff --git a/api/src/test/java/com/alibaba/nacos/api/config/remote/response/ConfigChangeBatchListenResponseTest.java b/api/src/test/java/com/alibaba/nacos/api/config/remote/response/ConfigChangeBatchListenResponseTest.java index 54e068eaefe..de56fb71064 100644 --- a/api/src/test/java/com/alibaba/nacos/api/config/remote/response/ConfigChangeBatchListenResponseTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/config/remote/response/ConfigChangeBatchListenResponseTest.java @@ -18,18 +18,18 @@ import com.alibaba.nacos.api.remote.response.ResponseCode; import com.fasterxml.jackson.core.JsonProcessingException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -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 ConfigChangeBatchListenResponseTest extends BasedConfigResponseTest { +class ConfigChangeBatchListenResponseTest extends BasedConfigResponseTest { ConfigChangeBatchListenResponse configChangeBatchListenResponse; - @Before - public void before() { + @BeforeEach + void before() { configChangeBatchListenResponse = new ConfigChangeBatchListenResponse(); requestId = injectResponseUuId(configChangeBatchListenResponse); configChangeBatchListenResponse.addChangeConfig(DATA_ID, GROUP, TENANT); @@ -50,8 +50,8 @@ public void testSerializeSuccessResponse() throws JsonProcessingException { @Override @Test public void testSerializeFailResponse() throws JsonProcessingException { - ConfigChangeBatchListenResponse configChangeBatchListenResponse = ConfigChangeBatchListenResponse - .buildFailResponse("Fail"); + ConfigChangeBatchListenResponse configChangeBatchListenResponse = ConfigChangeBatchListenResponse.buildFailResponse( + "Fail"); String json = mapper.writeValueAsString(configChangeBatchListenResponse); assertTrue(json.contains("\"resultCode\":" + ResponseCode.FAIL.getCode())); assertTrue(json.contains("\"errorCode\":0")); diff --git a/api/src/test/java/com/alibaba/nacos/api/config/remote/response/ConfigChangeNotifyResponseTest.java b/api/src/test/java/com/alibaba/nacos/api/config/remote/response/ConfigChangeNotifyResponseTest.java index 77c67353938..8c84f2b0d67 100644 --- a/api/src/test/java/com/alibaba/nacos/api/config/remote/response/ConfigChangeNotifyResponseTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/config/remote/response/ConfigChangeNotifyResponseTest.java @@ -18,17 +18,17 @@ import com.alibaba.nacos.api.remote.response.ResponseCode; import com.fasterxml.jackson.core.JsonProcessingException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ConfigChangeNotifyResponseTest extends BasedConfigResponseTest { ConfigChangeNotifyResponse configChangeNotifyResponse; - @Before - public void before() { + @BeforeEach + void before() { configChangeNotifyResponse = new ConfigChangeNotifyResponse(); requestId = injectResponseUuId(configChangeNotifyResponse); } @@ -41,7 +41,7 @@ public void testSerializeSuccessResponse() throws JsonProcessingException { assertTrue(json.contains("\"requestId\":\"" + requestId)); assertTrue(json.contains("\"resultCode\":" + ResponseCode.SUCCESS.getCode())); assertTrue(json.contains("\"errorCode\":0")); - + } @Override diff --git a/api/src/test/java/com/alibaba/nacos/api/config/remote/response/ConfigPublishResponseTest.java b/api/src/test/java/com/alibaba/nacos/api/config/remote/response/ConfigPublishResponseTest.java index 551db99c8bb..4aa69a6d8d0 100644 --- a/api/src/test/java/com/alibaba/nacos/api/config/remote/response/ConfigPublishResponseTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/config/remote/response/ConfigPublishResponseTest.java @@ -18,17 +18,17 @@ import com.alibaba.nacos.api.remote.response.ResponseCode; import com.fasterxml.jackson.core.JsonProcessingException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ConfigPublishResponseTest extends BasedConfigResponseTest { +class ConfigPublishResponseTest extends BasedConfigResponseTest { ConfigPublishResponse configPublishResponse; - @Before - public void before() { + @BeforeEach + void before() { configPublishResponse = ConfigPublishResponse.buildSuccessResponse(); requestId = injectResponseUuId(configPublishResponse); } diff --git a/api/src/test/java/com/alibaba/nacos/api/config/remote/response/ConfigQueryResponseTest.java b/api/src/test/java/com/alibaba/nacos/api/config/remote/response/ConfigQueryResponseTest.java index dae2c1528ad..e0574dc152b 100644 --- a/api/src/test/java/com/alibaba/nacos/api/config/remote/response/ConfigQueryResponseTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/config/remote/response/ConfigQueryResponseTest.java @@ -18,18 +18,18 @@ import com.alibaba.nacos.api.remote.response.ResponseCode; import com.fasterxml.jackson.core.JsonProcessingException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -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 ConfigQueryResponseTest extends BasedConfigResponseTest { +class ConfigQueryResponseTest extends BasedConfigResponseTest { ConfigQueryResponse configQueryResponse; - @Before - public void before() { + @BeforeEach + void before() { configQueryResponse = ConfigQueryResponse.buildSuccessResponse("success"); configQueryResponse.setContentType("text"); configQueryResponse.setEncryptedDataKey("encryptedKey"); diff --git a/api/src/test/java/com/alibaba/nacos/api/config/remote/response/ConfigRemoveResponseTest.java b/api/src/test/java/com/alibaba/nacos/api/config/remote/response/ConfigRemoveResponseTest.java index 68c4f42d467..6b735f41235 100644 --- a/api/src/test/java/com/alibaba/nacos/api/config/remote/response/ConfigRemoveResponseTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/config/remote/response/ConfigRemoveResponseTest.java @@ -18,17 +18,17 @@ import com.alibaba.nacos.api.remote.response.ResponseCode; import com.fasterxml.jackson.core.JsonProcessingException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ConfigRemoveResponseTest extends BasedConfigResponseTest { +class ConfigRemoveResponseTest extends BasedConfigResponseTest { ConfigRemoveResponse configRemoveResponse; - @Before - public void before() { + @BeforeEach + void before() { configRemoveResponse = ConfigRemoveResponse.buildSuccessResponse(); requestId = injectResponseUuId(configRemoveResponse); } diff --git a/api/src/test/java/com/alibaba/nacos/api/config/remote/response/cluster/ConfigChangeClusterSyncResponseTest.java b/api/src/test/java/com/alibaba/nacos/api/config/remote/response/cluster/ConfigChangeClusterSyncResponseTest.java index 949f404680a..b75054f4102 100644 --- a/api/src/test/java/com/alibaba/nacos/api/config/remote/response/cluster/ConfigChangeClusterSyncResponseTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/config/remote/response/cluster/ConfigChangeClusterSyncResponseTest.java @@ -19,17 +19,17 @@ import com.alibaba.nacos.api.config.remote.response.BasedConfigResponseTest; import com.alibaba.nacos.api.remote.response.ResponseCode; import com.fasterxml.jackson.core.JsonProcessingException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ConfigChangeClusterSyncResponseTest extends BasedConfigResponseTest { ConfigChangeClusterSyncResponse configChangeClusterSyncResponse; - @Before - public void before() { + @BeforeEach + void before() { configChangeClusterSyncResponse = new ConfigChangeClusterSyncResponse(); requestId = injectResponseUuId(configChangeClusterSyncResponse); } diff --git a/api/src/test/java/com/alibaba/nacos/api/exception/NacosExceptionTest.java b/api/src/test/java/com/alibaba/nacos/api/exception/NacosExceptionTest.java index d70c7b4f373..7d43cf5ee80 100644 --- a/api/src/test/java/com/alibaba/nacos/api/exception/NacosExceptionTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/exception/NacosExceptionTest.java @@ -17,14 +17,14 @@ package com.alibaba.nacos.api.exception; import com.alibaba.nacos.api.common.Constants; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class NacosExceptionTest { +class NacosExceptionTest { @Test - public void testEmptyConstructor() { + void testEmptyConstructor() { NacosException exception = new NacosException(); assertEquals(0, exception.getErrCode()); assertEquals(Constants.NULL, exception.getErrMsg()); @@ -35,7 +35,7 @@ public void testEmptyConstructor() { } @Test - public void testConstructorWithErrMsg() { + void testConstructorWithErrMsg() { NacosException exception = new NacosException(NacosException.SERVER_ERROR, "test"); assertEquals(NacosException.SERVER_ERROR, exception.getErrCode()); assertEquals("test", exception.getErrMsg()); @@ -43,7 +43,7 @@ public void testConstructorWithErrMsg() { } @Test - public void testConstructorWithCause() { + void testConstructorWithCause() { NacosException exception = new NacosException(NacosException.SERVER_ERROR, new RuntimeException("cause test")); assertEquals(NacosException.SERVER_ERROR, exception.getErrCode()); assertEquals("cause test", exception.getErrMsg()); @@ -51,7 +51,7 @@ public void testConstructorWithCause() { } @Test - public void testConstructorWithMultiCauses() { + void testConstructorWithMultiCauses() { NacosException exception = new NacosException(NacosException.SERVER_ERROR, new RuntimeException("cause test", new RuntimeException("multi"))); assertEquals(NacosException.SERVER_ERROR, exception.getErrCode()); @@ -60,7 +60,7 @@ public void testConstructorWithMultiCauses() { } @Test - public void testConstructorWithFull() { + void testConstructorWithFull() { NacosException exception = new NacosException(NacosException.SERVER_ERROR, "test", new RuntimeException("cause test")); assertEquals(NacosException.SERVER_ERROR, exception.getErrCode()); diff --git a/api/src/test/java/com/alibaba/nacos/api/exception/api/NacosApiExceptionTest.java b/api/src/test/java/com/alibaba/nacos/api/exception/api/NacosApiExceptionTest.java index 36e3920fe0b..9be5d98e635 100644 --- a/api/src/test/java/com/alibaba/nacos/api/exception/api/NacosApiExceptionTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/exception/api/NacosApiExceptionTest.java @@ -18,14 +18,14 @@ import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.model.v2.ErrorCode; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class NacosApiExceptionTest { +class NacosApiExceptionTest { @Test - public void testEmptyConstructor() { + void testEmptyConstructor() { NacosApiException exception = new NacosApiException(); assertEquals(0, exception.getErrCode()); assertEquals(0, exception.getDetailErrCode()); @@ -34,7 +34,7 @@ public void testEmptyConstructor() { } @Test - public void testConstructorWithoutCause() { + void testConstructorWithoutCause() { NacosApiException exception = new NacosApiException(500, ErrorCode.SERVER_ERROR, "test"); assertEquals(500, exception.getErrCode()); assertEquals(ErrorCode.SERVER_ERROR.getCode().intValue(), exception.getDetailErrCode()); @@ -43,7 +43,7 @@ public void testConstructorWithoutCause() { } @Test - public void testConstructorWithCause() { + void testConstructorWithCause() { NacosApiException exception = new NacosApiException(500, ErrorCode.SERVER_ERROR, new RuntimeException("cause test"), "test"); assertEquals(500, exception.getErrCode()); diff --git a/api/src/test/java/com/alibaba/nacos/api/exception/runtime/NacosDeserializationExceptionTest.java b/api/src/test/java/com/alibaba/nacos/api/exception/runtime/NacosDeserializationExceptionTest.java index 612ba9d7c34..e4922acb524 100644 --- a/api/src/test/java/com/alibaba/nacos/api/exception/runtime/NacosDeserializationExceptionTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/exception/runtime/NacosDeserializationExceptionTest.java @@ -18,17 +18,17 @@ import com.alibaba.nacos.api.common.Constants; import com.fasterxml.jackson.databind.type.SimpleType; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.lang.reflect.Type; -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; -public class NacosDeserializationExceptionTest { +class NacosDeserializationExceptionTest { @Test - public void testEmptyConstructor() { + void testEmptyConstructor() { NacosDeserializationException exception = new NacosDeserializationException(); assertEquals(Constants.Exception.DESERIALIZE_ERROR_CODE, exception.getErrCode()); assertNull(exception.getMessage()); @@ -36,7 +36,7 @@ public void testEmptyConstructor() { } @Test - public void testConstructorWithTargetClass() { + void testConstructorWithTargetClass() { NacosDeserializationException exception = new NacosDeserializationException( NacosDeserializationExceptionTest.class); assertEquals(Constants.Exception.DESERIALIZE_ERROR_CODE, exception.getErrCode()); @@ -46,7 +46,7 @@ public void testConstructorWithTargetClass() { } @Test - public void testConstructorWithTargetType() { + void testConstructorWithTargetType() { Type type = SimpleType.constructUnsafe(NacosDeserializationExceptionTest.class); NacosDeserializationException exception = new NacosDeserializationException(type); assertEquals(Constants.Exception.DESERIALIZE_ERROR_CODE, exception.getErrCode()); @@ -57,7 +57,7 @@ public void testConstructorWithTargetType() { } @Test - public void testConstructorWithCause() { + void testConstructorWithCause() { NacosDeserializationException exception = new NacosDeserializationException(new RuntimeException("test")); assertEquals(Constants.Exception.DESERIALIZE_ERROR_CODE, exception.getErrCode()); assertEquals("errCode: 101, errMsg: Nacos deserialize failed. ", exception.getMessage()); @@ -65,7 +65,7 @@ public void testConstructorWithCause() { } @Test - public void testConstructorWithTargetClassAndCause() { + void testConstructorWithTargetClassAndCause() { NacosDeserializationException exception = new NacosDeserializationException( NacosDeserializationExceptionTest.class, new RuntimeException("test")); assertEquals(Constants.Exception.DESERIALIZE_ERROR_CODE, exception.getErrCode()); @@ -75,7 +75,7 @@ public void testConstructorWithTargetClassAndCause() { } @Test - public void testConstructorWithTargetTypeAndCause() { + void testConstructorWithTargetTypeAndCause() { Type type = SimpleType.constructUnsafe(NacosDeserializationExceptionTest.class); NacosDeserializationException exception = new NacosDeserializationException(type, new RuntimeException("test")); assertEquals(Constants.Exception.DESERIALIZE_ERROR_CODE, exception.getErrCode()); diff --git a/api/src/test/java/com/alibaba/nacos/api/exception/runtime/NacosLoadExceptionTest.java b/api/src/test/java/com/alibaba/nacos/api/exception/runtime/NacosLoadExceptionTest.java index 3311852e980..3be1a4964ea 100644 --- a/api/src/test/java/com/alibaba/nacos/api/exception/runtime/NacosLoadExceptionTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/exception/runtime/NacosLoadExceptionTest.java @@ -16,15 +16,15 @@ package com.alibaba.nacos.api.exception.runtime; -import org.junit.Test; +import org.junit.jupiter.api.Test; -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; -public class NacosLoadExceptionTest { +class NacosLoadExceptionTest { @Test - public void testConstructor() { + void testConstructor() { NacosLoadException exception = new NacosLoadException("test"); assertEquals("test", exception.getMessage()); assertNull(exception.getCause()); diff --git a/api/src/test/java/com/alibaba/nacos/api/exception/runtime/NacosRuntimeExceptionTest.java b/api/src/test/java/com/alibaba/nacos/api/exception/runtime/NacosRuntimeExceptionTest.java index 5ea20081a2b..8e534811336 100644 --- a/api/src/test/java/com/alibaba/nacos/api/exception/runtime/NacosRuntimeExceptionTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/exception/runtime/NacosRuntimeExceptionTest.java @@ -17,16 +17,16 @@ package com.alibaba.nacos.api.exception.runtime; import com.alibaba.nacos.api.exception.NacosException; -import org.junit.Test; +import org.junit.jupiter.api.Test; -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; -public class NacosRuntimeExceptionTest { +class NacosRuntimeExceptionTest { @Test - public void testConstructorWithErrorCode() { + void testConstructorWithErrorCode() { NacosRuntimeException exception = new NacosRuntimeException(NacosException.INVALID_PARAM); assertEquals(NacosException.INVALID_PARAM, exception.getErrCode()); assertNull(exception.getMessage()); @@ -34,7 +34,7 @@ public void testConstructorWithErrorCode() { } @Test - public void testConstructorWithErrorCodeAndMsg() { + void testConstructorWithErrorCodeAndMsg() { NacosRuntimeException exception = new NacosRuntimeException(NacosException.INVALID_PARAM, "test"); assertEquals(NacosException.INVALID_PARAM, exception.getErrCode()); assertEquals("errCode: 400, errMsg: test ", exception.getMessage()); @@ -42,7 +42,7 @@ public void testConstructorWithErrorCodeAndMsg() { } @Test - public void testConstructorWithErrorCodeAndCause() { + void testConstructorWithErrorCodeAndCause() { NacosRuntimeException exception = new NacosRuntimeException(NacosException.INVALID_PARAM, new RuntimeException("test")); assertEquals(NacosException.INVALID_PARAM, exception.getErrCode()); @@ -51,9 +51,9 @@ public void testConstructorWithErrorCodeAndCause() { } @Test - public void testConstructorWithFull() { - NacosRuntimeException exception = new NacosRuntimeException(NacosException.INVALID_PARAM, - "test", new RuntimeException("cause test")); + void testConstructorWithFull() { + NacosRuntimeException exception = new NacosRuntimeException(NacosException.INVALID_PARAM, "test", + new RuntimeException("cause test")); assertEquals(NacosException.INVALID_PARAM, exception.getErrCode()); assertEquals("errCode: 400, errMsg: test ", exception.getMessage()); assertTrue(exception.getCause() instanceof RuntimeException); diff --git a/api/src/test/java/com/alibaba/nacos/api/exception/runtime/NacosSerializationExceptionTest.java b/api/src/test/java/com/alibaba/nacos/api/exception/runtime/NacosSerializationExceptionTest.java index da4b0e6793d..fd7b2850a0e 100644 --- a/api/src/test/java/com/alibaba/nacos/api/exception/runtime/NacosSerializationExceptionTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/exception/runtime/NacosSerializationExceptionTest.java @@ -17,15 +17,15 @@ package com.alibaba.nacos.api.exception.runtime; import com.alibaba.nacos.api.common.Constants; -import org.junit.Test; +import org.junit.jupiter.api.Test; -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; -public class NacosSerializationExceptionTest { +class NacosSerializationExceptionTest { @Test - public void testEmptyConstructor() { + void testEmptyConstructor() { NacosSerializationException exception = new NacosSerializationException(); assertEquals(Constants.Exception.SERIALIZE_ERROR_CODE, exception.getErrCode()); assertNull(exception.getMessage()); @@ -33,7 +33,7 @@ public void testEmptyConstructor() { } @Test - public void testConstructorWithSerializedClass() { + void testConstructorWithSerializedClass() { NacosSerializationException exception = new NacosSerializationException(NacosSerializationExceptionTest.class); assertEquals(Constants.Exception.SERIALIZE_ERROR_CODE, exception.getErrCode()); assertEquals(String.format("errCode: 100, errMsg: Nacos serialize for class [%s] failed. ", @@ -42,7 +42,7 @@ public void testConstructorWithSerializedClass() { } @Test - public void testConstructorWithCause() { + void testConstructorWithCause() { NacosSerializationException exception = new NacosSerializationException(new RuntimeException("test")); assertEquals(Constants.Exception.SERIALIZE_ERROR_CODE, exception.getErrCode()); assertEquals("errCode: 100, errMsg: Nacos serialize failed. ", exception.getMessage()); @@ -50,7 +50,7 @@ public void testConstructorWithCause() { } @Test - public void testConstructorWithSerializedClassAndCause() { + void testConstructorWithSerializedClassAndCause() { NacosSerializationException exception = new NacosSerializationException(NacosSerializationExceptionTest.class, new RuntimeException("test")); assertEquals(Constants.Exception.SERIALIZE_ERROR_CODE, exception.getErrCode()); diff --git a/api/src/test/java/com/alibaba/nacos/api/model/v2/ErrorCodeTest.java b/api/src/test/java/com/alibaba/nacos/api/model/v2/ErrorCodeTest.java index 3c61881135f..737c7a451cb 100644 --- a/api/src/test/java/com/alibaba/nacos/api/model/v2/ErrorCodeTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/model/v2/ErrorCodeTest.java @@ -16,16 +16,17 @@ package com.alibaba.nacos.api.model.v2; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; import java.util.HashSet; import java.util.Set; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class ErrorCodeTest { +class ErrorCodeTest { + @Test - public void testCodeNotSame() { + void testCodeNotSame() { Class errorCodeClass = ErrorCode.class; ErrorCode[] errorCodes = errorCodeClass.getEnumConstants(); diff --git a/api/src/test/java/com/alibaba/nacos/api/model/v2/ResultTest.java b/api/src/test/java/com/alibaba/nacos/api/model/v2/ResultTest.java index a67203eb1f6..18444cdf027 100644 --- a/api/src/test/java/com/alibaba/nacos/api/model/v2/ResultTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/model/v2/ResultTest.java @@ -16,15 +16,15 @@ package com.alibaba.nacos.api.model.v2; -import org.junit.Test; +import org.junit.jupiter.api.Test; -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; -public class ResultTest { +class ResultTest { @Test - public void testSuccessEmptyResult() { + void testSuccessEmptyResult() { Result result = Result.success(); assertNull(result.getData()); assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode()); @@ -32,7 +32,7 @@ public void testSuccessEmptyResult() { } @Test - public void testSuccessWithData() { + void testSuccessWithData() { Result result = Result.success("test"); assertEquals("test", result.getData()); assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode()); @@ -40,7 +40,7 @@ public void testSuccessWithData() { } @Test - public void testFailureMessageResult() { + void testFailureMessageResult() { Result result = Result.failure("test"); assertNull(result.getData()); assertEquals(ErrorCode.SERVER_ERROR.getCode(), result.getCode()); @@ -48,7 +48,7 @@ public void testFailureMessageResult() { } @Test - public void testFailureWithoutData() { + void testFailureWithoutData() { Result result = Result.failure(ErrorCode.DATA_ACCESS_ERROR); assertNull(result.getData()); assertEquals(ErrorCode.DATA_ACCESS_ERROR.getCode(), result.getCode()); @@ -56,7 +56,7 @@ public void testFailureWithoutData() { } @Test - public void testFailureWithData() { + void testFailureWithData() { Result result = Result.failure(ErrorCode.DATA_ACCESS_ERROR, "error"); assertEquals("error", result.getData()); assertEquals(ErrorCode.DATA_ACCESS_ERROR.getCode(), result.getCode()); @@ -64,7 +64,7 @@ public void testFailureWithData() { } @Test - public void testToString() { + void testToString() { Result result = Result.success("test"); assertEquals("Result{errorCode=0, message='success', data=test}", result.toString()); } diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/ability/ClientNamingAbilityTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/ability/ClientNamingAbilityTest.java index 4dd6dd79c0c..1a3b971aa81 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/ability/ClientNamingAbilityTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/ability/ClientNamingAbilityTest.java @@ -16,15 +16,15 @@ package com.alibaba.nacos.api.naming.ability; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ClientNamingAbilityTest { +class ClientNamingAbilityTest { @Test - public void testGetAndSet() { + void testGetAndSet() { ClientNamingAbility ability = new ClientNamingAbility(); assertFalse(ability.isSupportDeltaPush()); assertFalse(ability.isSupportRemoteMetric()); diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/ability/ServerNamingAbilityTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/ability/ServerNamingAbilityTest.java index 978b41f9988..4221972e3d6 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/ability/ServerNamingAbilityTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/ability/ServerNamingAbilityTest.java @@ -20,34 +20,33 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +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.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; -public class ServerNamingAbilityTest { +class ServerNamingAbilityTest { private static ObjectMapper jacksonMapper; - @BeforeClass - public static void setUpClass() throws Exception { + @BeforeAll + static void setUpClass() throws Exception { jacksonMapper = new ObjectMapper(); jacksonMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); jacksonMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } @Test - public void testDeserializeServerNamingAbilityForNonExistItem() throws JsonProcessingException { + void testDeserializeServerNamingAbilityForNonExistItem() throws JsonProcessingException { String nonExistItemJson = "{\"exampleAbility\":false}"; ServerNamingAbility actual = jacksonMapper.readValue(nonExistItemJson, ServerNamingAbility.class); assertFalse(actual.isSupportJraft()); } @Test - public void testEquals() throws JsonProcessingException { + void testEquals() throws JsonProcessingException { ServerNamingAbility expected = new ServerNamingAbility(); expected.setSupportJraft(true); String serializeJson = jacksonMapper.writeValueAsString(expected); @@ -60,19 +59,19 @@ public void testEquals() throws JsonProcessingException { } @Test - public void testEqualsForOneObject() { + void testEqualsForOneObject() { ServerNamingAbility ability = new ServerNamingAbility(); - assertTrue(ability.equals(ability)); + assertEquals(ability, ability); } @Test - public void testEqualsForOtherAbility() { + void testEqualsForOtherAbility() { ServerNamingAbility ability = new ServerNamingAbility(); - assertFalse(ability.equals(new ClientNamingAbility())); + assertNotEquals(ability, new ClientNamingAbility()); } @Test - public void testHashCode() throws JsonProcessingException { + void testHashCode() throws JsonProcessingException { ServerNamingAbility expected = new ServerNamingAbility(); expected.setSupportJraft(true); String serializeJson = jacksonMapper.writeValueAsString(expected); diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/listener/NamingEventTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/listener/NamingEventTest.java index c2a6076ff72..e918533e5f8 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/listener/NamingEventTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/listener/NamingEventTest.java @@ -16,26 +16,26 @@ package com.alibaba.nacos.api.naming.listener; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Collections; -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; -public class NamingEventTest { +class NamingEventTest { private MockNamingEventListener eventListener; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { eventListener = new MockNamingEventListener(); } @Test - public void testNamingEventWithSimpleConstructor() { + void testNamingEventWithSimpleConstructor() { NamingEvent event = new NamingEvent("serviceName", Collections.EMPTY_LIST); assertEquals("serviceName", event.getServiceName()); assertNull(event.getGroupName()); @@ -49,7 +49,7 @@ public void testNamingEventWithSimpleConstructor() { } @Test - public void testNamingEventWithFullConstructor() { + void testNamingEventWithFullConstructor() { NamingEvent event = new NamingEvent("serviceName", "group", "clusters", Collections.EMPTY_LIST); assertEquals("serviceName", event.getServiceName()); assertEquals("group", event.getGroupName()); diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/ClusterTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/ClusterTest.java index 6cc8a204eeb..69910bd2806 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/ClusterTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/ClusterTest.java @@ -22,29 +22,29 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +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.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; -public class ClusterTest { +class ClusterTest { private static ObjectMapper mapper; - @BeforeClass - public static void setUp() throws Exception { + @BeforeAll + static void setUp() throws Exception { mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } @Test - public void testSetAndGet() { + void testSetAndGet() { Cluster actual = new Cluster(); assertNull(actual.getName()); assertNull(actual.getServiceName()); @@ -72,7 +72,7 @@ public void testSetAndGet() { } @Test - public void testJsonSerialize() throws JsonProcessingException { + void testJsonSerialize() throws JsonProcessingException { Cluster actual = new Cluster("cluster"); actual.setServiceName("group@@service"); actual.setHealthChecker(new Http()); @@ -91,7 +91,7 @@ public void testJsonSerialize() throws JsonProcessingException { } @Test - public void testJsonDeserialize() throws JsonProcessingException { + void testJsonDeserialize() throws JsonProcessingException { String json = "{\"serviceName\":\"group@@service\",\"name\":\"cluster\"," + "\"healthChecker\":{\"type\":\"HTTP\",\"path\":\"\",\"headers\":\"\",\"expectedResponseCode\":200}," + "\"defaultPort\":81,\"defaultCheckPort\":82,\"useIPPort4Check\":false,\"metadata\":{\"a\":\"a\"}}"; diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/InstanceTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/InstanceTest.java index 441db368754..07726d07840 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/InstanceTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/InstanceTest.java @@ -22,30 +22,31 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.HashMap; -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.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class InstanceTest { +class InstanceTest { private static ObjectMapper mapper; - @BeforeClass - public static void setUp() throws Exception { + @BeforeAll + static void setUp() throws Exception { mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } @Test - public void testSetAndGet() { + void testSetAndGet() { Instance instance = new Instance(); assertNull(instance.getInstanceId()); assertNull(instance.getIp()); @@ -62,7 +63,7 @@ public void testSetAndGet() { } @Test - public void testJsonSerialize() throws JsonProcessingException { + void testJsonSerialize() throws JsonProcessingException { Instance instance = new Instance(); setInstance(instance); String actual = mapper.writeValueAsString(instance); @@ -82,7 +83,7 @@ public void testJsonSerialize() throws JsonProcessingException { } @Test - public void testJsonDeserialize() throws JsonProcessingException { + void testJsonDeserialize() throws JsonProcessingException { String json = "{\"instanceId\":\"id\",\"ip\":\"1.1.1.1\",\"port\":1000,\"weight\":100.0,\"healthy\":false," + "\"enabled\":false,\"ephemeral\":false,\"clusterName\":\"cluster\"," + "\"serviceName\":\"group@@serviceName\",\"metadata\":{\"a\":\"b\"},\"instanceHeartBeatInterval\":5000," @@ -92,21 +93,21 @@ public void testJsonDeserialize() throws JsonProcessingException { } @Test - public void testCheckClusterNameFormat() { + void testCheckClusterNameFormat() { Instance instance = new Instance(); instance.setClusterName("demo"); assertEquals("demo", instance.getClusterName()); } @Test - public void testToInetAddr() { + void testToInetAddr() { Instance instance = new Instance(); setInstance(instance); assertEquals("1.1.1.1:1000", instance.toInetAddr()); } @Test - public void testContainsMetadata() { + void testContainsMetadata() { Instance instance = new Instance(); assertFalse(instance.containsMetadata("a")); instance.setMetadata(null); @@ -116,7 +117,7 @@ public void testContainsMetadata() { } @Test - public void testGetInstanceIdGenerator() { + void testGetInstanceIdGenerator() { Instance instance = new Instance(); assertEquals(Constants.DEFAULT_INSTANCE_ID_GENERATOR, instance.getInstanceIdGenerator()); instance.addMetadata(PreservedMetadataKeys.INSTANCE_ID_GENERATOR, "test"); @@ -124,19 +125,19 @@ public void testGetInstanceIdGenerator() { } @Test - public void testEquals() { + void testEquals() { Instance actual = new Instance(); setInstance(actual); actual.setMetadata(new HashMap<>()); actual.addMetadata("a", "b"); - assertFalse(actual.equals(new Object())); + assertNotEquals(actual, new Object()); Instance expected = new Instance(); setInstance(expected); expected.setMetadata(new HashMap<>()); expected.addMetadata("a", "b"); - assertTrue(actual.equals(expected)); + assertEquals(actual, expected); expected.addMetadata("a", "c"); - assertFalse(actual.equals(expected)); + assertNotEquals(actual, expected); } private void setInstance(Instance instance) { diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/ListViewTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/ListViewTest.java index 562bb71cd87..a4a6b574f27 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/ListViewTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/ListViewTest.java @@ -16,19 +16,19 @@ package com.alibaba.nacos.api.naming.pojo; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.LinkedList; 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; -public class ListViewTest { +class ListViewTest { @Test - public void testToString() { + void testToString() { List data = new LinkedList<>(); data.add("1"); data.add("2"); @@ -41,7 +41,7 @@ public void testToString() { } @Test - public void testSetAndGet() { + void testSetAndGet() { ListView listView = new ListView<>(); assertEquals(0, listView.getCount()); assertNull(listView.getData()); diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/ServiceInfoTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/ServiceInfoTest.java index 271431800eb..4ff58f9382c 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/ServiceInfoTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/ServiceInfoTest.java @@ -20,8 +20,8 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.UnsupportedEncodingException; @@ -30,25 +30,26 @@ import java.util.LinkedList; import java.util.List; -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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ServiceInfoTest { +class ServiceInfoTest { private ObjectMapper mapper; private ServiceInfo serviceInfo; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); serviceInfo = new ServiceInfo("G@@testName", "testClusters"); } @Test - public void testSerialize() throws JsonProcessingException { + void testSerialize() throws JsonProcessingException { String actual = mapper.writeValueAsString(serviceInfo); assertTrue(actual.contains("\"name\":\"G@@testName\"")); assertTrue(actual.contains("\"clusters\":\"testClusters\"")); @@ -64,7 +65,7 @@ public void testSerialize() throws JsonProcessingException { } @Test - public void testDeserialize() throws IOException { + void testDeserialize() throws IOException { String example = "{\"name\":\"G@@testName\",\"clusters\":\"testClusters\",\"cacheMillis\":1000,\"hosts\":[]," + "\"lastRefTime\":0,\"checksum\":\"\",\"allIPs\":false,\"valid\":true,\"groupName\":\"\"}"; ServiceInfo actual = mapper.readValue(example, ServiceInfo.class); @@ -82,14 +83,14 @@ public void testDeserialize() throws IOException { } @Test - public void testGetKey() { + void testGetKey() { String key = serviceInfo.getKey(); assertEquals("G@@testName@@testClusters", key); assertEquals("G@@testName@@testClusters", serviceInfo.toString()); } @Test - public void testGetKeyEncode() { + void testGetKeyEncode() { String key = serviceInfo.getKeyEncoded(); String encodeName = null; try { @@ -101,7 +102,7 @@ public void testGetKeyEncode() { } @Test - public void testServiceInfoConstructor() { + void testServiceInfoConstructor() { String key1 = "group@@name"; String key2 = "group@@name@@c2"; ServiceInfo s1 = new ServiceInfo(key1); @@ -110,32 +111,34 @@ public void testServiceInfoConstructor() { assertEquals(key2, s2.getKey()); } - @Test(expected = IllegalArgumentException.class) - public void testServiceInfoConstructorWithError() { - String key1 = "name"; - ServiceInfo s1 = new ServiceInfo(key1); + @Test + void testServiceInfoConstructorWithError() { + assertThrows(IllegalArgumentException.class, () -> { + String key1 = "name"; + ServiceInfo s1 = new ServiceInfo(key1); + }); } @Test - public void testValidateForAllIps() { + void testValidateForAllIps() { serviceInfo.setAllIPs(true); assertTrue(serviceInfo.validate()); } @Test - public void testValidateForNullHosts() { + void testValidateForNullHosts() { serviceInfo.setHosts(null); assertFalse(serviceInfo.validate()); } @Test - public void testValidateForEmptyHosts() { + void testValidateForEmptyHosts() { serviceInfo.setHosts(Collections.EMPTY_LIST); assertFalse(serviceInfo.validate()); } @Test - public void testValidateForUnhealthyHosts() { + void testValidateForUnhealthyHosts() { Instance instance = new Instance(); instance.setHealthy(false); serviceInfo.addHost(instance); @@ -143,7 +146,7 @@ public void testValidateForUnhealthyHosts() { } @Test - public void testValidateForBothUnhealthyAndHealthyHosts() { + void testValidateForBothUnhealthyAndHealthyHosts() { List instanceList = new LinkedList<>(); Instance instance = new Instance(); instanceList.add(instance); @@ -155,7 +158,7 @@ public void testValidateForBothUnhealthyAndHealthyHosts() { } @Test - public void testFromKey() { + void testFromKey() { String key1 = "group@@name"; String key2 = "group@@name@@c2"; ServiceInfo s1 = ServiceInfo.fromKey(key1); @@ -165,7 +168,7 @@ public void testFromKey() { } @Test - public void testSetAndGet() throws JsonProcessingException { + void testSetAndGet() throws JsonProcessingException { serviceInfo.setReachProtectionThreshold(true); serviceInfo.setJsonFromServer(mapper.writeValueAsString(serviceInfo)); ServiceInfo actual = mapper.readValue(serviceInfo.getJsonFromServer(), ServiceInfo.class); diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/ServiceTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/ServiceTest.java index 518b57ea01e..d13eea441a1 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/ServiceTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/ServiceTest.java @@ -16,19 +16,19 @@ package com.alibaba.nacos.api.naming.pojo; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.HashMap; -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; -public class ServiceTest { +class ServiceTest { @Test - public void testSetAndGet() { + void testSetAndGet() { Service service = new Service(); assertNull(service.getName()); assertNull(service.getAppName()); @@ -51,12 +51,13 @@ public void testSetAndGet() { } @Test - public void testToString() { + void testToString() { Service service = new Service("service"); service.setGroupName("group"); service.setAppName("app"); service.setProtectThreshold(1.0f); service.setMetadata(Collections.singletonMap("a", "b")); - assertEquals("Service{name='service', protectThreshold=1.0, appName='app', groupName='group', metadata={a=b}}", service.toString()); + assertEquals("Service{name='service', protectThreshold=1.0, appName='app', groupName='group', metadata={a=b}}", + service.toString()); } } \ No newline at end of file diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/builder/InstanceBuilderTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/builder/InstanceBuilderTest.java index c53985927f2..85e34bda514 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/builder/InstanceBuilderTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/builder/InstanceBuilderTest.java @@ -17,18 +17,16 @@ package com.alibaba.nacos.api.naming.pojo.builder; import com.alibaba.nacos.api.naming.pojo.Instance; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -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; -public class InstanceBuilderTest { +class InstanceBuilderTest { private static final String SERVICE_NAME = "testService"; @@ -53,26 +51,26 @@ public class InstanceBuilderTest { private static final String META_VALUE = "value"; @Test - public void testBuildFullInstance() { + void testBuildFullInstance() { InstanceBuilder builder = InstanceBuilder.newBuilder(); - Instance actual = builder.setServiceName(SERVICE_NAME).setClusterName(CLUSTER_NAME).setInstanceId(INSTANCE_ID) - .setIp(IP).setPort(PORT).setWeight(WEIGHT).setHealthy(HEALTHY).setEnabled(ENABLED) - .setEphemeral(EPHEMERAL).addMetadata(META_KEY, META_VALUE).build(); - assertThat(actual.getServiceName(), is(SERVICE_NAME)); - assertThat(actual.getClusterName(), is(CLUSTER_NAME)); - assertThat(actual.getInstanceId(), is(INSTANCE_ID)); - assertThat(actual.getIp(), is(IP)); - assertThat(actual.getPort(), is(PORT)); - assertThat(actual.getWeight(), is(WEIGHT)); - assertThat(actual.isHealthy(), is(HEALTHY)); - assertThat(actual.isEnabled(), is(ENABLED)); - assertThat(actual.isEphemeral(), is(EPHEMERAL)); - assertThat(actual.getMetadata().size(), is(1)); - assertThat(actual.getMetadata().get(META_KEY), is(META_VALUE)); + Instance actual = builder.setServiceName(SERVICE_NAME).setClusterName(CLUSTER_NAME).setInstanceId(INSTANCE_ID).setIp(IP) + .setPort(PORT).setWeight(WEIGHT).setHealthy(HEALTHY).setEnabled(ENABLED).setEphemeral(EPHEMERAL) + .addMetadata(META_KEY, META_VALUE).build(); + assertEquals(actual.getServiceName(), SERVICE_NAME); + assertEquals(actual.getClusterName(), CLUSTER_NAME); + assertEquals(actual.getInstanceId(), INSTANCE_ID); + assertEquals(actual.getIp(), IP); + assertEquals(actual.getPort(), PORT); + assertEquals(actual.getWeight(), WEIGHT); + assertEquals(actual.isHealthy(), HEALTHY); + assertEquals(actual.isEnabled(), ENABLED); + assertEquals(actual.isEphemeral(), EPHEMERAL); + assertEquals(actual.getMetadata().size(), 1); + assertEquals(actual.getMetadata().get(META_KEY), META_VALUE); } @Test - public void testBuildInstanceWithoutNewMetadata() { + void testBuildInstanceWithoutNewMetadata() { InstanceBuilder builder = InstanceBuilder.newBuilder(); Map metadata = new HashMap<>(); metadata.put("test", "test"); @@ -81,8 +79,8 @@ public void testBuildInstanceWithoutNewMetadata() { assertNull(actual.getClusterName()); assertNull(actual.getInstanceId()); assertNull(actual.getIp()); - assertThat(actual.getPort(), is(0)); - assertThat(actual.getWeight(), is(1.0)); + assertEquals(actual.getPort(), 0); + assertEquals(actual.getWeight(), 1.0); assertTrue(actual.isHealthy()); assertTrue(actual.isEnabled()); assertTrue(actual.isEphemeral()); @@ -90,15 +88,15 @@ public void testBuildInstanceWithoutNewMetadata() { } @Test - public void testBuildEmptyInstance() { + void testBuildEmptyInstance() { InstanceBuilder builder = InstanceBuilder.newBuilder(); Instance actual = builder.build(); assertNull(actual.getServiceName()); assertNull(actual.getClusterName()); assertNull(actual.getInstanceId()); assertNull(actual.getIp()); - assertThat(actual.getPort(), is(0)); - assertThat(actual.getWeight(), is(1.0)); + assertEquals(actual.getPort(), 0); + assertEquals(actual.getWeight(), 1.0); assertTrue(actual.isHealthy()); assertTrue(actual.isEnabled()); assertTrue(actual.isEphemeral()); diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/AbstractHealthCheckerTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/AbstractHealthCheckerTest.java index 1ba45355fc2..22f9cd4cfce 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/AbstractHealthCheckerTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/AbstractHealthCheckerTest.java @@ -20,26 +20,26 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.jsontype.NamedType; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; -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 AbstractHealthCheckerTest { +class AbstractHealthCheckerTest { private final ObjectMapper objectMapper = new ObjectMapper(); - @Before - public void setUp() { + @BeforeEach + void setUp() { objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); objectMapper.registerSubtypes(new NamedType(TestChecker.class, TestChecker.TYPE)); } @Test - public void testSerialize() throws JsonProcessingException { + void testSerialize() throws JsonProcessingException { TestChecker testChecker = new TestChecker(); testChecker.setTestValue(""); String actual = objectMapper.writeValueAsString(testChecker); @@ -48,7 +48,7 @@ public void testSerialize() throws JsonProcessingException { } @Test - public void testDeserialize() throws IOException { + void testDeserialize() throws IOException { String testChecker = "{\"type\":\"TEST\",\"testValue\":\"\"}"; TestChecker actual = objectMapper.readValue(testChecker, TestChecker.class); assertEquals("", actual.getTestValue()); @@ -56,7 +56,7 @@ public void testDeserialize() throws IOException { } @Test - public void testClone() throws CloneNotSupportedException { + void testClone() throws CloneNotSupportedException { AbstractHealthChecker none = new AbstractHealthChecker.None().clone(); assertEquals(AbstractHealthChecker.None.class, none.getClass()); } diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/HealthCheckTypeTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/HealthCheckTypeTest.java index b5e8e5237b7..cd75c7edd0f 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/HealthCheckTypeTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/HealthCheckTypeTest.java @@ -19,17 +19,17 @@ import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Http; import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Mysql; import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Tcp; -import org.junit.Test; +import org.junit.jupiter.api.Test; 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; -public class HealthCheckTypeTest { +class HealthCheckTypeTest { @Test - public void testOfHealthCheckerClassForBuildInType() { + void testOfHealthCheckerClassForBuildInType() { assertEquals(Tcp.class, HealthCheckType.ofHealthCheckerClass("TCP")); assertEquals(Http.class, HealthCheckType.ofHealthCheckerClass("HTTP")); assertEquals(Mysql.class, HealthCheckType.ofHealthCheckerClass("MYSQL")); @@ -37,18 +37,18 @@ public void testOfHealthCheckerClassForBuildInType() { } @Test - public void testOfHealthCheckerClassForExtendType() { + void testOfHealthCheckerClassForExtendType() { HealthCheckType.registerHealthChecker(TestChecker.TYPE, TestChecker.class); assertEquals(TestChecker.class, HealthCheckType.ofHealthCheckerClass(TestChecker.TYPE)); } @Test - public void testOfHealthCheckerClassForNonExistType() { + void testOfHealthCheckerClassForNonExistType() { assertNull(HealthCheckType.ofHealthCheckerClass("non-exist")); } @Test - public void testGetLoadedHealthCheckerClasses() { + void testGetLoadedHealthCheckerClasses() { HealthCheckType.registerHealthChecker(TestChecker.TYPE, TestChecker.class); List> actual = HealthCheckType.getLoadedHealthCheckerClasses(); assertEquals(5, actual.size()); diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/HealthCheckerFactoryTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/HealthCheckerFactoryTest.java index 9e60f4842f4..340b16f7265 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/HealthCheckerFactoryTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/HealthCheckerFactoryTest.java @@ -19,75 +19,80 @@ import com.alibaba.nacos.api.exception.runtime.NacosDeserializationException; import com.alibaba.nacos.api.exception.runtime.NacosSerializationException; import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Tcp; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class HealthCheckerFactoryTest { +class HealthCheckerFactoryTest { - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { HealthCheckerFactory.registerSubType(new TestChecker()); } @Test - public void testSerialize() { + void testSerialize() { Tcp tcp = new Tcp(); String actual = HealthCheckerFactory.serialize(tcp); assertTrue(actual.contains("\"type\":\"TCP\"")); } @Test - public void testSerializeExtend() { + void testSerializeExtend() { TestChecker testChecker = new TestChecker(); String actual = HealthCheckerFactory.serialize(testChecker); assertTrue(actual.contains("\"type\":\"TEST\"")); } @Test - public void testDeserialize() { + void testDeserialize() { String tcpString = "{\"type\":\"TCP\"}"; AbstractHealthChecker actual = HealthCheckerFactory.deserialize(tcpString); assertEquals(Tcp.class, actual.getClass()); } @Test - public void testDeserializeExtend() { + void testDeserializeExtend() { String tcpString = "{\"type\":\"TEST\",\"testValue\":null}"; AbstractHealthChecker actual = HealthCheckerFactory.deserialize(tcpString); assertEquals(TestChecker.class, actual.getClass()); } @Test - public void testSerializeNoRegister() { + void testSerializeNoRegister() { NoRegisterHealthChecker noRegister = new NoRegisterHealthChecker(); assertFalse(HealthCheckerFactory.serialize(noRegister).contains("no register")); } @Test - public void testDeserializeNoRegister() { + void testDeserializeNoRegister() { String tcpString = "{\"type\":\"no register\",\"testValue\":null}"; AbstractHealthChecker actual = HealthCheckerFactory.deserialize(tcpString); assertEquals(AbstractHealthChecker.None.class, actual.getClass()); } - @Test(expected = NacosSerializationException.class) - public void testSerializeFailure() { - SelfDependHealthChecker selfDependHealthChecker = new SelfDependHealthChecker(); - System.out.println(HealthCheckerFactory.serialize(selfDependHealthChecker)); + @Test + void testSerializeFailure() { + assertThrows(NacosSerializationException.class, () -> { + SelfDependHealthChecker selfDependHealthChecker = new SelfDependHealthChecker(); + System.out.println(HealthCheckerFactory.serialize(selfDependHealthChecker)); + }); } - @Test(expected = NacosDeserializationException.class) - public void testDeserializeFailure() { - String errorString = "{\"type\"=\"TCP\"}"; - System.out.println(HealthCheckerFactory.deserialize(errorString)); + @Test + void testDeserializeFailure() { + assertThrows(NacosDeserializationException.class, () -> { + String errorString = "{\"type\"=\"TCP\"}"; + System.out.println(HealthCheckerFactory.deserialize(errorString)); + }); } @Test - public void testCreateNoneHealthChecker() { + void testCreateNoneHealthChecker() { assertEquals(AbstractHealthChecker.None.class, HealthCheckerFactory.createNoneHealthChecker().getClass()); } diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/TestChecker.java b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/TestChecker.java index 4d2e8c0a278..f570245d0c3 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/TestChecker.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/TestChecker.java @@ -28,6 +28,10 @@ public class TestChecker extends AbstractHealthChecker { private String testValue; + public TestChecker() { + super(TYPE); + } + public String getTestValue() { return testValue; } @@ -36,10 +40,6 @@ public void setTestValue(String testValue) { this.testValue = testValue; } - public TestChecker() { - super(TYPE); - } - @Override public AbstractHealthChecker clone() throws CloneNotSupportedException { return null; diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/impl/HttpTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/impl/HttpTest.java index f23918d30f0..5c93e83544b 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/impl/HttpTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/impl/HttpTest.java @@ -18,36 +18,37 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; 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.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class HttpTest { +class HttpTest { private ObjectMapper objectMapper; private Http http; - @Before - public void setUp() { + @BeforeEach + void setUp() { objectMapper = new ObjectMapper(); http = new Http(); } @Test - public void testGetExpectedResponseCodeWithEmpty() { + void testGetExpectedResponseCodeWithEmpty() { http.setHeaders(""); assertTrue(http.getCustomHeaders().isEmpty()); } @Test - public void testGetExpectedResponseCodeWithoutEmpty() { + void testGetExpectedResponseCodeWithoutEmpty() { http.setHeaders("x:a|y:"); Map actual = http.getCustomHeaders(); assertFalse(actual.isEmpty()); @@ -56,7 +57,7 @@ public void testGetExpectedResponseCodeWithoutEmpty() { } @Test - public void testSerialize() throws JsonProcessingException { + void testSerialize() throws JsonProcessingException { http.setHeaders("x:a|y:"); http.setPath("/x"); String actual = objectMapper.writeValueAsString(http); @@ -67,7 +68,7 @@ public void testSerialize() throws JsonProcessingException { } @Test - public void testDeserialize() throws IOException { + void testDeserialize() throws IOException { String testChecker = "{\"type\":\"HTTP\",\"path\":\"/x\",\"headers\":\"x:a|y:\",\"expectedResponseCode\":200}"; Http actual = objectMapper.readValue(testChecker, Http.class); assertEquals("x:a|y:", actual.getHeaders()); @@ -78,23 +79,23 @@ public void testDeserialize() throws IOException { } @Test - public void testClone() throws CloneNotSupportedException { + void testClone() throws CloneNotSupportedException { Http cloned = http.clone(); assertEquals(http.hashCode(), cloned.hashCode()); - assertTrue(http.equals(cloned)); + assertEquals(http, cloned); } @Test - public void testNotEquals() throws CloneNotSupportedException { - assertFalse(http.equals(new Tcp())); + void testNotEquals() throws CloneNotSupportedException { + assertNotEquals(http, new Tcp()); Http cloned = http.clone(); cloned.setPath("aaa"); - assertFalse(http.equals(cloned)); + assertNotEquals(http, cloned); cloned = http.clone(); cloned.setHeaders("aaa"); - assertFalse(http.equals(cloned)); + assertNotEquals(http, cloned); cloned = http.clone(); cloned.setExpectedResponseCode(500); - assertFalse(http.equals(cloned)); + assertNotEquals(http, cloned); } } diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/impl/MysqlTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/impl/MysqlTest.java index 7dfd6ad92d5..3e11d888590 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/impl/MysqlTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/impl/MysqlTest.java @@ -18,23 +18,23 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; -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.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class MysqlTest { +class MysqlTest { private ObjectMapper objectMapper; private Mysql mysql; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { mysql = new Mysql(); mysql.setUser("user"); mysql.setPwd("pwd"); @@ -43,7 +43,7 @@ public void setUp() throws Exception { } @Test - public void testSerialize() throws JsonProcessingException { + void testSerialize() throws JsonProcessingException { String actual = objectMapper.writeValueAsString(mysql); assertTrue(actual.contains("\"user\":\"user\"")); assertTrue(actual.contains("\"type\":\"MYSQL\"")); @@ -52,7 +52,7 @@ public void testSerialize() throws JsonProcessingException { } @Test - public void testDeserialize() throws IOException { + void testDeserialize() throws IOException { String testChecker = "{\"type\":\"MYSQL\",\"user\":\"user\",\"pwd\":\"pwd\",\"cmd\":\"cmd\"}"; Mysql actual = objectMapper.readValue(testChecker, Mysql.class); assertEquals("cmd", actual.getCmd()); @@ -62,23 +62,23 @@ public void testDeserialize() throws IOException { } @Test - public void testClone() throws CloneNotSupportedException { + void testClone() throws CloneNotSupportedException { Mysql cloned = mysql.clone(); assertEquals(mysql.hashCode(), cloned.hashCode()); - assertTrue(mysql.equals(cloned)); + assertEquals(mysql, cloned); } @Test - public void testNotEquals() throws CloneNotSupportedException { - assertFalse(mysql.equals(new Tcp())); + void testNotEquals() throws CloneNotSupportedException { + assertNotEquals(mysql, new Tcp()); Mysql cloned = mysql.clone(); cloned.setUser("aaa"); - assertFalse(mysql.equals(cloned)); + assertNotEquals(mysql, cloned); cloned = mysql.clone(); cloned.setPwd("aaa"); - assertFalse(mysql.equals(cloned)); + assertNotEquals(mysql, cloned); cloned = mysql.clone(); cloned.setCmd("aaa"); - assertFalse(mysql.equals(cloned)); + assertNotEquals(mysql, cloned); } } diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/impl/TcpTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/impl/TcpTest.java index d1c57bc4c79..5d02ef946b3 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/impl/TcpTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/pojo/healthcheck/impl/TcpTest.java @@ -16,18 +16,17 @@ package com.alibaba.nacos.api.naming.pojo.healthcheck.impl; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class TcpTest { +class TcpTest { @Test - public void testClone() throws CloneNotSupportedException { + void testClone() throws CloneNotSupportedException { Tcp original = new Tcp(); Tcp cloned = original.clone(); assertEquals(original.hashCode(), cloned.hashCode()); - assertTrue(original.equals(cloned)); + assertEquals(original, cloned); } } \ No newline at end of file diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/BasedNamingRequestTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/BasedNamingRequestTest.java index 435b44611a9..3804dc173f5 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/BasedNamingRequestTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/BasedNamingRequestTest.java @@ -19,11 +19,11 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.BeforeClass; +import org.junit.jupiter.api.BeforeAll; import static com.alibaba.nacos.api.common.Constants.Naming.NAMING_MODULE; -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 abstract class BasedNamingRequestTest { @@ -35,7 +35,7 @@ public abstract class BasedNamingRequestTest { protected static ObjectMapper mapper; - @BeforeClass + @BeforeAll public static void setUp() throws Exception { mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/BatchInstanceRequestTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/BatchInstanceRequestTest.java index af4127dddbe..8a48fa101c9 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/BatchInstanceRequestTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/BatchInstanceRequestTest.java @@ -19,17 +19,17 @@ import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.remote.NamingRemoteConstants; import com.fasterxml.jackson.core.JsonProcessingException; -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.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class BatchInstanceRequestTest extends BasedNamingRequestTest { +class BatchInstanceRequestTest extends BasedNamingRequestTest { @Test - public void testSerialize() throws JsonProcessingException { + void testSerialize() throws JsonProcessingException { BatchInstanceRequest request = new BatchInstanceRequest(NAMESPACE, SERVICE, GROUP, NamingRemoteConstants.BATCH_REGISTER_INSTANCE, Collections.singletonList(new Instance())); String json = mapper.writeValueAsString(request); @@ -39,7 +39,7 @@ public void testSerialize() throws JsonProcessingException { } @Test - public void testDeserialize() throws JsonProcessingException { + void testDeserialize() throws JsonProcessingException { String json = "{\"headers\":{},\"namespace\":\"namespace\",\"serviceName\":\"service\",\"groupName\":\"group\"," + "\"type\":\"batchRegisterInstance\",\"instances\":[{\"port\":0,\"weight\":1.0,\"healthy\":true," + "\"enabled\":true,\"ephemeral\":true,\"metadata\":{},\"instanceIdGenerator\":\"simple\"," diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/InstanceRequestTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/InstanceRequestTest.java index 72c34af4c03..5237df64675 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/InstanceRequestTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/InstanceRequestTest.java @@ -19,15 +19,15 @@ import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.remote.NamingRemoteConstants; import com.fasterxml.jackson.core.JsonProcessingException; -import org.junit.Test; +import org.junit.jupiter.api.Test; -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 InstanceRequestTest extends BasedNamingRequestTest { +class InstanceRequestTest extends BasedNamingRequestTest { @Test - public void testSerialize() throws JsonProcessingException { + void testSerialize() throws JsonProcessingException { InstanceRequest request = new InstanceRequest(NAMESPACE, SERVICE, GROUP, NamingRemoteConstants.REGISTER_INSTANCE, new Instance()); String json = mapper.writeValueAsString(request); @@ -37,7 +37,7 @@ public void testSerialize() throws JsonProcessingException { } @Test - public void testDeserialize() throws JsonProcessingException { + void testDeserialize() throws JsonProcessingException { String json = "{\"headers\":{},\"namespace\":\"namespace\",\"serviceName\":\"service\",\"groupName\":\"group\"," + "\"type\":\"deregisterInstance\",\"instance\":{\"port\":0,\"weight\":1.0,\"healthy\":true," + "\"enabled\":true,\"ephemeral\":true,\"metadata\":{},\"instanceIdGenerator\":\"simple\"," diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/NotifySubscriberRequestTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/NotifySubscriberRequestTest.java index e8dd9df4627..a60eaf98c48 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/NotifySubscriberRequestTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/NotifySubscriberRequestTest.java @@ -21,14 +21,14 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import static com.alibaba.nacos.api.common.Constants.Naming.NAMING_MODULE; -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 NotifySubscriberRequestTest { +class NotifySubscriberRequestTest { private static final String SERVICE = "service"; @@ -38,15 +38,15 @@ public class NotifySubscriberRequestTest { private static ObjectMapper mapper; - @BeforeClass - public static void setUp() throws Exception { + @BeforeAll + static void setUp() throws Exception { mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } @Test - public void testSerialize() throws JsonProcessingException { + void testSerialize() throws JsonProcessingException { ServiceInfo serviceInfo = new ServiceInfo(GROUP + "@@" + SERVICE); NotifySubscriberRequest request = NotifySubscriberRequest.buildNotifySubscriberRequest(serviceInfo); request.setServiceName(SERVICE); @@ -58,7 +58,7 @@ public void testSerialize() throws JsonProcessingException { } @Test - public void testDeserialize() throws JsonProcessingException { + void testDeserialize() throws JsonProcessingException { String json = "{\"headers\":{},\"namespace\":\"namespace\",\"serviceName\":\"service\",\"groupName\":\"group\"," + "\"serviceInfo\":{\"name\":\"service\",\"groupName\":\"group\",\"cacheMillis\":1000,\"hosts\":[]," + "\"lastRefTime\":0,\"checksum\":\"\",\"allIPs\":false,\"reachProtectionThreshold\":false," diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/PersistentInstanceRequestTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/PersistentInstanceRequestTest.java index be358447a0f..41ea9ae5d74 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/PersistentInstanceRequestTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/PersistentInstanceRequestTest.java @@ -19,15 +19,15 @@ import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.remote.NamingRemoteConstants; import com.fasterxml.jackson.core.JsonProcessingException; -import org.junit.Test; +import org.junit.jupiter.api.Test; -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 PersistentInstanceRequestTest extends BasedNamingRequestTest { +class PersistentInstanceRequestTest extends BasedNamingRequestTest { @Test - public void testSerialize() throws JsonProcessingException { + void testSerialize() throws JsonProcessingException { PersistentInstanceRequest request = new PersistentInstanceRequest(NAMESPACE, SERVICE, GROUP, NamingRemoteConstants.REGISTER_INSTANCE, new Instance()); String json = mapper.writeValueAsString(request); @@ -37,7 +37,7 @@ public void testSerialize() throws JsonProcessingException { } @Test - public void testDeserialize() throws JsonProcessingException { + void testDeserialize() throws JsonProcessingException { String json = "{\"headers\":{},\"namespace\":\"namespace\",\"serviceName\":\"service\",\"groupName\":\"group\"," + "\"type\":\"deregisterInstance\",\"instance\":{\"port\":0,\"weight\":1.0,\"healthy\":true," + "\"enabled\":true,\"ephemeral\":true,\"metadata\":{},\"instanceIdGenerator\":\"simple\"," diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/ServiceListRequestTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/ServiceListRequestTest.java index 8014e5b602b..a0e897495c1 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/ServiceListRequestTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/ServiceListRequestTest.java @@ -17,16 +17,16 @@ package com.alibaba.nacos.api.naming.remote.request; import com.fasterxml.jackson.core.JsonProcessingException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static com.alibaba.nacos.api.common.Constants.Naming.NAMING_MODULE; -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 ServiceListRequestTest extends BasedNamingRequestTest { +class ServiceListRequestTest extends BasedNamingRequestTest { @Test - public void testSerialize() throws JsonProcessingException { + void testSerialize() throws JsonProcessingException { ServiceListRequest request = new ServiceListRequest(NAMESPACE, GROUP, 1, 10); request.setSelector("label"); String json = mapper.writeValueAsString(request); @@ -39,7 +39,7 @@ public void testSerialize() throws JsonProcessingException { } @Test - public void testDeserialize() throws JsonProcessingException { + void testDeserialize() throws JsonProcessingException { String json = "{\"headers\":{},\"namespace\":\"namespace\",\"serviceName\":\"\",\"groupName\":\"group\"," + "\"pageNo\":1,\"pageSize\":10,\"selector\":\"label\",\"module\":\"naming\"}"; ServiceListRequest actual = mapper.readValue(json, ServiceListRequest.class); diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/ServiceQueryRequestTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/ServiceQueryRequestTest.java index 609a33caa36..93e039220d0 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/ServiceQueryRequestTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/ServiceQueryRequestTest.java @@ -18,15 +18,15 @@ import com.alibaba.nacos.api.common.Constants; import com.fasterxml.jackson.core.JsonProcessingException; -import org.junit.Test; +import org.junit.jupiter.api.Test; -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 ServiceQueryRequestTest extends BasedNamingRequestTest { +class ServiceQueryRequestTest extends BasedNamingRequestTest { @Test - public void testSerialize() throws JsonProcessingException { + void testSerialize() throws JsonProcessingException { ServiceQueryRequest request = new ServiceQueryRequest(NAMESPACE, SERVICE, GROUP); request.setCluster(Constants.DEFAULT_CLUSTER_NAME); String json = mapper.writeValueAsString(request); @@ -37,7 +37,7 @@ public void testSerialize() throws JsonProcessingException { } @Test - public void testDeserialize() throws JsonProcessingException { + void testDeserialize() throws JsonProcessingException { String json = "{\"headers\":{},\"namespace\":\"namespace\",\"serviceName\":\"service\",\"groupName\":\"group\"," + "\"cluster\":\"DEFAULT\",\"healthyOnly\":true,\"udpPort\":0,\"module\":\"naming\"}"; ServiceQueryRequest actual = mapper.readValue(json, ServiceQueryRequest.class); diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/SubscribeServiceRequestTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/SubscribeServiceRequestTest.java index 1eabfb40a35..f0a76876bde 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/SubscribeServiceRequestTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/remote/request/SubscribeServiceRequestTest.java @@ -17,16 +17,16 @@ package com.alibaba.nacos.api.naming.remote.request; import com.fasterxml.jackson.core.JsonProcessingException; -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.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 SubscribeServiceRequestTest extends BasedNamingRequestTest { +class SubscribeServiceRequestTest extends BasedNamingRequestTest { @Test - public void testSerialize() throws JsonProcessingException { + void testSerialize() throws JsonProcessingException { SubscribeServiceRequest request = new SubscribeServiceRequest(NAMESPACE, GROUP, SERVICE, "", true); String json = mapper.writeValueAsString(request); checkSerializeBasedInfo(json); @@ -35,7 +35,7 @@ public void testSerialize() throws JsonProcessingException { } @Test - public void testDeserialize() throws JsonProcessingException { + void testDeserialize() throws JsonProcessingException { String json = "{\"headers\":{},\"namespace\":\"namespace\",\"serviceName\":\"service\",\"groupName\":\"group\"," + "\"subscribe\":false,\"clusters\":\"aa,bb\",\"module\":\"naming\"}"; SubscribeServiceRequest actual = mapper.readValue(json, SubscribeServiceRequest.class); diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/remote/response/BatchInstanceResponseTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/remote/response/BatchInstanceResponseTest.java index bb8c409873f..74e37c33213 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/remote/response/BatchInstanceResponseTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/remote/response/BatchInstanceResponseTest.java @@ -21,32 +21,32 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -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 BatchInstanceResponseTest { +class BatchInstanceResponseTest { protected static ObjectMapper mapper; - @BeforeClass - public static void setUp() throws Exception { + @BeforeAll + static void setUp() throws Exception { mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } @Test - public void testSerialize() throws JsonProcessingException { + void testSerialize() throws JsonProcessingException { BatchInstanceResponse response = new BatchInstanceResponse(NamingRemoteConstants.REGISTER_INSTANCE); String json = mapper.writeValueAsString(response); assertTrue(json.contains("\"type\":\"" + NamingRemoteConstants.REGISTER_INSTANCE + "\"")); } @Test - public void testDeserialize() throws JsonProcessingException { + void testDeserialize() throws JsonProcessingException { String json = "{\"resultCode\":200,\"errorCode\":0,\"type\":\"registerInstance\",\"success\":true}"; BatchInstanceResponse response = mapper.readValue(json, BatchInstanceResponse.class); assertEquals(NamingRemoteConstants.REGISTER_INSTANCE, response.getType()); diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/remote/response/InstanceResponseTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/remote/response/InstanceResponseTest.java index 1f448824a11..33dafa78524 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/remote/response/InstanceResponseTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/remote/response/InstanceResponseTest.java @@ -21,32 +21,32 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -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 InstanceResponseTest { +class InstanceResponseTest { protected static ObjectMapper mapper; - @BeforeClass - public static void setUp() throws Exception { + @BeforeAll + static void setUp() throws Exception { mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } @Test - public void testSerialize() throws JsonProcessingException { + void testSerialize() throws JsonProcessingException { InstanceResponse response = new InstanceResponse(NamingRemoteConstants.REGISTER_INSTANCE); String json = mapper.writeValueAsString(response); assertTrue(json.contains("\"type\":\"" + NamingRemoteConstants.REGISTER_INSTANCE + "\"")); } @Test - public void testDeserialize() throws JsonProcessingException { + void testDeserialize() throws JsonProcessingException { String json = "{\"resultCode\":200,\"errorCode\":0,\"type\":\"deregisterInstance\",\"success\":true}"; InstanceResponse response = mapper.readValue(json, InstanceResponse.class); assertEquals(NamingRemoteConstants.DE_REGISTER_INSTANCE, response.getType()); diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/remote/response/QueryServiceResponseTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/remote/response/QueryServiceResponseTest.java index cc98aebf802..a75d7c89e3f 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/remote/response/QueryServiceResponseTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/remote/response/QueryServiceResponseTest.java @@ -21,25 +21,25 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class QueryServiceResponseTest { +class QueryServiceResponseTest { protected static ObjectMapper mapper; - @BeforeClass - public static void setUp() throws Exception { + @BeforeAll + static void setUp() throws Exception { mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } @Test - public void testSerializeSuccessResponse() throws JsonProcessingException { + void testSerializeSuccessResponse() throws JsonProcessingException { QueryServiceResponse response = QueryServiceResponse.buildSuccessResponse(new ServiceInfo()); String json = mapper.writeValueAsString(response); assertTrue(json.contains("\"serviceInfo\":{")); @@ -49,7 +49,7 @@ public void testSerializeSuccessResponse() throws JsonProcessingException { } @Test - public void testSerializeFailResponse() throws JsonProcessingException { + void testSerializeFailResponse() throws JsonProcessingException { QueryServiceResponse response = QueryServiceResponse.buildFailResponse("test"); String json = mapper.writeValueAsString(response); assertTrue(json.contains("\"resultCode\":500")); @@ -59,7 +59,7 @@ public void testSerializeFailResponse() throws JsonProcessingException { } @Test - public void testDeserialize() throws JsonProcessingException { + void testDeserialize() throws JsonProcessingException { String json = "{\"resultCode\":200,\"errorCode\":0,\"serviceInfo\":{\"cacheMillis\":1000,\"hosts\":[]," + "\"lastRefTime\":0,\"checksum\":\"\",\"allIPs\":false,\"reachProtectionThreshold\":false," + "\"valid\":true},\"success\":true}"; diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/remote/response/ServiceListResponseTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/remote/response/ServiceListResponseTest.java index 8fc59aade65..1f9c8b21953 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/remote/response/ServiceListResponseTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/remote/response/ServiceListResponseTest.java @@ -20,27 +20,27 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.util.Collections; -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 ServiceListResponseTest { +class ServiceListResponseTest { protected static ObjectMapper mapper; - @BeforeClass - public static void setUp() throws Exception { + @BeforeAll + static void setUp() throws Exception { mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } @Test - public void testSerializeSuccessResponse() throws JsonProcessingException { + void testSerializeSuccessResponse() throws JsonProcessingException { ServiceListResponse response = ServiceListResponse.buildSuccessResponse(10, Collections.singletonList("a")); String json = mapper.writeValueAsString(response); assertTrue(json.contains("\"count\":10")); @@ -51,7 +51,7 @@ public void testSerializeSuccessResponse() throws JsonProcessingException { } @Test - public void testSerializeFailResponse() throws JsonProcessingException { + void testSerializeFailResponse() throws JsonProcessingException { ServiceListResponse response = ServiceListResponse.buildFailResponse("test"); String json = mapper.writeValueAsString(response); assertTrue(json.contains("\"resultCode\":500")); @@ -61,7 +61,7 @@ public void testSerializeFailResponse() throws JsonProcessingException { } @Test - public void testDeserialize() throws JsonProcessingException { + void testDeserialize() throws JsonProcessingException { String json = "{\"resultCode\":200,\"errorCode\":0,\"count\":10,\"serviceNames\":[\"a\"],\"success\":true}"; ServiceListResponse response = mapper.readValue(json, ServiceListResponse.class); assertEquals(10, response.getCount()); diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/remote/response/SubscribeServiceResponseTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/remote/response/SubscribeServiceResponseTest.java index ba2288bc891..d52902aa807 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/remote/response/SubscribeServiceResponseTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/remote/response/SubscribeServiceResponseTest.java @@ -21,25 +21,25 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class SubscribeServiceResponseTest { +class SubscribeServiceResponseTest { protected static ObjectMapper mapper; - @BeforeClass - public static void setUp() throws Exception { + @BeforeAll + static void setUp() throws Exception { mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } @Test - public void testSerializeSuccessResponse() throws JsonProcessingException { + void testSerializeSuccessResponse() throws JsonProcessingException { SubscribeServiceResponse response = new SubscribeServiceResponse(200, null, new ServiceInfo()); String json = mapper.writeValueAsString(response); assertTrue(json.contains("\"serviceInfo\":{")); @@ -49,7 +49,7 @@ public void testSerializeSuccessResponse() throws JsonProcessingException { } @Test - public void testSerializeFailResponse() throws JsonProcessingException { + void testSerializeFailResponse() throws JsonProcessingException { SubscribeServiceResponse response = new SubscribeServiceResponse(500, "test", null); String json = mapper.writeValueAsString(response); assertTrue(json.contains("\"resultCode\":500")); @@ -59,7 +59,7 @@ public void testSerializeFailResponse() throws JsonProcessingException { } @Test - public void testDeserialize() throws JsonProcessingException { + void testDeserialize() throws JsonProcessingException { String json = "{\"resultCode\":200,\"errorCode\":0,\"serviceInfo\":{\"cacheMillis\":1000,\"hosts\":[]," + "\"lastRefTime\":0,\"checksum\":\"\",\"allIPs\":false,\"reachProtectionThreshold\":false," + "\"valid\":true},\"success\":true}"; diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/utils/NamingUtilsTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/utils/NamingUtilsTest.java index 55eb315c6e9..8b64bb6b181 100644 --- a/api/src/test/java/com/alibaba/nacos/api/naming/utils/NamingUtilsTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/naming/utils/NamingUtilsTest.java @@ -21,107 +21,117 @@ import com.alibaba.nacos.api.naming.PreservedMetadataKeys; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.utils.StringUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; 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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class NamingUtilsTest { +class NamingUtilsTest { @Test - public void testGetGroupedName() { + void testGetGroupedName() { assertEquals("group@@serviceName", NamingUtils.getGroupedName("serviceName", "group")); } - @Test(expected = IllegalArgumentException.class) - public void testGetGroupedNameWithoutGroup() { - NamingUtils.getGroupedName("serviceName", ""); + @Test + void testGetGroupedNameWithoutGroup() { + assertThrows(IllegalArgumentException.class, () -> { + NamingUtils.getGroupedName("serviceName", ""); + }); } - @Test(expected = IllegalArgumentException.class) - public void testGetGroupedNameWithoutServiceName() { - NamingUtils.getGroupedName("", "group"); + @Test + void testGetGroupedNameWithoutServiceName() { + assertThrows(IllegalArgumentException.class, () -> { + NamingUtils.getGroupedName("", "group"); + }); } @Test - public void testGetServiceName() { + void testGetServiceName() { String validServiceName = "group@@serviceName"; assertEquals("serviceName", NamingUtils.getServiceName(validServiceName)); } @Test - public void testGetServiceNameWithoutGroup() { + void testGetServiceNameWithoutGroup() { String serviceName = "serviceName"; assertEquals(serviceName, NamingUtils.getServiceName(serviceName)); } @Test - public void testGetServiceNameWithEmpty() { + void testGetServiceNameWithEmpty() { assertEquals(StringUtils.EMPTY, NamingUtils.getServiceName(null)); } @Test - public void testGetGroupName() { + void testGetGroupName() { String validServiceName = "group@@serviceName"; assertEquals("group", NamingUtils.getGroupName(validServiceName)); } @Test - public void testGetGroupNameWithoutGroup() { + void testGetGroupNameWithoutGroup() { String serviceName = "serviceName"; assertEquals(Constants.DEFAULT_GROUP, NamingUtils.getGroupName(serviceName)); } @Test - public void testGetGroupNameWithEmpty() { + void testGetGroupNameWithEmpty() { assertEquals(StringUtils.EMPTY, NamingUtils.getGroupName(null)); } @Test - public void testIsServiceNameCompatibilityMode() { + void testIsServiceNameCompatibilityMode() { String serviceName1 = "group@@serviceName"; assertTrue(NamingUtils.isServiceNameCompatibilityMode(serviceName1)); - + String serviceName2 = "serviceName"; assertFalse(NamingUtils.isServiceNameCompatibilityMode(serviceName2)); - + String serviceName3 = null; assertFalse(NamingUtils.isServiceNameCompatibilityMode(serviceName3)); } @Test - public void testCheckServiceNameFormat() { + void testCheckServiceNameFormat() { String validServiceName = "group@@serviceName"; NamingUtils.checkServiceNameFormat(validServiceName); } - @Test(expected = IllegalArgumentException.class) - public void testCheckServiceNameFormatWithoutGroupAndService() { - String validServiceName = "@@"; - NamingUtils.checkServiceNameFormat(validServiceName); + @Test + void testCheckServiceNameFormatWithoutGroupAndService() { + assertThrows(IllegalArgumentException.class, () -> { + String validServiceName = "@@"; + NamingUtils.checkServiceNameFormat(validServiceName); + }); } - @Test(expected = IllegalArgumentException.class) - public void testCheckServiceNameFormatWithoutGroup() { - String validServiceName = "@@service"; - NamingUtils.checkServiceNameFormat(validServiceName); + @Test + void testCheckServiceNameFormatWithoutGroup() { + assertThrows(IllegalArgumentException.class, () -> { + String validServiceName = "@@service"; + NamingUtils.checkServiceNameFormat(validServiceName); + }); } - @Test(expected = IllegalArgumentException.class) - public void testCheckServiceNameFormatWithoutService() { - String validServiceName = "group@@"; - NamingUtils.checkServiceNameFormat(validServiceName); + @Test + void testCheckServiceNameFormatWithoutService() { + assertThrows(IllegalArgumentException.class, () -> { + String validServiceName = "group@@"; + NamingUtils.checkServiceNameFormat(validServiceName); + }); } @Test - public void testGetGroupedNameOptional() { + void testGetGroupedNameOptional() { String onlyGroupName = NamingUtils.getGroupedNameOptional(StringUtils.EMPTY, "groupA"); assertEquals("groupA@@", onlyGroupName); @@ -133,7 +143,7 @@ public void testGetGroupedNameOptional() { } @Test - public void testCheckInstanceIsLegal() throws NacosException { + void testCheckInstanceIsLegal() throws NacosException { // check invalid clusterName Instance instance = new Instance(); instance.setClusterName("cluster1,cluster2"); @@ -151,7 +161,7 @@ public void testCheckInstanceIsLegal() throws NacosException { instance.setClusterName("cluster1"); NamingUtils.checkInstanceIsLegal(instance); assertTrue(true); - + // check heartBeatTimeout, heartBeatInterval, ipDeleteTimeout Map meta = new HashMap<>(); meta.put(PreservedMetadataKeys.HEART_BEAT_TIMEOUT, "1"); @@ -163,8 +173,7 @@ public void testCheckInstanceIsLegal() throws NacosException { assertTrue(false); } catch (Exception e) { assertTrue(e instanceof NacosException); - assertEquals( - "Instance 'heart beat interval' must less than 'heart beat timeout' and 'ip delete timeout'.", + assertEquals("Instance 'heart beat interval' must less than 'heart beat timeout' and 'ip delete timeout'.", e.getMessage()); } meta.put(PreservedMetadataKeys.HEART_BEAT_TIMEOUT, "3"); @@ -175,7 +184,7 @@ public void testCheckInstanceIsLegal() throws NacosException { } @Test - public void testBatchCheckInstanceIsLegal() throws NacosException { + void testBatchCheckInstanceIsLegal() throws NacosException { // check invalid clusterName Instance instance = new Instance(); instance.setClusterName("cluster1,cluster2"); @@ -212,8 +221,7 @@ public void testBatchCheckInstanceIsLegal() throws NacosException { assertTrue(false); } catch (Exception e) { assertTrue(e instanceof NacosException); - assertEquals( - "Instance 'heart beat interval' must less than 'heart beat timeout' and 'ip delete timeout'.", + assertEquals("Instance 'heart beat interval' must less than 'heart beat timeout' and 'ip delete timeout'.", e.getMessage()); } instanceList.remove(instance); @@ -228,7 +236,7 @@ public void testBatchCheckInstanceIsLegal() throws NacosException { } @Test - public void testCheckInstanceIsEphemeral() throws NacosException { + void testCheckInstanceIsEphemeral() throws NacosException { Instance instance = new Instance(); instance.setIp("127.0.0.1"); instance.setPort(9089); @@ -241,12 +249,12 @@ public void testCheckInstanceIsEphemeral() throws NacosException { instance.setEphemeral(false); NamingUtils.checkInstanceIsEphemeral(instance); } catch (NacosException e) { - Assert.assertEquals(e.getErrCode(), NacosException.INVALID_PARAM); + assertEquals(NacosException.INVALID_PARAM, e.getErrCode()); } } - + @Test - public void testCheckInstanceIsNull() throws NacosException { + void testCheckInstanceIsNull() throws NacosException { Instance instance = new Instance(); instance.setIp("127.0.0.1"); instance.setPort(9089); @@ -254,15 +262,15 @@ public void testCheckInstanceIsNull() throws NacosException { try { NamingUtils.checkInstanceIsLegal(null); } catch (NacosException e) { - Assert.assertEquals(e.getErrCode(), NacosException.INVALID_PARAM); + assertEquals(NacosException.INVALID_PARAM, e.getErrCode()); } } @Test - public void testIsNumber() { + void testIsNumber() { String str1 = "abc"; - assertTrue(!NamingUtils.isNumber(str1)); - + assertFalse(NamingUtils.isNumber(str1)); + String str2 = "123456"; assertTrue(NamingUtils.isNumber(str2)); } diff --git a/api/src/test/java/com/alibaba/nacos/api/remote/AbstractPushCallBackTest.java b/api/src/test/java/com/alibaba/nacos/api/remote/AbstractPushCallBackTest.java index 8ccb82f2a20..b415eae67ac 100644 --- a/api/src/test/java/com/alibaba/nacos/api/remote/AbstractPushCallBackTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/remote/AbstractPushCallBackTest.java @@ -16,18 +16,18 @@ package com.alibaba.nacos.api.remote; -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.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 AbstractPushCallBackTest { +class AbstractPushCallBackTest { boolean testValue; @Test - public void testAbstractPushCallBack() { + void testAbstractPushCallBack() { AbstractPushCallBack callBack = new AbstractPushCallBack(2000) { @Override diff --git a/api/src/test/java/com/alibaba/nacos/api/remote/AbstractRequestCallBackTest.java b/api/src/test/java/com/alibaba/nacos/api/remote/AbstractRequestCallBackTest.java index 3af0a91040d..4a9d74530cc 100644 --- a/api/src/test/java/com/alibaba/nacos/api/remote/AbstractRequestCallBackTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/remote/AbstractRequestCallBackTest.java @@ -18,20 +18,20 @@ import com.alibaba.nacos.api.remote.response.ErrorResponse; import com.alibaba.nacos.api.remote.response.Response; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.Executor; -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 AbstractRequestCallBackTest { +class AbstractRequestCallBackTest { boolean testValue; @Test - public void testAbstractPushCallBack() { + void testAbstractPushCallBack() { AbstractRequestCallBack callBack = new AbstractRequestCallBack() { @Override public Executor getExecutor() { diff --git a/api/src/test/java/com/alibaba/nacos/api/remote/DefaultRequestFutureTest.java b/api/src/test/java/com/alibaba/nacos/api/remote/DefaultRequestFutureTest.java index 854e6b4659f..e8f778a6d7a 100644 --- a/api/src/test/java/com/alibaba/nacos/api/remote/DefaultRequestFutureTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/remote/DefaultRequestFutureTest.java @@ -17,27 +17,28 @@ package com.alibaba.nacos.api.remote; import com.alibaba.nacos.api.remote.response.Response; -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.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; -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; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; -@RunWith(MockitoJUnitRunner.class) -public class DefaultRequestFutureTest { +@ExtendWith(MockitoExtension.class) +class DefaultRequestFutureTest { private static final String CONNECTION_ID = "1233_1.1.1.1_3306"; @@ -51,17 +52,17 @@ public class DefaultRequestFutureTest { private long timestamp; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { timestamp = System.currentTimeMillis(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { } @Test - public void testSyncGetResponseSuccessWithoutTimeout() throws InterruptedException { + void testSyncGetResponseSuccessWithoutTimeout() throws InterruptedException { DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID); new Thread(() -> { try { @@ -79,7 +80,7 @@ public void testSyncGetResponseSuccessWithoutTimeout() throws InterruptedExcepti } @Test - public void testSyncGetResponseFailureWithoutTimeout() throws InterruptedException { + void testSyncGetResponseFailureWithoutTimeout() throws InterruptedException { DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID); new Thread(() -> { try { @@ -97,7 +98,7 @@ public void testSyncGetResponseFailureWithoutTimeout() throws InterruptedExcepti } @Test - public void testSyncGetResponseSuccessWithTimeout() throws InterruptedException, TimeoutException { + void testSyncGetResponseSuccessWithTimeout() throws InterruptedException, TimeoutException { DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID); new Thread(() -> { try { @@ -115,7 +116,7 @@ public void testSyncGetResponseSuccessWithTimeout() throws InterruptedException, } @Test - public void testSyncGetResponseSuccessWithInvalidTimeout() throws InterruptedException, TimeoutException { + void testSyncGetResponseSuccessWithInvalidTimeout() throws InterruptedException, TimeoutException { DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID); new Thread(() -> { try { @@ -132,14 +133,16 @@ public void testSyncGetResponseSuccessWithInvalidTimeout() throws InterruptedExc assertTrue(requestFuture.getTimeStamp() >= timestamp); } - @Test(expected = TimeoutException.class) - public void testSyncGetResponseFailureWithTimeout() throws InterruptedException, TimeoutException { - DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID); - requestFuture.get(100L); + @Test + void testSyncGetResponseFailureWithTimeout() throws InterruptedException, TimeoutException { + assertThrows(TimeoutException.class, () -> { + DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID); + requestFuture.get(100L); + }); } @Test - public void testSyncGetResponseSuccessByTriggerWithoutTimeout() throws InterruptedException { + void testSyncGetResponseSuccessByTriggerWithoutTimeout() throws InterruptedException { MockTimeoutInnerTrigger trigger = new MockTimeoutInnerTrigger(); DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID, null, trigger); new Thread(() -> { @@ -159,7 +162,7 @@ public void testSyncGetResponseSuccessByTriggerWithoutTimeout() throws Interrupt } @Test - public void testSyncGetResponseFailureByTriggerWithoutTimeout() throws InterruptedException { + void testSyncGetResponseFailureByTriggerWithoutTimeout() throws InterruptedException { MockTimeoutInnerTrigger trigger = new MockTimeoutInnerTrigger(); DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID, null, trigger); new Thread(() -> { @@ -179,7 +182,7 @@ public void testSyncGetResponseFailureByTriggerWithoutTimeout() throws Interrupt } @Test - public void testSyncGetResponseSuccessByTriggerWithTimeout() throws InterruptedException, TimeoutException { + void testSyncGetResponseSuccessByTriggerWithTimeout() throws InterruptedException, TimeoutException { MockTimeoutInnerTrigger trigger = new MockTimeoutInnerTrigger(); DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID, null, trigger); new Thread(() -> { @@ -198,19 +201,21 @@ public void testSyncGetResponseSuccessByTriggerWithTimeout() throws InterruptedE assertFalse(trigger.isTimeout); } - @Test(expected = TimeoutException.class) - public void testSyncGetResponseFailureByTriggerWithTimeout() throws InterruptedException, TimeoutException { - MockTimeoutInnerTrigger trigger = new MockTimeoutInnerTrigger(); - DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID, null, trigger); - try { - requestFuture.get(100L); - } finally { - assertTrue(trigger.isTimeout); - } + @Test + void testSyncGetResponseFailureByTriggerWithTimeout() throws InterruptedException, TimeoutException { + assertThrows(TimeoutException.class, () -> { + MockTimeoutInnerTrigger trigger = new MockTimeoutInnerTrigger(); + DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID, null, trigger); + try { + requestFuture.get(100L); + } finally { + assertTrue(trigger.isTimeout); + } + }); } @Test - public void testASyncGetResponseSuccessWithoutTimeout() throws InterruptedException { + void testASyncGetResponseSuccessWithoutTimeout() throws InterruptedException { MockTimeoutInnerTrigger trigger = new MockTimeoutInnerTrigger(); MockRequestCallback callback = new MockRequestCallback(200L); DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID, callback, trigger); @@ -229,7 +234,7 @@ public void testASyncGetResponseSuccessWithoutTimeout() throws InterruptedExcept } @Test - public void testASyncGetResponseSuccessWithoutTimeoutByExecutor() throws InterruptedException { + void testASyncGetResponseSuccessWithoutTimeoutByExecutor() throws InterruptedException { MockTimeoutInnerTrigger trigger = new MockTimeoutInnerTrigger(); MockRequestCallback callback = new MockRequestCallback(executor, 200L); DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID, callback, trigger); @@ -246,7 +251,7 @@ public void testASyncGetResponseSuccessWithoutTimeoutByExecutor() throws Interru } @Test - public void testASyncGetResponseFailureWithoutTimeout() throws InterruptedException { + void testASyncGetResponseFailureWithoutTimeout() throws InterruptedException { MockTimeoutInnerTrigger trigger = new MockTimeoutInnerTrigger(); MockRequestCallback callback = new MockRequestCallback(1000L); DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID, callback, trigger); @@ -265,10 +270,11 @@ public void testASyncGetResponseFailureWithoutTimeout() throws InterruptedExcept } @Test - public void testASyncGetResponseFailureWithTimeout() throws InterruptedException { + void testASyncGetResponseFailureWithTimeout() throws InterruptedException { MockTimeoutInnerTrigger trigger = new MockTimeoutInnerTrigger(); MockRequestCallback callback = new MockRequestCallback(100L); - final DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID, callback, trigger); + final DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID, callback, + trigger); TimeUnit.MILLISECONDS.sleep(500); assertNull(callback.response); assertTrue(callback.exception instanceof TimeoutException); diff --git a/api/src/test/java/com/alibaba/nacos/api/remote/RpcScheduledExecutorTest.java b/api/src/test/java/com/alibaba/nacos/api/remote/RpcScheduledExecutorTest.java index 695c74b5e99..fea7d7c90d7 100644 --- a/api/src/test/java/com/alibaba/nacos/api/remote/RpcScheduledExecutorTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/remote/RpcScheduledExecutorTest.java @@ -16,31 +16,31 @@ package com.alibaba.nacos.api.remote; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class RpcScheduledExecutorTest { +class RpcScheduledExecutorTest { private static final String NAME = "test.rpc.thread"; - Map threadNameMap = new HashMap<>(); + Map threadNameMap = new ConcurrentHashMap<>(); @Test - public void testRpcScheduledExecutor() throws InterruptedException { + void testRpcScheduledExecutor() throws InterruptedException { RpcScheduledExecutor executor = new RpcScheduledExecutor(2, NAME); CountDownLatch latch = new CountDownLatch(2); executor.submit(new TestRunner(1, latch)); executor.submit(new TestRunner(2, latch)); - latch.await(1, TimeUnit.SECONDS); + boolean await = latch.await(1, TimeUnit.SECONDS); + assertTrue(await); assertEquals(2, threadNameMap.size()); - assertEquals(NAME + ".0", threadNameMap.get("1")); - assertEquals(NAME + ".1", threadNameMap.get("2")); } private class TestRunner implements Runnable { @@ -56,13 +56,8 @@ public TestRunner(int id, CountDownLatch latch) { @Override public void run() { - try { - threadNameMap.put(String.valueOf(id), Thread.currentThread().getName()); - TimeUnit.MILLISECONDS.sleep(500); - } catch (InterruptedException ignored) { - } finally { - latch.countDown(); - } + threadNameMap.put(String.valueOf(id), Thread.currentThread().getName()); + latch.countDown(); } } } \ No newline at end of file diff --git a/api/src/test/java/com/alibaba/nacos/api/remote/ability/ClientRemoteAbilityTest.java b/api/src/test/java/com/alibaba/nacos/api/remote/ability/ClientRemoteAbilityTest.java index 9e84a5d22ce..21d60872997 100644 --- a/api/src/test/java/com/alibaba/nacos/api/remote/ability/ClientRemoteAbilityTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/remote/ability/ClientRemoteAbilityTest.java @@ -20,32 +20,32 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -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 ClientRemoteAbilityTest { +class ClientRemoteAbilityTest { private static ObjectMapper mapper; - @BeforeClass - public static void setUp() throws Exception { + @BeforeAll + static void setUp() throws Exception { mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } @Test - public void testSerialize() throws JsonProcessingException { + void testSerialize() throws JsonProcessingException { ClientRemoteAbility abilities = new ClientRemoteAbility(); String json = mapper.writeValueAsString(abilities); assertEquals("{\"supportRemoteConnection\":false}", json); } @Test - public void testDeserialize() throws JsonProcessingException { + void testDeserialize() throws JsonProcessingException { String json = "{\"supportRemoteConnection\":true}"; ClientRemoteAbility abilities = mapper.readValue(json, ClientRemoteAbility.class); assertTrue(abilities.isSupportRemoteConnection()); diff --git a/api/src/test/java/com/alibaba/nacos/api/remote/ability/ServerRemoteAbilityTest.java b/api/src/test/java/com/alibaba/nacos/api/remote/ability/ServerRemoteAbilityTest.java index a2df423249d..6265c68bc5b 100644 --- a/api/src/test/java/com/alibaba/nacos/api/remote/ability/ServerRemoteAbilityTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/remote/ability/ServerRemoteAbilityTest.java @@ -20,37 +20,37 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.MapperFeature; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -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.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ServerRemoteAbilityTest { +class ServerRemoteAbilityTest { private static ObjectMapper mapper; private ServerRemoteAbility serverAbilities; - @BeforeClass - public static void setUpBeforeClass() throws Exception { + @BeforeAll + static void setUpBeforeClass() throws Exception { mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { serverAbilities = new ServerRemoteAbility(); } @Test - public void testSerialize() throws JsonProcessingException { + void testSerialize() throws JsonProcessingException { serverAbilities = new ServerRemoteAbility(); String json = mapper.writeValueAsString(serverAbilities); assertTrue(json.contains("\"supportRemoteConnection\":false")); @@ -58,7 +58,7 @@ public void testSerialize() throws JsonProcessingException { } @Test - public void testDeserialize() throws JsonProcessingException { + void testDeserialize() throws JsonProcessingException { String json = "{\"supportRemoteConnection\":true,\"grpcReportEnabled\":true}"; ServerRemoteAbility abilities = mapper.readValue(json, ServerRemoteAbility.class); assertTrue(abilities.isSupportRemoteConnection()); @@ -66,10 +66,10 @@ public void testDeserialize() throws JsonProcessingException { } @Test - public void testEqualsAndHashCode() { + void testEqualsAndHashCode() { assertEquals(serverAbilities, serverAbilities); assertEquals(serverAbilities.hashCode(), serverAbilities.hashCode()); - assertNotEquals(serverAbilities, null); + assertNotEquals(null, serverAbilities); assertNotEquals(serverAbilities, new ClientAbilities()); ServerRemoteAbility test = new ServerRemoteAbility(); assertEquals(serverAbilities, test); diff --git a/api/src/test/java/com/alibaba/nacos/api/remote/request/BasicRequestTest.java b/api/src/test/java/com/alibaba/nacos/api/remote/request/BasicRequestTest.java index 336f9af7b95..d12af4aefdf 100644 --- a/api/src/test/java/com/alibaba/nacos/api/remote/request/BasicRequestTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/remote/request/BasicRequestTest.java @@ -19,13 +19,13 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Before; +import org.junit.jupiter.api.BeforeEach; public abstract class BasicRequestTest { protected ObjectMapper mapper; - @Before + @BeforeEach public void setUp() throws Exception { mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); diff --git a/api/src/test/java/com/alibaba/nacos/api/remote/request/ConnectResetRequestTest.java b/api/src/test/java/com/alibaba/nacos/api/remote/request/ConnectResetRequestTest.java index d2a7d11925a..6356319f7aa 100644 --- a/api/src/test/java/com/alibaba/nacos/api/remote/request/ConnectResetRequestTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/remote/request/ConnectResetRequestTest.java @@ -16,35 +16,38 @@ package com.alibaba.nacos.api.remote.request; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ConnectResetRequestTest extends BasicRequestTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ConnectResetRequestTest extends BasicRequestTest { @Test - public void testSerialize() throws Exception { + void testSerialize() throws Exception { ConnectResetRequest request = new ConnectResetRequest(); request.setServerIp("127.0.0.1"); request.setServerPort("8888"); request.setRequestId("1"); request.setConnectionId("11111_127.0.0.1_8888"); String json = mapper.writeValueAsString(request); - Assert.assertNotNull(json); - Assert.assertTrue(json.contains("\"serverIp\":\"127.0.0.1\"")); - Assert.assertTrue(json.contains("\"serverPort\":\"8888\"")); - Assert.assertTrue(json.contains("\"module\":\"internal\"")); - Assert.assertTrue(json.contains("\"requestId\":\"1\"")); - Assert.assertTrue(json.contains("\"connectionId\":\"11111_127.0.0.1_8888\"")); + assertNotNull(json); + assertTrue(json.contains("\"serverIp\":\"127.0.0.1\"")); + assertTrue(json.contains("\"serverPort\":\"8888\"")); + assertTrue(json.contains("\"module\":\"internal\"")); + assertTrue(json.contains("\"requestId\":\"1\"")); + assertTrue(json.contains("\"connectionId\":\"11111_127.0.0.1_8888\"")); } @Test - public void testDeserialize() throws Exception { + void testDeserialize() throws Exception { String json = "{\"headers\":{},\"requestId\":\"1\",\"serverIp\":\"127.0.0.1\",\"serverPort\":\"8888\"," + "\"module\":\"internal\",\"connectionId\":\"11111_127.0.0.1_8888\"}"; ConnectResetRequest result = mapper.readValue(json, ConnectResetRequest.class); - Assert.assertNotNull(result); - Assert.assertEquals("127.0.0.1", result.getServerIp()); - Assert.assertEquals("8888", result.getServerPort()); - Assert.assertEquals("11111_127.0.0.1_8888", result.getConnectionId()); + assertNotNull(result); + assertEquals("127.0.0.1", result.getServerIp()); + assertEquals("8888", result.getServerPort()); + assertEquals("11111_127.0.0.1_8888", result.getConnectionId()); } } \ No newline at end of file diff --git a/api/src/test/java/com/alibaba/nacos/api/remote/request/ConnectionSetupRequestTest.java b/api/src/test/java/com/alibaba/nacos/api/remote/request/ConnectionSetupRequestTest.java index 03424d50a64..81d61dc4b0a 100644 --- a/api/src/test/java/com/alibaba/nacos/api/remote/request/ConnectionSetupRequestTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/remote/request/ConnectionSetupRequestTest.java @@ -16,16 +16,19 @@ package com.alibaba.nacos.api.remote.request; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.HashMap; -public class ConnectionSetupRequestTest extends BasicRequestTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ConnectionSetupRequestTest extends BasicRequestTest { @Test - public void testSerialize() throws Exception { + void testSerialize() throws Exception { ConnectionSetupRequest request = new ConnectionSetupRequest(); request.setClientVersion("2.2.2"); request.setAbilityTable(new HashMap<>()); @@ -33,27 +36,28 @@ public void testSerialize() throws Exception { request.setLabels(Collections.singletonMap("labelKey", "labelValue")); request.setRequestId("1"); String json = mapper.writeValueAsString(request); - Assert.assertNotNull(json); - Assert.assertTrue(json.contains("\"clientVersion\":\"2.2.2\"")); - Assert.assertTrue(json.contains("\"tenant\":\"testNamespaceId\"")); - Assert.assertTrue(json.contains("\"labels\":{\"labelKey\":\"labelValue\"}")); - Assert.assertTrue(json.contains("\"abilityTable\":{")); - Assert.assertTrue(json.contains("\"module\":\"internal\"")); - Assert.assertTrue(json.contains("\"requestId\":\"1\"")); + assertNotNull(json); + assertTrue(json.contains("\"clientVersion\":\"2.2.2\"")); + assertTrue(json.contains("\"tenant\":\"testNamespaceId\"")); + assertTrue(json.contains("\"labels\":{\"labelKey\":\"labelValue\"}")); + assertTrue(json.contains("\"abilityTable\":{")); + assertTrue(json.contains("\"module\":\"internal\"")); + assertTrue(json.contains("\"requestId\":\"1\"")); } @Test - public void testDeserialize() throws Exception { - String json = "{\"headers\":{},\"requestId\":\"1\",\"clientVersion\":\"2.2.2\",\"abilities\":{\"remoteAbility\":" - + "{\"supportRemoteConnection\":false},\"configAbility\":{\"supportRemoteMetrics\":false}," - + "\"namingAbility\":{\"supportDeltaPush\":false,\"supportRemoteMetric\":false}},\"tenant\":\"testNamespaceId\"," - + "\"labels\":{\"labelKey\":\"labelValue\"},\"module\":\"internal\"}"; + void testDeserialize() throws Exception { + String json = + "{\"headers\":{},\"requestId\":\"1\",\"clientVersion\":\"2.2.2\",\"abilities\":{\"remoteAbility\":" + + "{\"supportRemoteConnection\":false},\"configAbility\":{\"supportRemoteMetrics\":false}," + + "\"namingAbility\":{\"supportDeltaPush\":false,\"supportRemoteMetric\":false}},\"tenant\":\"testNamespaceId\"," + + "\"labels\":{\"labelKey\":\"labelValue\"},\"module\":\"internal\"}"; ConnectionSetupRequest result = mapper.readValue(json, ConnectionSetupRequest.class); - Assert.assertNotNull(result); - Assert.assertEquals("2.2.2", result.getClientVersion()); - Assert.assertEquals("testNamespaceId", result.getTenant()); - Assert.assertEquals(1, result.getLabels().size()); - Assert.assertEquals("labelValue", result.getLabels().get("labelKey")); - Assert.assertEquals("1", result.getRequestId()); + assertNotNull(result); + assertEquals("2.2.2", result.getClientVersion()); + assertEquals("testNamespaceId", result.getTenant()); + assertEquals(1, result.getLabels().size()); + assertEquals("labelValue", result.getLabels().get("labelKey")); + assertEquals("1", result.getRequestId()); } } \ No newline at end of file diff --git a/api/src/test/java/com/alibaba/nacos/api/remote/request/EmptyContentRequestTest.java b/api/src/test/java/com/alibaba/nacos/api/remote/request/EmptyContentRequestTest.java index 61aebc55594..5fe22b36eab 100644 --- a/api/src/test/java/com/alibaba/nacos/api/remote/request/EmptyContentRequestTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/remote/request/EmptyContentRequestTest.java @@ -19,19 +19,19 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -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 EmptyContentRequestTest extends BasicRequestTest { +class EmptyContentRequestTest extends BasicRequestTest { private static final String COMMON_JSON = "{\"headers\":{\"clientIp\":\"1.1.1.1\"},\"requestId\":\"1\",\"module\":\"internal\"}"; private static final String TO_STRING = "%s{headers={clientIp=1.1.1.1}, requestId='1'}"; - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); @@ -39,26 +39,22 @@ public void setUp() throws Exception { } @Test - public void testClientDetectionRequest() - throws JsonProcessingException, InstantiationException, IllegalAccessException { + void testClientDetectionRequest() throws JsonProcessingException, InstantiationException, IllegalAccessException { doTest(ClientDetectionRequest.class); } @Test - public void testHealthCheckRequest() - throws JsonProcessingException, InstantiationException, IllegalAccessException { + void testHealthCheckRequest() throws JsonProcessingException, InstantiationException, IllegalAccessException { doTest(HealthCheckRequest.class); } @Test - public void testServerCheckRequest() - throws JsonProcessingException, InstantiationException, IllegalAccessException { + void testServerCheckRequest() throws JsonProcessingException, InstantiationException, IllegalAccessException { doTest(ServerCheckRequest.class); } @Test - public void testServerLoaderInfoRequest() - throws JsonProcessingException, InstantiationException, IllegalAccessException { + void testServerLoaderInfoRequest() throws JsonProcessingException, InstantiationException, IllegalAccessException { doTest(ServerLoaderInfoRequest.class); } diff --git a/api/src/test/java/com/alibaba/nacos/api/remote/request/PushAckRequestTest.java b/api/src/test/java/com/alibaba/nacos/api/remote/request/PushAckRequestTest.java index 2d13f00158c..02f0fe4b68f 100644 --- a/api/src/test/java/com/alibaba/nacos/api/remote/request/PushAckRequestTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/remote/request/PushAckRequestTest.java @@ -17,31 +17,35 @@ package com.alibaba.nacos.api.remote.request; import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class PushAckRequestTest extends BasicRequestTest { +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.assertTrue; + +class PushAckRequestTest extends BasicRequestTest { @Test - public void testSerialize() throws Exception { + void testSerialize() throws Exception { PushAckRequest request = PushAckRequest.build("1", false); request.setException(new NacosRuntimeException(500, "test")); String json = mapper.writeValueAsString(request); - Assert.assertNotNull(json); - Assert.assertTrue(json.contains("\"success\":false")); - Assert.assertTrue(json.contains("\"exception\":{")); - Assert.assertTrue(json.contains("\"module\":\"internal\"")); - Assert.assertTrue(json.contains("\"requestId\":\"1\"")); + assertNotNull(json); + assertTrue(json.contains("\"success\":false")); + assertTrue(json.contains("\"exception\":{")); + assertTrue(json.contains("\"module\":\"internal\"")); + assertTrue(json.contains("\"requestId\":\"1\"")); } @Test - public void testDeserialize() throws Exception { + void testDeserialize() throws Exception { String json = "{\"headers\":{},\"requestId\":\"1\",\"success\":false," + "\"exception\":{\"stackTrace\":[],\"errCode\":500,\"message\":\"errCode: 500, errMsg: test \"," + "\"localizedMessage\":\"errCode: 500, errMsg: test \",\"suppressed\":[]},\"module\":\"internal\"}"; PushAckRequest result = mapper.readValue(json, PushAckRequest.class); - Assert.assertNotNull(result); - Assert.assertFalse(result.isSuccess()); - Assert.assertEquals("1", result.getRequestId()); + assertNotNull(result); + assertFalse(result.isSuccess()); + assertEquals("1", result.getRequestId()); } } \ No newline at end of file diff --git a/api/src/test/java/com/alibaba/nacos/api/remote/request/RequestMetaTest.java b/api/src/test/java/com/alibaba/nacos/api/remote/request/RequestMetaTest.java index 13f60b5b34d..866e942d804 100644 --- a/api/src/test/java/com/alibaba/nacos/api/remote/request/RequestMetaTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/remote/request/RequestMetaTest.java @@ -18,22 +18,22 @@ import com.alibaba.nacos.api.ability.constant.AbilityKey; import com.alibaba.nacos.api.ability.constant.AbilityStatus; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -public class RequestMetaTest { +class RequestMetaTest { private RequestMeta requestMeta; - @Before - public void setUp() { + @BeforeEach + void setUp() { requestMeta = new RequestMeta(); requestMeta.setClientIp("127.0.0.1"); requestMeta.setClientVersion("1.0.0"); @@ -44,22 +44,22 @@ public void setUp() { } @Test - public void testGetClientIp() { + void testGetClientIp() { assertEquals("127.0.0.1", requestMeta.getClientIp()); } @Test - public void testGetClientVersion() { + void testGetClientVersion() { assertEquals("1.0.0", requestMeta.getClientVersion()); } @Test - public void testGetConnectionId() { + void testGetConnectionId() { assertEquals("test-connection-id", requestMeta.getConnectionId()); } @Test - public void testGetLabels() { + void testGetLabels() { Map labels = requestMeta.getLabels(); assertNotNull(labels); assertEquals(1, labels.size()); @@ -67,20 +67,20 @@ public void testGetLabels() { } @Test - public void testToString() { + void testToString() { String expected = "RequestMeta{connectionId='test-connection-id', clientIp='127.0.0.1', clientVersion='1.0.0', labels={env=dev}}"; assertEquals(expected, requestMeta.toString()); } @Test - public void testGetConnectionAbilityForNonExist() { + void testGetConnectionAbilityForNonExist() { assertEquals(AbilityStatus.UNKNOWN, requestMeta.getConnectionAbility(AbilityKey.SERVER_TEST_1)); requestMeta.setAbilityTable(Collections.emptyMap()); assertEquals(AbilityStatus.UNKNOWN, requestMeta.getConnectionAbility(AbilityKey.SERVER_TEST_1)); } @Test - public void testGetConnectionAbilityForExist() { + void testGetConnectionAbilityForExist() { requestMeta.setAbilityTable(Collections.singletonMap(AbilityKey.SERVER_TEST_1.getName(), Boolean.FALSE)); assertEquals(AbilityStatus.NOT_SUPPORTED, requestMeta.getConnectionAbility(AbilityKey.SERVER_TEST_1)); requestMeta.setAbilityTable(Collections.singletonMap(AbilityKey.SERVER_TEST_1.getName(), Boolean.TRUE)); diff --git a/api/src/test/java/com/alibaba/nacos/api/remote/request/RequestTest.java b/api/src/test/java/com/alibaba/nacos/api/remote/request/RequestTest.java index f52c3f3a025..24ee28b0ac0 100644 --- a/api/src/test/java/com/alibaba/nacos/api/remote/request/RequestTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/remote/request/RequestTest.java @@ -16,23 +16,23 @@ package com.alibaba.nacos.api.remote.request; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Collections; -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; -public class RequestTest { +class RequestTest { - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { } @Test - public void testHeader() { + void testHeader() { MockRequest request = new MockRequest(); assertTrue(request.getHeaders().isEmpty()); assertNull(request.getHeader("clientIp")); diff --git a/api/src/test/java/com/alibaba/nacos/api/remote/request/ServerReloadRequestTest.java b/api/src/test/java/com/alibaba/nacos/api/remote/request/ServerReloadRequestTest.java index 8066c2eb014..34c23e91b00 100644 --- a/api/src/test/java/com/alibaba/nacos/api/remote/request/ServerReloadRequestTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/remote/request/ServerReloadRequestTest.java @@ -16,35 +16,38 @@ package com.alibaba.nacos.api.remote.request; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ServerReloadRequestTest extends BasicRequestTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ServerReloadRequestTest extends BasicRequestTest { @Test - public void testSerialize() throws Exception { + void testSerialize() throws Exception { ServerReloadRequest request = new ServerReloadRequest(); request.setReloadCount(10); request.setReloadServer("1.1.1.1"); request.setRequestId("1"); String json = mapper.writeValueAsString(request); System.out.println(json); - Assert.assertNotNull(json); - Assert.assertTrue(json.contains("\"reloadCount\":10")); - Assert.assertTrue(json.contains("\"reloadServer\":\"1.1.1.1\"")); - Assert.assertTrue(json.contains("\"module\":\"internal\"")); - Assert.assertTrue(json.contains("\"requestId\":\"1\"")); + assertNotNull(json); + assertTrue(json.contains("\"reloadCount\":10")); + assertTrue(json.contains("\"reloadServer\":\"1.1.1.1\"")); + assertTrue(json.contains("\"module\":\"internal\"")); + assertTrue(json.contains("\"requestId\":\"1\"")); } @Test - public void testDeserialize() throws Exception { + void testDeserialize() throws Exception { String json = "{\"headers\":{},\"requestId\":\"1\",\"reloadCount\":10,\"reloadServer\":\"1.1.1.1\"," + "\"module\":\"internal\"}"; ServerReloadRequest result = mapper.readValue(json, ServerReloadRequest.class); - Assert.assertNotNull(result); - Assert.assertEquals(10, result.getReloadCount()); - Assert.assertEquals("1.1.1.1", result.getReloadServer()); - Assert.assertEquals("1", result.getRequestId()); - Assert.assertEquals("internal", result.getModule()); + assertNotNull(result); + assertEquals(10, result.getReloadCount()); + assertEquals("1.1.1.1", result.getReloadServer()); + assertEquals("1", result.getRequestId()); + assertEquals("internal", result.getModule()); } } \ No newline at end of file diff --git a/api/src/test/java/com/alibaba/nacos/api/remote/request/SetupAckRequestTest.java b/api/src/test/java/com/alibaba/nacos/api/remote/request/SetupAckRequestTest.java index b0697db5e1d..c98108685bf 100644 --- a/api/src/test/java/com/alibaba/nacos/api/remote/request/SetupAckRequestTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/remote/request/SetupAckRequestTest.java @@ -17,34 +17,37 @@ package com.alibaba.nacos.api.remote.request; import com.alibaba.nacos.api.ability.constant.AbilityKey; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collections; -public class SetupAckRequestTest extends BasicRequestTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SetupAckRequestTest extends BasicRequestTest { @Test - public void testSerialize() throws Exception { + void testSerialize() throws Exception { SetupAckRequest request = new SetupAckRequest( Collections.singletonMap(AbilityKey.SERVER_TEST_1.getName(), Boolean.TRUE)); request.setRequestId("1"); String json = mapper.writeValueAsString(request); System.out.println(json); - Assert.assertNotNull(json); - Assert.assertTrue(json.contains("\"abilityTable\":{\"test_1\":true}")); - Assert.assertTrue(json.contains("\"module\":\"internal\"")); - Assert.assertTrue(json.contains("\"requestId\":\"1\"")); + assertNotNull(json); + assertTrue(json.contains("\"abilityTable\":{\"test_1\":true}")); + assertTrue(json.contains("\"module\":\"internal\"")); + assertTrue(json.contains("\"requestId\":\"1\"")); } @Test - public void testDeserialize() throws Exception { + void testDeserialize() throws Exception { String json = "{\"headers\":{},\"requestId\":\"1\",\"abilityTable\":{\"test_1\":true}," + "\"module\":\"internal\"}"; SetupAckRequest result = mapper.readValue(json, SetupAckRequest.class); - Assert.assertNotNull(result); - Assert.assertTrue(result.getAbilityTable().get("test_1")); - Assert.assertEquals("1", result.getRequestId()); - Assert.assertEquals("internal", result.getModule()); + assertNotNull(result); + assertTrue(result.getAbilityTable().get("test_1")); + assertEquals("1", result.getRequestId()); + assertEquals("internal", result.getModule()); } } \ No newline at end of file diff --git a/api/src/test/java/com/alibaba/nacos/api/remote/response/EmptyContentResponseTest.java b/api/src/test/java/com/alibaba/nacos/api/remote/response/EmptyContentResponseTest.java index 28b23af0891..19484416b7c 100644 --- a/api/src/test/java/com/alibaba/nacos/api/remote/response/EmptyContentResponseTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/remote/response/EmptyContentResponseTest.java @@ -20,15 +20,15 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -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; -public class EmptyContentResponseTest { +class EmptyContentResponseTest { private static final String COMMON_JSON = "{\"resultCode\":200,\"errorCode\":0,\"requestId\":\"1\",\"success\":true}"; @@ -36,14 +36,14 @@ public class EmptyContentResponseTest { ObjectMapper mapper = new ObjectMapper(); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } @Test - public void testSetErrorInfo() { + void testSetErrorInfo() { Response response = new Response() { }; response.setErrorInfo(ResponseCode.FAIL.getCode(), ResponseCode.FAIL.getDesc()); @@ -53,7 +53,7 @@ public void testSetErrorInfo() { } @Test - public void testClientDetectionResponse() throws JsonProcessingException { + void testClientDetectionResponse() throws JsonProcessingException { ClientDetectionResponse response = new ClientDetectionResponse(); response.setRequestId("1"); String actual = mapper.writeValueAsString(response); @@ -63,7 +63,7 @@ public void testClientDetectionResponse() throws JsonProcessingException { } @Test - public void testConnectResetResponse() throws JsonProcessingException { + void testConnectResetResponse() throws JsonProcessingException { ConnectResetResponse response = new ConnectResetResponse(); response.setRequestId("1"); String actual = mapper.writeValueAsString(response); @@ -73,7 +73,7 @@ public void testConnectResetResponse() throws JsonProcessingException { } @Test - public void testHealthCheckResponse() throws JsonProcessingException { + void testHealthCheckResponse() throws JsonProcessingException { HealthCheckResponse response = new HealthCheckResponse(); response.setRequestId("1"); String actual = mapper.writeValueAsString(response); @@ -83,7 +83,7 @@ public void testHealthCheckResponse() throws JsonProcessingException { } @Test - public void testServerReloadResponse() throws JsonProcessingException { + void testServerReloadResponse() throws JsonProcessingException { ServerReloadResponse response = new ServerReloadResponse(); response.setRequestId("1"); String actual = mapper.writeValueAsString(response); @@ -93,7 +93,7 @@ public void testServerReloadResponse() throws JsonProcessingException { } @Test - public void testSetupAckResponse() throws JsonProcessingException { + void testSetupAckResponse() throws JsonProcessingException { SetupAckResponse response = new SetupAckResponse(); response.setRequestId("1"); String actual = mapper.writeValueAsString(response); diff --git a/api/src/test/java/com/alibaba/nacos/api/remote/response/ErrorResponseTest.java b/api/src/test/java/com/alibaba/nacos/api/remote/response/ErrorResponseTest.java index 33392a4c447..4bf169a06f3 100644 --- a/api/src/test/java/com/alibaba/nacos/api/remote/response/ErrorResponseTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/remote/response/ErrorResponseTest.java @@ -18,59 +18,60 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ErrorResponseTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ErrorResponseTest { @Test - public void testBuildWithErrorCode() { + void testBuildWithErrorCode() { int errorCode = 500; String msg = "err msg"; Response response = ErrorResponse.build(errorCode, msg); - Assert.assertEquals(errorCode, response.getErrorCode()); - Assert.assertEquals(errorCode, response.getResultCode()); - Assert.assertEquals(msg, response.getMessage()); + assertEquals(errorCode, response.getErrorCode()); + assertEquals(errorCode, response.getResultCode()); + assertEquals(msg, response.getMessage()); } @Test - public void testBuildWithThrowable() { + void testBuildWithThrowable() { String errMsg = "exception msg"; RuntimeException runtimeException = new RuntimeException(errMsg); Response response = ErrorResponse.build(runtimeException); - Assert.assertEquals(ResponseCode.FAIL.getCode(), response.getErrorCode()); - Assert.assertEquals(ResponseCode.FAIL.getCode(), response.getResultCode()); - Assert.assertEquals(errMsg, response.getMessage()); + assertEquals(ResponseCode.FAIL.getCode(), response.getErrorCode()); + assertEquals(ResponseCode.FAIL.getCode(), response.getResultCode()); + assertEquals(errMsg, response.getMessage()); } @Test - public void testBuildWithNacosException() { + void testBuildWithNacosException() { int errCode = 500; String errMsg = "nacos exception msg"; NacosException nacosException = new NacosException(errCode, errMsg); Response response = ErrorResponse.build(nacosException); - Assert.assertEquals(errCode, response.getErrorCode()); - Assert.assertEquals(errCode, response.getResultCode()); - Assert.assertEquals(errMsg, response.getMessage()); + assertEquals(errCode, response.getErrorCode()); + assertEquals(errCode, response.getResultCode()); + assertEquals(errMsg, response.getMessage()); } @Test - public void testBuildWithNacosRuntimeException() { + void testBuildWithNacosRuntimeException() { int errCode = 500; String errMsg = "nacos runtime exception msg"; NacosRuntimeException nacosRuntimeException = new NacosRuntimeException(errCode, errMsg); Response response = ErrorResponse.build(nacosRuntimeException); - Assert.assertEquals(errCode, response.getErrorCode()); - Assert.assertEquals(errCode, response.getResultCode()); - Assert.assertEquals("errCode: " + errCode + ", errMsg: " + errMsg + " ", response.getMessage()); + assertEquals(errCode, response.getErrorCode()); + assertEquals(errCode, response.getResultCode()); + assertEquals("errCode: " + errCode + ", errMsg: " + errMsg + " ", response.getMessage()); } - + } diff --git a/api/src/test/java/com/alibaba/nacos/api/remote/response/ServerCheckResponseTest.java b/api/src/test/java/com/alibaba/nacos/api/remote/response/ServerCheckResponseTest.java index 9a7603435c8..4497514ed74 100644 --- a/api/src/test/java/com/alibaba/nacos/api/remote/response/ServerCheckResponseTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/remote/response/ServerCheckResponseTest.java @@ -20,24 +20,24 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -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 ServerCheckResponseTest { +class ServerCheckResponseTest { ObjectMapper mapper = new ObjectMapper(); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } @Test - public void testSerialization() throws JsonProcessingException { + void testSerialization() throws JsonProcessingException { ServerCheckResponse response = new ServerCheckResponse("35643245_1.1.1.1_3306", false); String actual = mapper.writeValueAsString(response); assertTrue(actual.contains("\"connectionId\":\"35643245_1.1.1.1_3306\"")); @@ -45,7 +45,7 @@ public void testSerialization() throws JsonProcessingException { } @Test - public void testDeserialization() throws JsonProcessingException { + void testDeserialization() throws JsonProcessingException { String json = "{\"resultCode\":200,\"errorCode\":0,\"connectionId\":\"35643245_1.1.1.1_3306\",\"success\":true," + "\"supportAbilityNegotiation\":true}"; ServerCheckResponse response = mapper.readValue(json, ServerCheckResponse.class); diff --git a/api/src/test/java/com/alibaba/nacos/api/remote/response/ServerLoaderInfoResponseTest.java b/api/src/test/java/com/alibaba/nacos/api/remote/response/ServerLoaderInfoResponseTest.java index 7f5041e73b0..20c86906042 100644 --- a/api/src/test/java/com/alibaba/nacos/api/remote/response/ServerLoaderInfoResponseTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/remote/response/ServerLoaderInfoResponseTest.java @@ -20,24 +20,24 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -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 ServerLoaderInfoResponseTest { +class ServerLoaderInfoResponseTest { ObjectMapper mapper = new ObjectMapper(); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } @Test - public void testSerialization() throws JsonProcessingException { + void testSerialization() throws JsonProcessingException { ServerLoaderInfoResponse response = new ServerLoaderInfoResponse(); response.putMetricsValue("test", "testValue"); String actual = mapper.writeValueAsString(response); @@ -46,7 +46,7 @@ public void testSerialization() throws JsonProcessingException { } @Test - public void testDeserialization() throws JsonProcessingException { + void testDeserialization() throws JsonProcessingException { String json = "{\"resultCode\":200,\"errorCode\":0,\"loaderMetrics\":{\"test\":\"testValue\"},\"success\":true}"; ServerLoaderInfoResponse response = mapper.readValue(json, ServerLoaderInfoResponse.class); assertEquals(1, response.getLoaderMetrics().size()); diff --git a/api/src/test/java/com/alibaba/nacos/api/selector/AbstractCmdbSelectorTest.java b/api/src/test/java/com/alibaba/nacos/api/selector/AbstractCmdbSelectorTest.java index 267e5882b84..af9323e9786 100644 --- a/api/src/test/java/com/alibaba/nacos/api/selector/AbstractCmdbSelectorTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/selector/AbstractCmdbSelectorTest.java @@ -20,29 +20,29 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.selector.context.CmdbContext; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import static com.alibaba.nacos.api.common.Constants.Naming.CMDB_CONTEXT_TYPE; -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; -public class AbstractCmdbSelectorTest { +class AbstractCmdbSelectorTest { private AtomicInteger counter; - @Before - public void setUp() { + @BeforeEach + void setUp() { counter = new AtomicInteger(); } @Test - public void testSetExpression() { + void testSetExpression() { MockCmdbSelector cmdbSelector = new MockCmdbSelector(); assertNull(cmdbSelector.getExpression()); cmdbSelector.setExpression("test"); @@ -50,7 +50,7 @@ public void testSetExpression() { } @Test - public void testParse() throws NacosException { + void testParse() throws NacosException { MockCmdbSelector cmdbSelector = new MockCmdbSelector(); cmdbSelector.parse("test"); assertEquals("test", cmdbSelector.getExpression()); @@ -58,7 +58,7 @@ public void testParse() throws NacosException { } @Test - public void testSelect() { + void testSelect() { CmdbContext context = new CmdbContext<>(); CmdbContext.CmdbInstance provider = new CmdbContext.CmdbInstance<>(); provider.setInstance(new Instance()); @@ -78,12 +78,12 @@ public void testSelect() { } @Test - public void testGetContextType() { + void testGetContextType() { assertEquals(CMDB_CONTEXT_TYPE, new MockCmdbSelector().getContextType()); } @Test - public void testGetType() { + void testGetType() { assertEquals("mock", new MockCmdbSelector().getType()); } diff --git a/api/src/test/java/com/alibaba/nacos/api/selector/ExpressionSelectorTest.java b/api/src/test/java/com/alibaba/nacos/api/selector/ExpressionSelectorTest.java index 20e813168d0..f403a227ec2 100644 --- a/api/src/test/java/com/alibaba/nacos/api/selector/ExpressionSelectorTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/selector/ExpressionSelectorTest.java @@ -21,25 +21,25 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.jsontype.NamedType; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -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 ExpressionSelectorTest { +class ExpressionSelectorTest { ObjectMapper mapper = new ObjectMapper(); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.registerSubtypes(new NamedType(ExpressionSelector.class, SelectorType.label.name())); } @Test - public void testSerialization() throws JsonProcessingException { + void testSerialization() throws JsonProcessingException { ExpressionSelector selector = new ExpressionSelector(); selector.setExpression("test expression"); String actual = mapper.writeValueAsString(selector); @@ -48,7 +48,7 @@ public void testSerialization() throws JsonProcessingException { } @Test - public void testDeserialization() throws JsonProcessingException { + void testDeserialization() throws JsonProcessingException { String json = "{\"type\":\"label\",\"expression\":\"test expression\"}"; AbstractSelector actual = mapper.readValue(json, AbstractSelector.class); assertEquals(SelectorType.label.name(), actual.getType()); diff --git a/api/src/test/java/com/alibaba/nacos/api/selector/NoneSelectorTest.java b/api/src/test/java/com/alibaba/nacos/api/selector/NoneSelectorTest.java index 8f2f87214c4..1c6d679b502 100644 --- a/api/src/test/java/com/alibaba/nacos/api/selector/NoneSelectorTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/selector/NoneSelectorTest.java @@ -21,32 +21,32 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.jsontype.NamedType; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -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 NoneSelectorTest { +class NoneSelectorTest { ObjectMapper mapper = new ObjectMapper(); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.registerSubtypes(new NamedType(NoneSelector.class, SelectorType.none.name())); } @Test - public void testSerialization() throws JsonProcessingException { + void testSerialization() throws JsonProcessingException { NoneSelector selector = new NoneSelector(); String actual = mapper.writeValueAsString(selector); assertTrue(actual.contains("\"type\":\"" + SelectorType.none.name() + "\"")); } @Test - public void testDeserialization() throws JsonProcessingException { + void testDeserialization() throws JsonProcessingException { String json = "{\"type\":\"none\"}"; AbstractSelector actual = mapper.readValue(json, AbstractSelector.class); assertEquals(SelectorType.none.name(), actual.getType()); diff --git a/api/src/test/java/com/alibaba/nacos/api/selector/context/CmdbContextTest.java b/api/src/test/java/com/alibaba/nacos/api/selector/context/CmdbContextTest.java index 90fe6c1fe9a..f3f3bbfa0c5 100644 --- a/api/src/test/java/com/alibaba/nacos/api/selector/context/CmdbContextTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/selector/context/CmdbContextTest.java @@ -17,16 +17,16 @@ package com.alibaba.nacos.api.selector.context; 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.jupiter.api.Assertions.assertEquals; -public class CmdbContextTest { +class CmdbContextTest { @Test - public void testToString() { + void testToString() { CmdbContext cmdbContext = new CmdbContext<>(); cmdbContext.setProviders(Collections.singletonList(new CmdbContext.CmdbInstance<>())); cmdbContext.setConsumer(new CmdbContext.CmdbInstance<>()); diff --git a/api/src/test/java/com/alibaba/nacos/api/utils/AbilityKeyTest.java b/api/src/test/java/com/alibaba/nacos/api/utils/AbilityKeyTest.java index a7a88fce339..0812ce18723 100644 --- a/api/src/test/java/com/alibaba/nacos/api/utils/AbilityKeyTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/utils/AbilityKeyTest.java @@ -18,26 +18,28 @@ import com.alibaba.nacos.api.ability.constant.AbilityKey; import com.alibaba.nacos.api.ability.constant.AbilityMode; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collection; import java.util.Collections; import java.util.HashMap; 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.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -/**. +/** + * . + * * @author Daydreamer * @description Ability key test * @date 2022/9/8 12:27 **/ -public class AbilityKeyTest { +class AbilityKeyTest { @Test - public void testMapStr() { + void testMapStr() { Map enumMap = new HashMap<>(); Map stringBooleanMap = AbilityKey.mapStr(enumMap); assertEquals(0, stringBooleanMap.size()); @@ -47,27 +49,27 @@ public void testMapStr() { enumMap.put(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC, false); stringBooleanMap = AbilityKey.mapStr(enumMap); assertEquals(3, stringBooleanMap.size()); - Assert.assertTrue(stringBooleanMap.get(AbilityKey.SERVER_TEST_1.getName())); - Assert.assertFalse(stringBooleanMap.get(AbilityKey.SERVER_TEST_2.getName())); - Assert.assertFalse(stringBooleanMap.get(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC.getName())); + assertTrue(stringBooleanMap.get(AbilityKey.SERVER_TEST_1.getName())); + assertFalse(stringBooleanMap.get(AbilityKey.SERVER_TEST_2.getName())); + assertFalse(stringBooleanMap.get(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC.getName())); enumMap.put(AbilityKey.SERVER_TEST_2, true); enumMap.put(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC, true); stringBooleanMap = AbilityKey.mapStr(enumMap); assertEquals(3, stringBooleanMap.size()); - Assert.assertTrue(stringBooleanMap.get(AbilityKey.SERVER_TEST_1.getName())); - Assert.assertTrue(stringBooleanMap.get(AbilityKey.SERVER_TEST_2.getName())); - Assert.assertTrue(stringBooleanMap.get(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC.getName())); + assertTrue(stringBooleanMap.get(AbilityKey.SERVER_TEST_1.getName())); + assertTrue(stringBooleanMap.get(AbilityKey.SERVER_TEST_2.getName())); + assertTrue(stringBooleanMap.get(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC.getName())); } @Test - public void testMapEnumForEmpty() { + void testMapEnumForEmpty() { Map actual = AbilityKey.mapEnum(AbilityMode.SERVER, Collections.emptyMap()); assertTrue(actual.isEmpty()); } @Test - public void testMapEnum() { + void testMapEnum() { Map mapStr = new HashMap<>(); mapStr.put("test-no-existed", true); Map enumMap = AbilityKey.mapEnum(AbilityMode.SERVER, mapStr); @@ -77,23 +79,23 @@ public void testMapEnum() { mapStr.put(AbilityKey.SERVER_TEST_1.getName(), true); mapStr.put(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC.getName(), true); enumMap = AbilityKey.mapEnum(AbilityMode.SERVER, mapStr); - Assert.assertFalse(enumMap.get(AbilityKey.SERVER_TEST_2)); - Assert.assertTrue(enumMap.get(AbilityKey.SERVER_TEST_1)); - Assert.assertTrue(enumMap.get(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); - + assertFalse(enumMap.get(AbilityKey.SERVER_TEST_2)); + assertTrue(enumMap.get(AbilityKey.SERVER_TEST_1)); + assertTrue(enumMap.get(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); + mapStr.clear(); mapStr.put(AbilityKey.SERVER_TEST_2.getName(), true); mapStr.put(AbilityKey.SERVER_TEST_1.getName(), true); mapStr.put(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC.getName(), true); enumMap = AbilityKey.mapEnum(AbilityMode.SERVER, mapStr); - Assert.assertTrue(enumMap.get(AbilityKey.SERVER_TEST_2)); - Assert.assertTrue(enumMap.get(AbilityKey.SERVER_TEST_1)); - Assert.assertTrue(enumMap.get(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); + assertTrue(enumMap.get(AbilityKey.SERVER_TEST_2)); + assertTrue(enumMap.get(AbilityKey.SERVER_TEST_1)); + assertTrue(enumMap.get(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); } @Test - public void testGetAllValues() { + void testGetAllValues() { Collection actual = AbilityKey.getAllValues(AbilityMode.SERVER); assertEquals(3, actual.size()); actual = AbilityKey.getAllValues(AbilityMode.SDK_CLIENT); @@ -103,7 +105,7 @@ public void testGetAllValues() { } @Test - public void testGetAllNames() { + void testGetAllNames() { Collection actual = AbilityKey.getAllNames(AbilityMode.SERVER); assertEquals(3, actual.size()); actual = AbilityKey.getAllNames(AbilityMode.SDK_CLIENT); @@ -113,7 +115,7 @@ public void testGetAllNames() { } @Test - public void testGetDescription() { + void testGetDescription() { assertEquals("just for junit test", AbilityKey.SERVER_TEST_1.getDescription()); } } diff --git a/api/src/test/java/com/alibaba/nacos/api/utils/NetUtilsTest.java b/api/src/test/java/com/alibaba/nacos/api/utils/NetUtilsTest.java index ed9a0f59479..42b57103353 100644 --- a/api/src/test/java/com/alibaba/nacos/api/utils/NetUtilsTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/utils/NetUtilsTest.java @@ -16,22 +16,22 @@ package com.alibaba.nacos.api.utils; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.InetAddress; import java.util.Properties; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class NetUtilsTest { +class NetUtilsTest { - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { Class clazz = Class.forName("com.alibaba.nacos.api.utils.NetUtils"); Field field = clazz.getDeclaredField("localIp"); field.setAccessible(true); @@ -42,7 +42,7 @@ public void tearDown() throws Exception { } @Test - public void testLocalIpWithSpecifiedIp() { + void testLocalIpWithSpecifiedIp() { System.setProperty("com.alibaba.nacos.client.local.ip", "10.2.8.8"); assertEquals("10.2.8.8", NetUtils.localIP()); System.setProperty("com.alibaba.nacos.client.local.ip", "10.2.8.9"); @@ -50,7 +50,7 @@ public void testLocalIpWithSpecifiedIp() { } @Test - public void testLocalIpWithPreferHostname() throws Exception { + void testLocalIpWithPreferHostname() throws Exception { InetAddress inetAddress = invokeGetInetAddress(); String hostname = inetAddress.getHostName(); System.setProperty("com.alibaba.nacos.client.local.preferHostname", "true"); @@ -58,14 +58,14 @@ public void testLocalIpWithPreferHostname() throws Exception { } @Test - public void testLocalIpWithoutPreferHostname() throws Exception { + void testLocalIpWithoutPreferHostname() throws Exception { InetAddress inetAddress = invokeGetInetAddress(); String ip = inetAddress.getHostAddress(); assertEquals(ip, NetUtils.localIP()); } @Test - public void testLocalIpWithException() throws Exception { + void testLocalIpWithException() throws Exception { Field field = System.class.getDeclaredField("props"); field.setAccessible(true); Properties properties = (Properties) field.get(null); diff --git a/api/src/test/java/com/alibaba/nacos/api/utils/StringUtilsTest.java b/api/src/test/java/com/alibaba/nacos/api/utils/StringUtilsTest.java index 48a35722461..2775f83c47f 100644 --- a/api/src/test/java/com/alibaba/nacos/api/utils/StringUtilsTest.java +++ b/api/src/test/java/com/alibaba/nacos/api/utils/StringUtilsTest.java @@ -16,94 +16,98 @@ package com.alibaba.nacos.api.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class StringUtilsTest { +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 { @Test - public void testIsEmpty() { - Assert.assertTrue(StringUtils.isEmpty(null)); - Assert.assertTrue(StringUtils.isEmpty("")); - Assert.assertFalse(StringUtils.isEmpty(" ")); - Assert.assertFalse(StringUtils.isEmpty("bob")); - Assert.assertFalse(StringUtils.isEmpty(" bob ")); + void testIsEmpty() { + assertTrue(StringUtils.isEmpty(null)); + assertTrue(StringUtils.isEmpty("")); + assertFalse(StringUtils.isEmpty(" ")); + assertFalse(StringUtils.isEmpty("bob")); + assertFalse(StringUtils.isEmpty(" bob ")); } @Test - public void testIsBlank() { - Assert.assertTrue(StringUtils.isBlank(null)); - Assert.assertTrue(StringUtils.isBlank("")); - Assert.assertTrue(StringUtils.isBlank(" ")); - Assert.assertFalse(StringUtils.isBlank("bob")); - Assert.assertFalse(StringUtils.isBlank(" bob ")); + void testIsBlank() { + assertTrue(StringUtils.isBlank(null)); + assertTrue(StringUtils.isBlank("")); + assertTrue(StringUtils.isBlank(" ")); + assertFalse(StringUtils.isBlank("bob")); + assertFalse(StringUtils.isBlank(" bob ")); } @Test - public void testTrim() { - Assert.assertNull(StringUtils.trim(null)); - Assert.assertEquals(StringUtils.EMPTY, StringUtils.trim("")); - Assert.assertEquals(StringUtils.EMPTY, StringUtils.trim(" ")); - Assert.assertEquals("abc", StringUtils.trim("abc")); - Assert.assertEquals("abc", StringUtils.trim(" abc ")); + void testTrim() { + assertNull(StringUtils.trim(null)); + assertEquals(StringUtils.EMPTY, StringUtils.trim("")); + assertEquals(StringUtils.EMPTY, StringUtils.trim(" ")); + assertEquals("abc", StringUtils.trim("abc")); + assertEquals("abc", StringUtils.trim(" abc ")); } @Test - public void testEquals() { - Assert.assertTrue(StringUtils.equals(null, null)); - Assert.assertFalse(StringUtils.equals(null, "abc")); - Assert.assertFalse(StringUtils.equals("abc", null)); - Assert.assertTrue(StringUtils.equals("abc", "abc")); - Assert.assertFalse(StringUtils.equals("abc", "ABC")); - Assert.assertTrue(StringUtils.equals(new StringBuilder("abc"), "abc")); - Assert.assertFalse(StringUtils.equals(new StringBuilder("ABC"), "abc")); + void testEquals() { + assertTrue(StringUtils.equals(null, null)); + assertFalse(StringUtils.equals(null, "abc")); + assertFalse(StringUtils.equals("abc", null)); + assertTrue(StringUtils.equals("abc", "abc")); + assertFalse(StringUtils.equals("abc", "ABC")); + assertTrue(StringUtils.equals(new StringBuilder("abc"), "abc")); + assertFalse(StringUtils.equals(new StringBuilder("ABC"), "abc")); } @Test - public void testRegionMatchesEqualsCaseSensitive() { - Assert.assertTrue(StringUtils.regionMatches("abc", false, 0, "xabc", 1, 3)); - + void testRegionMatchesEqualsCaseSensitive() { + assertTrue(StringUtils.regionMatches("abc", false, 0, "xabc", 1, 3)); + } @Test - public void testRegionMatchesEqualsCaseInsensitive() { - Assert.assertTrue(StringUtils.regionMatches("abc", true, 0, "xabc", 1, 3)); - Assert.assertTrue(StringUtils.regionMatches("abc", true, 0, "xAbc", 1, 3)); + void testRegionMatchesEqualsCaseInsensitive() { + assertTrue(StringUtils.regionMatches("abc", true, 0, "xabc", 1, 3)); + assertTrue(StringUtils.regionMatches("abc", true, 0, "xAbc", 1, 3)); } @Test - public void testRegionMatchesNotEqualsCaseSensitive() { - Assert.assertFalse(StringUtils.regionMatches("abc", false, 0, "xAbc", 1, 3)); - Assert.assertFalse(StringUtils.regionMatches("abc", false, 0, "xCbc", 1, 3)); + void testRegionMatchesNotEqualsCaseSensitive() { + assertFalse(StringUtils.regionMatches("abc", false, 0, "xAbc", 1, 3)); + assertFalse(StringUtils.regionMatches("abc", false, 0, "xCbc", 1, 3)); } @Test - public void testRegionMatchesNotEqualsCaseInsensitive() { - Assert.assertFalse(StringUtils.regionMatches("abc", true, 0, "xCab", 1, 3)); + void testRegionMatchesNotEqualsCaseInsensitive() { + assertFalse(StringUtils.regionMatches("abc", true, 0, "xCab", 1, 3)); } @Test - public void testRegionMatchesEqualsCaseSensitiveForNonString() { - Assert.assertTrue(StringUtils.regionMatches(new StringBuilder("abc"), false, 0, "xabc", 1, 3)); + void testRegionMatchesEqualsCaseSensitiveForNonString() { + assertTrue(StringUtils.regionMatches(new StringBuilder("abc"), false, 0, "xabc", 1, 3)); } @Test - public void testRegionMatchesEqualsCaseInsensitiveForNonString() { - Assert.assertTrue(StringUtils.regionMatches(new StringBuilder("abc"), true, 0, "xabc", 1, 3)); - Assert.assertTrue(StringUtils.regionMatches(new StringBuilder("abc"), true, 0, "xAbc", 1, 3)); + void testRegionMatchesEqualsCaseInsensitiveForNonString() { + assertTrue(StringUtils.regionMatches(new StringBuilder("abc"), true, 0, "xabc", 1, 3)); + assertTrue(StringUtils.regionMatches(new StringBuilder("abc"), true, 0, "xAbc", 1, 3)); } @Test - public void testRegionMatchesNotEqualsCaseSensitiveForNonString() { - Assert.assertFalse(StringUtils.regionMatches(new StringBuilder("abc"), false, 0, "xAbc", 1, 3)); - Assert.assertFalse(StringUtils.regionMatches(new StringBuilder("abc"), false, 0, "xCbc", 1, 3)); + void testRegionMatchesNotEqualsCaseSensitiveForNonString() { + assertFalse(StringUtils.regionMatches(new StringBuilder("abc"), false, 0, "xAbc", 1, 3)); + assertFalse(StringUtils.regionMatches(new StringBuilder("abc"), false, 0, "xCbc", 1, 3)); } @Test - public void testRegionMatchesNotEqualsCaseInsensitiveForNonString() { - Assert.assertFalse(StringUtils.regionMatches(new StringBuilder("abc"), true, 0, "xCab", 1, 3)); + void testRegionMatchesNotEqualsCaseInsensitiveForNonString() { + assertFalse(StringUtils.regionMatches(new StringBuilder("abc"), true, 0, "xCab", 1, 3)); } } diff --git a/auth/pom.xml b/auth/pom.xml index 745aab5dd4b..f1af84b1a1f 100644 --- a/auth/pom.xml +++ b/auth/pom.xml @@ -50,7 +50,11 @@ spring-boot-starter true - + + org.springframework + spring-test + test + org.apache.tomcat.embed tomcat-embed-core diff --git a/auth/src/main/java/com/alibaba/nacos/auth/config/AuthModuleStateBuilder.java b/auth/src/main/java/com/alibaba/nacos/auth/config/AuthModuleStateBuilder.java index dd83d1329a4..b6eb66657ce 100644 --- a/auth/src/main/java/com/alibaba/nacos/auth/config/AuthModuleStateBuilder.java +++ b/auth/src/main/java/com/alibaba/nacos/auth/config/AuthModuleStateBuilder.java @@ -39,6 +39,10 @@ public class AuthModuleStateBuilder implements ModuleStateBuilder { public static final String AUTH_SYSTEM_TYPE = "auth_system_type"; + public static final String AUTH_ADMIN_REQUEST = "auth_admin_request"; + + private boolean cacheable; + @Override public ModuleState build() { ModuleState result = new ModuleState(AUTH_MODULE); @@ -46,12 +50,28 @@ public ModuleState build() { result.newState(AUTH_ENABLED, authConfigs.isAuthEnabled()); result.newState(LOGIN_PAGE_ENABLED, isLoginPageEnabled(authConfigs)); result.newState(AUTH_SYSTEM_TYPE, authConfigs.getNacosAuthSystemType()); + result.newState(AUTH_ADMIN_REQUEST, isAdminRequest(authConfigs)); return result; } + @Override + public boolean isCacheable() { + return cacheable; + } + private Boolean isLoginPageEnabled(AuthConfigs authConfigs) { Optional authPluginService = AuthPluginManager.getInstance() .findAuthServiceSpiImpl(authConfigs.getNacosAuthSystemType()); return authPluginService.map(AuthPluginService::isLoginEnabled).orElse(false); } + + private Boolean isAdminRequest(AuthConfigs authConfigs) { + Optional authPluginService = AuthPluginManager.getInstance() + .findAuthServiceSpiImpl(authConfigs.getNacosAuthSystemType()); + boolean isAdminRequest = authPluginService.map(AuthPluginService::isAdminRequest).orElse(true); + if (!isAdminRequest) { + cacheable = true; + } + return isAdminRequest; + } } diff --git a/auth/src/main/java/com/alibaba/nacos/auth/parser/grpc/ConfigGrpcResourceParser.java b/auth/src/main/java/com/alibaba/nacos/auth/parser/grpc/ConfigGrpcResourceParser.java index 78fd66e776b..eb1a5aaab8b 100644 --- a/auth/src/main/java/com/alibaba/nacos/auth/parser/grpc/ConfigGrpcResourceParser.java +++ b/auth/src/main/java/com/alibaba/nacos/auth/parser/grpc/ConfigGrpcResourceParser.java @@ -67,7 +67,7 @@ protected String getResourceName(Request request) { dataId = ((AbstractConfigRequest) request).getDataId(); } else { dataId = (String) ReflectUtils - .getFieldValue(request, com.alibaba.nacos.api.common.Constants.DATAID, StringUtils.EMPTY); + .getFieldValue(request, com.alibaba.nacos.api.common.Constants.DATA_ID, StringUtils.EMPTY); } return StringUtils.isBlank(dataId) ? StringUtils.EMPTY : dataId; } diff --git a/auth/src/main/java/com/alibaba/nacos/auth/parser/http/ConfigHttpResourceParser.java b/auth/src/main/java/com/alibaba/nacos/auth/parser/http/ConfigHttpResourceParser.java index b453638e09e..edba5189000 100644 --- a/auth/src/main/java/com/alibaba/nacos/auth/parser/http/ConfigHttpResourceParser.java +++ b/auth/src/main/java/com/alibaba/nacos/auth/parser/http/ConfigHttpResourceParser.java @@ -16,6 +16,7 @@ package com.alibaba.nacos.auth.parser.http; +import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.common.utils.NamespaceUtil; import com.alibaba.nacos.common.utils.StringUtils; @@ -31,8 +32,11 @@ public class ConfigHttpResourceParser extends AbstractHttpResourceParser { @Override protected String getNamespaceId(HttpServletRequest request) { - return NamespaceUtil.processNamespaceParameter(request.getParameter("tenant")); - + String namespaceId = request.getParameter(Constants.NAMESPACE_ID); + if (StringUtils.isBlank(namespaceId)) { + namespaceId = request.getParameter(Constants.TENANT); + } + return NamespaceUtil.processNamespaceParameter(namespaceId); } @Override @@ -43,7 +47,7 @@ protected String getGroup(HttpServletRequest request) { @Override protected String getResourceName(HttpServletRequest request) { - String dataId = request.getParameter(com.alibaba.nacos.api.common.Constants.DATAID); + String dataId = request.getParameter(com.alibaba.nacos.api.common.Constants.DATA_ID); return StringUtils.isBlank(dataId) ? StringUtils.EMPTY : dataId; } diff --git a/auth/src/test/java/com/alibaba/nacos/auth/GrpcProtocolAuthServiceTest.java b/auth/src/test/java/com/alibaba/nacos/auth/GrpcProtocolAuthServiceTest.java index db48142058c..490fb6132c7 100644 --- a/auth/src/test/java/com/alibaba/nacos/auth/GrpcProtocolAuthServiceTest.java +++ b/auth/src/test/java/com/alibaba/nacos/auth/GrpcProtocolAuthServiceTest.java @@ -19,30 +19,30 @@ import com.alibaba.nacos.api.config.remote.request.ConfigPublishRequest; import com.alibaba.nacos.api.naming.remote.request.AbstractNamingRequest; import com.alibaba.nacos.auth.annotation.Secured; +import com.alibaba.nacos.auth.config.AuthConfigs; +import com.alibaba.nacos.auth.mock.MockAuthPluginService; import com.alibaba.nacos.plugin.auth.api.IdentityContext; import com.alibaba.nacos.plugin.auth.api.Permission; import com.alibaba.nacos.plugin.auth.api.Resource; -import com.alibaba.nacos.auth.config.AuthConfigs; import com.alibaba.nacos.plugin.auth.constant.SignType; import com.alibaba.nacos.plugin.auth.exception.AccessException; -import com.alibaba.nacos.auth.mock.MockAuthPluginService; -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.Method; -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.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; -@RunWith(MockitoJUnitRunner.class) -public class GrpcProtocolAuthServiceTest { +@ExtendWith(MockitoExtension.class) +class GrpcProtocolAuthServiceTest { @Mock private AuthConfigs authConfigs; @@ -53,8 +53,8 @@ public class GrpcProtocolAuthServiceTest { private GrpcProtocolAuthService protocolAuthService; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { protocolAuthService = new GrpcProtocolAuthService(authConfigs); protocolAuthService.initialize(); mockConfigRequest(); @@ -78,7 +78,7 @@ private void mockNamingRequest() { @Test @Secured(resource = "testResource") - public void testParseResourceWithSpecifiedResource() throws NoSuchMethodException { + void testParseResourceWithSpecifiedResource() throws NoSuchMethodException { Secured secured = getMethodSecure("testParseResourceWithSpecifiedResource"); Resource actual = protocolAuthService.parseResource(namingRequest, secured); assertEquals("testResource", actual.getName()); @@ -90,7 +90,7 @@ public void testParseResourceWithSpecifiedResource() throws NoSuchMethodExceptio @Test @Secured(signType = "non-exist") - public void testParseResourceWithNonExistType() throws NoSuchMethodException { + void testParseResourceWithNonExistType() throws NoSuchMethodException { Secured secured = getMethodSecure("testParseResourceWithNonExistType"); Resource actual = protocolAuthService.parseResource(namingRequest, secured); assertEquals(Resource.EMPTY_RESOURCE, actual); @@ -98,7 +98,7 @@ public void testParseResourceWithNonExistType() throws NoSuchMethodException { @Test @Secured() - public void testParseResourceWithNamingType() throws NoSuchMethodException { + void testParseResourceWithNamingType() throws NoSuchMethodException { Secured secured = getMethodSecure("testParseResourceWithNamingType"); Resource actual = protocolAuthService.parseResource(namingRequest, secured); assertEquals(SignType.NAMING, actual.getType()); @@ -110,7 +110,7 @@ public void testParseResourceWithNamingType() throws NoSuchMethodException { @Test @Secured(signType = SignType.CONFIG) - public void testParseResourceWithConfigType() throws NoSuchMethodException { + void testParseResourceWithConfigType() throws NoSuchMethodException { Secured secured = getMethodSecure("testParseResourceWithConfigType"); Resource actual = protocolAuthService.parseResource(configRequest, secured); assertEquals(SignType.CONFIG, actual.getType()); @@ -121,39 +121,39 @@ public void testParseResourceWithConfigType() throws NoSuchMethodException { } @Test - public void testParseIdentity() { + void testParseIdentity() { IdentityContext actual = protocolAuthService.parseIdentity(namingRequest); assertNotNull(actual); } @Test - public void testValidateIdentityWithoutPlugin() throws AccessException { + void testValidateIdentityWithoutPlugin() throws AccessException { IdentityContext identityContext = new IdentityContext(); assertTrue(protocolAuthService.validateIdentity(identityContext, Resource.EMPTY_RESOURCE)); } @Test - public void testValidateIdentityWithPlugin() throws AccessException { + void testValidateIdentityWithPlugin() throws AccessException { Mockito.when(authConfigs.getNacosAuthSystemType()).thenReturn(MockAuthPluginService.TEST_PLUGIN); IdentityContext identityContext = new IdentityContext(); assertFalse(protocolAuthService.validateIdentity(identityContext, Resource.EMPTY_RESOURCE)); } @Test - public void testValidateAuthorityWithoutPlugin() throws AccessException { - assertTrue(protocolAuthService - .validateAuthority(new IdentityContext(), new Permission(Resource.EMPTY_RESOURCE, ""))); + void testValidateAuthorityWithoutPlugin() throws AccessException { + assertTrue(protocolAuthService.validateAuthority(new IdentityContext(), + new Permission(Resource.EMPTY_RESOURCE, ""))); } @Test - public void testValidateAuthorityWithPlugin() throws AccessException { + void testValidateAuthorityWithPlugin() throws AccessException { Mockito.when(authConfigs.getNacosAuthSystemType()).thenReturn(MockAuthPluginService.TEST_PLUGIN); - assertFalse(protocolAuthService - .validateAuthority(new IdentityContext(), new Permission(Resource.EMPTY_RESOURCE, ""))); + assertFalse(protocolAuthService.validateAuthority(new IdentityContext(), + new Permission(Resource.EMPTY_RESOURCE, ""))); } private Secured getMethodSecure(String methodName) throws NoSuchMethodException { - Method method = GrpcProtocolAuthServiceTest.class.getMethod(methodName); + Method method = GrpcProtocolAuthServiceTest.class.getDeclaredMethod(methodName); return method.getAnnotation(Secured.class); } } diff --git a/auth/src/test/java/com/alibaba/nacos/auth/HttpProtocolAuthServiceTest.java b/auth/src/test/java/com/alibaba/nacos/auth/HttpProtocolAuthServiceTest.java index 27bbf613046..cf6cb59a2b3 100644 --- a/auth/src/test/java/com/alibaba/nacos/auth/HttpProtocolAuthServiceTest.java +++ b/auth/src/test/java/com/alibaba/nacos/auth/HttpProtocolAuthServiceTest.java @@ -19,32 +19,36 @@ import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.naming.CommonParams; import com.alibaba.nacos.auth.annotation.Secured; +import com.alibaba.nacos.auth.config.AuthConfigs; +import com.alibaba.nacos.auth.mock.MockAuthPluginService; import com.alibaba.nacos.plugin.auth.api.IdentityContext; import com.alibaba.nacos.plugin.auth.api.Permission; import com.alibaba.nacos.plugin.auth.api.Resource; -import com.alibaba.nacos.auth.config.AuthConfigs; import com.alibaba.nacos.plugin.auth.constant.SignType; import com.alibaba.nacos.plugin.auth.exception.AccessException; -import com.alibaba.nacos.auth.mock.MockAuthPluginService; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import javax.servlet.http.HttpServletRequest; import java.lang.reflect.Method; -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.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.mockito.ArgumentMatchers.eq; -@RunWith(MockitoJUnitRunner.class) -public class HttpProtocolAuthServiceTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class HttpProtocolAuthServiceTest { @Mock private AuthConfigs authConfigs; @@ -54,8 +58,8 @@ public class HttpProtocolAuthServiceTest { private HttpProtocolAuthService httpProtocolAuthService; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { httpProtocolAuthService = new HttpProtocolAuthService(authConfigs); httpProtocolAuthService.initialize(); Mockito.when(request.getParameter(eq(CommonParams.NAMESPACE_ID))).thenReturn("testNNs"); @@ -63,12 +67,12 @@ public void setUp() throws Exception { Mockito.when(request.getParameter(eq(CommonParams.SERVICE_NAME))).thenReturn("testS"); Mockito.when(request.getParameter(eq("tenant"))).thenReturn("testCNs"); Mockito.when(request.getParameter(eq(Constants.GROUP))).thenReturn("testCG"); - Mockito.when(request.getParameter(eq(Constants.DATAID))).thenReturn("testD"); + Mockito.when(request.getParameter(eq(Constants.DATA_ID))).thenReturn("testD"); } @Test @Secured(resource = "testResource") - public void testParseResourceWithSpecifiedResource() throws NoSuchMethodException { + void testParseResourceWithSpecifiedResource() throws NoSuchMethodException { Secured secured = getMethodSecure("testParseResourceWithSpecifiedResource"); Resource actual = httpProtocolAuthService.parseResource(request, secured); assertEquals("testResource", actual.getName()); @@ -80,7 +84,7 @@ public void testParseResourceWithSpecifiedResource() throws NoSuchMethodExceptio @Test @Secured(signType = "non-exist") - public void testParseResourceWithNonExistType() throws NoSuchMethodException { + void testParseResourceWithNonExistType() throws NoSuchMethodException { Secured secured = getMethodSecure("testParseResourceWithNonExistType"); Resource actual = httpProtocolAuthService.parseResource(request, secured); assertEquals(Resource.EMPTY_RESOURCE, actual); @@ -88,7 +92,7 @@ public void testParseResourceWithNonExistType() throws NoSuchMethodException { @Test @Secured() - public void testParseResourceWithNamingType() throws NoSuchMethodException { + void testParseResourceWithNamingType() throws NoSuchMethodException { Secured secured = getMethodSecure("testParseResourceWithNamingType"); Resource actual = httpProtocolAuthService.parseResource(request, secured); assertEquals(SignType.NAMING, actual.getType()); @@ -100,50 +104,50 @@ public void testParseResourceWithNamingType() throws NoSuchMethodException { @Test @Secured(signType = SignType.CONFIG) - public void testParseResourceWithConfigType() throws NoSuchMethodException { + void testParseResourceWithConfigType() throws NoSuchMethodException { Secured secured = getMethodSecure("testParseResourceWithConfigType"); Resource actual = httpProtocolAuthService.parseResource(request, secured); assertEquals(SignType.CONFIG, actual.getType()); assertEquals("testD", actual.getName()); - assertEquals("testCNs", actual.getNamespaceId()); + assertEquals("testNNs", actual.getNamespaceId()); assertEquals("testCG", actual.getGroup()); assertNotNull(actual.getProperties()); } @Test - public void testParseIdentity() { + void testParseIdentity() { IdentityContext actual = httpProtocolAuthService.parseIdentity(request); assertNotNull(actual); } @Test - public void testValidateIdentityWithoutPlugin() throws AccessException { + void testValidateIdentityWithoutPlugin() throws AccessException { IdentityContext identityContext = new IdentityContext(); assertTrue(httpProtocolAuthService.validateIdentity(identityContext, Resource.EMPTY_RESOURCE)); } @Test - public void testValidateIdentityWithPlugin() throws AccessException { + void testValidateIdentityWithPlugin() throws AccessException { Mockito.when(authConfigs.getNacosAuthSystemType()).thenReturn(MockAuthPluginService.TEST_PLUGIN); IdentityContext identityContext = new IdentityContext(); assertFalse(httpProtocolAuthService.validateIdentity(identityContext, Resource.EMPTY_RESOURCE)); } @Test - public void testValidateAuthorityWithoutPlugin() throws AccessException { - assertTrue(httpProtocolAuthService - .validateAuthority(new IdentityContext(), new Permission(Resource.EMPTY_RESOURCE, ""))); + void testValidateAuthorityWithoutPlugin() throws AccessException { + assertTrue(httpProtocolAuthService.validateAuthority(new IdentityContext(), + new Permission(Resource.EMPTY_RESOURCE, ""))); } @Test - public void testValidateAuthorityWithPlugin() throws AccessException { + void testValidateAuthorityWithPlugin() throws AccessException { Mockito.when(authConfigs.getNacosAuthSystemType()).thenReturn(MockAuthPluginService.TEST_PLUGIN); - assertFalse(httpProtocolAuthService - .validateAuthority(new IdentityContext(), new Permission(Resource.EMPTY_RESOURCE, ""))); + assertFalse(httpProtocolAuthService.validateAuthority(new IdentityContext(), + new Permission(Resource.EMPTY_RESOURCE, ""))); } private Secured getMethodSecure(String methodName) throws NoSuchMethodException { - Method method = HttpProtocolAuthServiceTest.class.getMethod(methodName); + Method method = HttpProtocolAuthServiceTest.class.getDeclaredMethod(methodName); return method.getAnnotation(Secured.class); } } diff --git a/auth/src/test/java/com/alibaba/nacos/auth/config/AuthConfigsTest.java b/auth/src/test/java/com/alibaba/nacos/auth/config/AuthConfigsTest.java index 94db1a2cebf..b8f59f3693f 100644 --- a/auth/src/test/java/com/alibaba/nacos/auth/config/AuthConfigsTest.java +++ b/auth/src/test/java/com/alibaba/nacos/auth/config/AuthConfigsTest.java @@ -18,13 +18,13 @@ import com.alibaba.nacos.common.event.ServerConfigChangeEvent; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.mock.env.MockEnvironment; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class AuthConfigsTest { +class AuthConfigsTest { private static final boolean TEST_AUTH_ENABLED = true; @@ -40,8 +40,8 @@ public class AuthConfigsTest { private MockEnvironment environment; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { environment = new MockEnvironment(); EnvUtil.setEnvironment(environment); environment.setProperty("nacos.core.auth.plugin.test.key", "test"); @@ -49,7 +49,7 @@ public void setUp() throws Exception { } @Test - public void testUpgradeFromEvent() { + void testUpgradeFromEvent() { environment.setProperty("nacos.core.auth.enabled", String.valueOf(TEST_AUTH_ENABLED)); environment.setProperty("nacos.core.auth.caching.enabled", String.valueOf(TEST_CACHING_ENABLED)); environment.setProperty("nacos.core.auth.server.identity.key", TEST_SERVER_IDENTITY_KEY); diff --git a/auth/src/test/java/com/alibaba/nacos/auth/config/AuthModuleStateBuilderTest.java b/auth/src/test/java/com/alibaba/nacos/auth/config/AuthModuleStateBuilderTest.java index bfed02f61e3..e2691598150 100644 --- a/auth/src/test/java/com/alibaba/nacos/auth/config/AuthModuleStateBuilderTest.java +++ b/auth/src/test/java/com/alibaba/nacos/auth/config/AuthModuleStateBuilderTest.java @@ -16,23 +16,25 @@ package com.alibaba.nacos.auth.config; +import com.alibaba.nacos.auth.mock.MockAuthPluginServiceB; import com.alibaba.nacos.sys.module.ModuleState; import com.alibaba.nacos.sys.utils.ApplicationUtils; -import org.junit.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 org.springframework.context.ConfigurableApplicationContext; import static com.alibaba.nacos.auth.config.AuthModuleStateBuilder.AUTH_ENABLED; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +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.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class AuthModuleStateBuilderTest { +@ExtendWith(MockitoExtension.class) +class AuthModuleStateBuilderTest { @Mock private ConfigurableApplicationContext context; @@ -40,22 +42,44 @@ public class AuthModuleStateBuilderTest { @Mock private AuthConfigs authConfigs; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { when(context.getBean(AuthConfigs.class)).thenReturn(authConfigs); ApplicationUtils.injectContext(context); - when(authConfigs.getNacosAuthSystemType()).thenReturn("nacos"); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { } @Test - public void testBuild() { + void testBuild() { + when(authConfigs.getNacosAuthSystemType()).thenReturn("nacos"); + ModuleState actual = new AuthModuleStateBuilder().build(); assertFalse((Boolean) actual.getStates().get(AUTH_ENABLED)); assertFalse((Boolean) actual.getStates().get("login_page_enabled")); assertEquals("nacos", actual.getStates().get("auth_system_type")); + assertTrue((Boolean) actual.getStates().get("auth_admin_request")); + + when(authConfigs.getNacosAuthSystemType()).thenReturn(MockAuthPluginServiceB.TEST_PLUGIN); + ModuleState actual2 = new AuthModuleStateBuilder().build(); + assertTrue((Boolean) actual2.getStates().get("login_page_enabled")); + assertEquals(MockAuthPluginServiceB.TEST_PLUGIN, actual2.getStates().get("auth_system_type")); + assertFalse((Boolean) actual2.getStates().get("auth_admin_request")); + } + + @Test + void testCacheable() { + AuthModuleStateBuilder authModuleStateBuilder = new AuthModuleStateBuilder(); + authModuleStateBuilder.build(); + boolean cacheable = authModuleStateBuilder.isCacheable(); + assertFalse(cacheable); + + when(authConfigs.getNacosAuthSystemType()).thenReturn(MockAuthPluginServiceB.TEST_PLUGIN); + AuthModuleStateBuilder authModuleStateBuilder2 = new AuthModuleStateBuilder(); + authModuleStateBuilder2.build(); + boolean cacheable2 = authModuleStateBuilder2.isCacheable(); + assertTrue(cacheable2); } } \ No newline at end of file diff --git a/auth/src/test/java/com/alibaba/nacos/auth/context/GrpcIdentityContextBuilderTest.java b/auth/src/test/java/com/alibaba/nacos/auth/context/GrpcIdentityContextBuilderTest.java index 08d388dcea1..74001e1cb71 100644 --- a/auth/src/test/java/com/alibaba/nacos/auth/context/GrpcIdentityContextBuilderTest.java +++ b/auth/src/test/java/com/alibaba/nacos/auth/context/GrpcIdentityContextBuilderTest.java @@ -17,24 +17,28 @@ package com.alibaba.nacos.auth.context; import com.alibaba.nacos.api.remote.request.Request; -import com.alibaba.nacos.plugin.auth.api.IdentityContext; import com.alibaba.nacos.auth.config.AuthConfigs; +import com.alibaba.nacos.plugin.auth.api.IdentityContext; import com.alibaba.nacos.plugin.auth.constant.Constants; -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.HashMap; import java.util.Map; -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.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class GrpcIdentityContextBuilderTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class GrpcIdentityContextBuilderTest { private static final String TEST_PLUGIN = "test"; @@ -50,8 +54,8 @@ public class GrpcIdentityContextBuilderTest { private GrpcIdentityContextBuilder identityContextBuilder; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { identityContextBuilder = new GrpcIdentityContextBuilder(authConfigs); when(authConfigs.getNacosAuthSystemType()).thenReturn(TEST_PLUGIN); Map headers = new HashMap<>(); @@ -61,14 +65,14 @@ public void setUp() throws Exception { } @Test - public void testBuildWithoutPlugin() { + void testBuildWithoutPlugin() { when(authConfigs.getNacosAuthSystemType()).thenReturn("non-exist"); IdentityContext actual = identityContextBuilder.build(request); assertNull(actual.getParameter(IDENTITY_TEST_KEY)); } @Test - public void testBuild() { + void testBuild() { IdentityContext actual = identityContextBuilder.build(request); assertEquals(IDENTITY_TEST_VALUE, actual.getParameter(IDENTITY_TEST_KEY)); assertEquals("1.1.1.1", actual.getParameter(Constants.Identity.REMOTE_IP)); diff --git a/auth/src/test/java/com/alibaba/nacos/auth/context/HtppIdentityContextBuilderTest.java b/auth/src/test/java/com/alibaba/nacos/auth/context/HtppIdentityContextBuilderTest.java index 602a46436c5..1937ff54eff 100644 --- a/auth/src/test/java/com/alibaba/nacos/auth/context/HtppIdentityContextBuilderTest.java +++ b/auth/src/test/java/com/alibaba/nacos/auth/context/HtppIdentityContextBuilderTest.java @@ -16,24 +16,28 @@ package com.alibaba.nacos.auth.context; -import com.alibaba.nacos.plugin.auth.api.IdentityContext; import com.alibaba.nacos.auth.config.AuthConfigs; +import com.alibaba.nacos.plugin.auth.api.IdentityContext; import com.alibaba.nacos.plugin.auth.constant.Constants; -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 javax.servlet.http.HttpServletRequest; import java.util.Enumeration; -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.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class HtppIdentityContextBuilderTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class HtppIdentityContextBuilderTest { private static final String TEST_PLUGIN = "test"; @@ -55,14 +59,14 @@ public class HtppIdentityContextBuilderTest { private HttpIdentityContextBuilder identityContextBuilder; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { identityContextBuilder = new HttpIdentityContextBuilder(authConfigs); when(authConfigs.getNacosAuthSystemType()).thenReturn(TEST_PLUGIN); } @Test - public void testBuildWithoutPlugin() { + void testBuildWithoutPlugin() { mockHeader(true); mockParameter(true); when(authConfigs.getNacosAuthSystemType()).thenReturn("non-exist"); @@ -71,7 +75,7 @@ public void testBuildWithoutPlugin() { } @Test - public void testBuildWithHeader() { + void testBuildWithHeader() { mockHeader(true); mockParameter(false); IdentityContext actual = identityContextBuilder.build(request); @@ -80,7 +84,7 @@ public void testBuildWithHeader() { } @Test - public void testBuildWithParameter() { + void testBuildWithParameter() { mockHeader(false); mockParameter(true); IdentityContext actual = identityContextBuilder.build(request); diff --git a/auth/src/test/java/com/alibaba/nacos/auth/mock/MockAuthPluginService.java b/auth/src/test/java/com/alibaba/nacos/auth/mock/MockAuthPluginService.java index d54b3bc920b..73f74631e8b 100644 --- a/auth/src/test/java/com/alibaba/nacos/auth/mock/MockAuthPluginService.java +++ b/auth/src/test/java/com/alibaba/nacos/auth/mock/MockAuthPluginService.java @@ -16,12 +16,12 @@ package com.alibaba.nacos.auth.mock; -import com.alibaba.nacos.plugin.auth.api.Resource; -import com.alibaba.nacos.plugin.auth.constant.ActionTypes; -import com.alibaba.nacos.plugin.auth.spi.server.AuthPluginService; import com.alibaba.nacos.plugin.auth.api.IdentityContext; import com.alibaba.nacos.plugin.auth.api.Permission; +import com.alibaba.nacos.plugin.auth.api.Resource; +import com.alibaba.nacos.plugin.auth.constant.ActionTypes; import com.alibaba.nacos.plugin.auth.exception.AccessException; +import com.alibaba.nacos.plugin.auth.spi.server.AuthPluginService; import java.util.Collection; import java.util.Collections; diff --git a/auth/src/test/java/com/alibaba/nacos/auth/mock/MockAuthPluginServiceB.java b/auth/src/test/java/com/alibaba/nacos/auth/mock/MockAuthPluginServiceB.java new file mode 100644 index 00000000000..0bf161a7bf9 --- /dev/null +++ b/auth/src/test/java/com/alibaba/nacos/auth/mock/MockAuthPluginServiceB.java @@ -0,0 +1,68 @@ +/* + * Copyright 1999-2021 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.auth.mock; + +import com.alibaba.nacos.plugin.auth.api.IdentityContext; +import com.alibaba.nacos.plugin.auth.api.Permission; +import com.alibaba.nacos.plugin.auth.api.Resource; +import com.alibaba.nacos.plugin.auth.constant.ActionTypes; +import com.alibaba.nacos.plugin.auth.spi.server.AuthPluginService; + +import java.util.Collection; +import java.util.Collections; + +public class MockAuthPluginServiceB implements AuthPluginService { + + public static final String TEST_PLUGIN = "testB"; + + public static final String IDENTITY_TEST_KEY = "identity-test-key"; + + @Override + public Collection identityNames() { + return Collections.singletonList(IDENTITY_TEST_KEY); + } + + @Override + public boolean enableAuth(ActionTypes action, String type) { + return true; + } + + @Override + public boolean validateIdentity(IdentityContext identityContext, Resource resource) { + return false; + } + + @Override + public Boolean validateAuthority(IdentityContext identityContext, Permission permission) { + return false; + } + + @Override + public String getAuthServiceName() { + return TEST_PLUGIN; + } + + @Override + public boolean isLoginEnabled() { + return true; + } + + @Override + public boolean isAdminRequest() { + return false; + } +} diff --git a/auth/src/test/java/com/alibaba/nacos/auth/parser/grpc/ConfigGrpcResourceParserTest.java b/auth/src/test/java/com/alibaba/nacos/auth/parser/grpc/ConfigGrpcResourceParserTest.java index 9650f9b7e26..03d0457f574 100644 --- a/auth/src/test/java/com/alibaba/nacos/auth/parser/grpc/ConfigGrpcResourceParserTest.java +++ b/auth/src/test/java/com/alibaba/nacos/auth/parser/grpc/ConfigGrpcResourceParserTest.java @@ -23,25 +23,25 @@ import com.alibaba.nacos.auth.annotation.Secured; import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.plugin.auth.api.Resource; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.Method; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class ConfigGrpcResourceParserTest { +class ConfigGrpcResourceParserTest { private ConfigGrpcResourceParser resourceParser; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { resourceParser = new ConfigGrpcResourceParser(); } @Test @Secured(signType = Constants.Config.CONFIG_MODULE) - public void testParseWithFullContext() throws NoSuchMethodException { + void testParseWithFullContext() throws NoSuchMethodException { Secured secured = getMethodSecure(); Request request = mockConfigRequest("testNs", "testG", "testD"); Resource actual = resourceParser.parse(request, secured); @@ -53,7 +53,7 @@ public void testParseWithFullContext() throws NoSuchMethodException { @Test @Secured(signType = Constants.Config.CONFIG_MODULE) - public void testParseWithoutNamespace() throws NoSuchMethodException { + void testParseWithoutNamespace() throws NoSuchMethodException { Secured secured = getMethodSecure(); Request request = mockConfigRequest("", "testG", "testD"); Resource actual = resourceParser.parse(request, secured); @@ -65,7 +65,7 @@ public void testParseWithoutNamespace() throws NoSuchMethodException { @Test @Secured(signType = Constants.Config.CONFIG_MODULE) - public void testParseWithoutGroup() throws NoSuchMethodException { + void testParseWithoutGroup() throws NoSuchMethodException { Secured secured = getMethodSecure(); Request request = mockConfigRequest("testNs", "", "testD"); Resource actual = resourceParser.parse(request, secured); @@ -77,7 +77,7 @@ public void testParseWithoutGroup() throws NoSuchMethodException { @Test @Secured(signType = Constants.Config.CONFIG_MODULE) - public void testParseWithoutDataId() throws NoSuchMethodException { + void testParseWithoutDataId() throws NoSuchMethodException { Secured secured = getMethodSecure(); Request request = mockConfigRequest("testNs", "testG", ""); Resource actual = resourceParser.parse(request, secured); @@ -89,7 +89,7 @@ public void testParseWithoutDataId() throws NoSuchMethodException { @Test @Secured(signType = Constants.Config.CONFIG_MODULE) - public void testParseWithConfigBatchListenRequest() throws NoSuchMethodException { + void testParseWithConfigBatchListenRequest() throws NoSuchMethodException { Secured secured = getMethodSecure(); ConfigBatchListenRequest request = new ConfigBatchListenRequest(); request.addConfigListenContext("testG", "testD", "testNs", "111"); @@ -112,7 +112,7 @@ private Secured getMethodSecure() throws NoSuchMethodException { StackTraceElement[] traces = new Exception().getStackTrace(); StackTraceElement callerElement = traces[1]; String methodName = callerElement.getMethodName(); - Method method = this.getClass().getMethod(methodName); + Method method = this.getClass().getDeclaredMethod(methodName); return method.getAnnotation(Secured.class); } } diff --git a/auth/src/test/java/com/alibaba/nacos/auth/parser/grpc/NamingGrpcResourceParserTest.java b/auth/src/test/java/com/alibaba/nacos/auth/parser/grpc/NamingGrpcResourceParserTest.java index a175ba3b365..620ed569875 100644 --- a/auth/src/test/java/com/alibaba/nacos/auth/parser/grpc/NamingGrpcResourceParserTest.java +++ b/auth/src/test/java/com/alibaba/nacos/auth/parser/grpc/NamingGrpcResourceParserTest.java @@ -23,26 +23,26 @@ import com.alibaba.nacos.auth.annotation.Secured; import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.plugin.auth.api.Resource; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.Method; -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; -public class NamingGrpcResourceParserTest { +class NamingGrpcResourceParserTest { private NamingGrpcResourceParser resourceParser; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { resourceParser = new NamingGrpcResourceParser(); } @Test @Secured() - public void testParseWithFullContextForNamingRequest() throws NoSuchMethodException { + void testParseWithFullContextForNamingRequest() throws NoSuchMethodException { Secured secured = getMethodSecure(); AbstractNamingRequest request = mockNamingRequest("testNs", "testG", "testS"); Resource actual = resourceParser.parse(request, secured); @@ -50,13 +50,13 @@ public void testParseWithFullContextForNamingRequest() throws NoSuchMethodExcept assertEquals("testG", actual.getGroup()); assertEquals("testS", actual.getName()); assertEquals(Constants.Naming.NAMING_MODULE, actual.getType()); - assertEquals(MockNamingRequest.class.getSimpleName(), actual.getProperties().getProperty( - com.alibaba.nacos.plugin.auth.constant.Constants.Resource.REQUEST_CLASS)); + assertEquals(MockNamingRequest.class.getSimpleName(), actual.getProperties() + .getProperty(com.alibaba.nacos.plugin.auth.constant.Constants.Resource.REQUEST_CLASS)); } @Test @Secured() - public void testParseWithFullContextForOtherRequest() throws NoSuchMethodException { + void testParseWithFullContextForOtherRequest() throws NoSuchMethodException { Secured secured = getMethodSecure(); Request request = mockOtherRequest("testNs", "testG", "testS"); Resource actual = resourceParser.parse(request, secured); @@ -64,13 +64,13 @@ public void testParseWithFullContextForOtherRequest() throws NoSuchMethodExcepti assertEquals("testG", actual.getGroup()); assertEquals("testS", actual.getName()); assertEquals(Constants.Naming.NAMING_MODULE, actual.getType()); - assertEquals(NotifySubscriberRequest.class.getSimpleName(), actual.getProperties().getProperty( - com.alibaba.nacos.plugin.auth.constant.Constants.Resource.REQUEST_CLASS)); + assertEquals(NotifySubscriberRequest.class.getSimpleName(), actual.getProperties() + .getProperty(com.alibaba.nacos.plugin.auth.constant.Constants.Resource.REQUEST_CLASS)); } @Test @Secured() - public void testParseWithoutNamespaceForNamingRequest() throws NoSuchMethodException { + void testParseWithoutNamespaceForNamingRequest() throws NoSuchMethodException { Secured secured = getMethodSecure(); AbstractNamingRequest request = mockNamingRequest(null, "testG", "testS"); Resource actual = resourceParser.parse(request, secured); @@ -78,13 +78,13 @@ public void testParseWithoutNamespaceForNamingRequest() throws NoSuchMethodExcep assertEquals("testG", actual.getGroup()); assertEquals("testS", actual.getName()); assertEquals(Constants.Naming.NAMING_MODULE, actual.getType()); - assertEquals(MockNamingRequest.class.getSimpleName(), actual.getProperties().getProperty( - com.alibaba.nacos.plugin.auth.constant.Constants.Resource.REQUEST_CLASS)); + assertEquals(MockNamingRequest.class.getSimpleName(), actual.getProperties() + .getProperty(com.alibaba.nacos.plugin.auth.constant.Constants.Resource.REQUEST_CLASS)); } @Test @Secured() - public void testParseWithoutNamespaceForOtherRequest() throws NoSuchMethodException { + void testParseWithoutNamespaceForOtherRequest() throws NoSuchMethodException { Secured secured = getMethodSecure(); Request request = mockOtherRequest(null, "testG", "testS"); Resource actual = resourceParser.parse(request, secured); @@ -92,13 +92,13 @@ public void testParseWithoutNamespaceForOtherRequest() throws NoSuchMethodExcept assertEquals("testG", actual.getGroup()); assertEquals("testS", actual.getName()); assertEquals(Constants.Naming.NAMING_MODULE, actual.getType()); - assertEquals(NotifySubscriberRequest.class.getSimpleName(), actual.getProperties().getProperty( - com.alibaba.nacos.plugin.auth.constant.Constants.Resource.REQUEST_CLASS)); + assertEquals(NotifySubscriberRequest.class.getSimpleName(), actual.getProperties() + .getProperty(com.alibaba.nacos.plugin.auth.constant.Constants.Resource.REQUEST_CLASS)); } @Test @Secured() - public void testParseWithoutGroupForNamingRequest() throws NoSuchMethodException { + void testParseWithoutGroupForNamingRequest() throws NoSuchMethodException { Secured secured = getMethodSecure(); AbstractNamingRequest request = mockNamingRequest("testNs", null, "testS"); Resource actual = resourceParser.parse(request, secured); @@ -106,13 +106,13 @@ public void testParseWithoutGroupForNamingRequest() throws NoSuchMethodException assertEquals(StringUtils.EMPTY, actual.getGroup()); assertEquals("testS", actual.getName()); assertEquals(Constants.Naming.NAMING_MODULE, actual.getType()); - assertEquals(MockNamingRequest.class.getSimpleName(), actual.getProperties().getProperty( - com.alibaba.nacos.plugin.auth.constant.Constants.Resource.REQUEST_CLASS)); + assertEquals(MockNamingRequest.class.getSimpleName(), actual.getProperties() + .getProperty(com.alibaba.nacos.plugin.auth.constant.Constants.Resource.REQUEST_CLASS)); } @Test @Secured() - public void testParseWithoutGroupForOtherRequest() throws NoSuchMethodException { + void testParseWithoutGroupForOtherRequest() throws NoSuchMethodException { Secured secured = getMethodSecure(); Request request = mockOtherRequest("testNs", null, "testS"); Resource actual = resourceParser.parse(request, secured); @@ -120,13 +120,13 @@ public void testParseWithoutGroupForOtherRequest() throws NoSuchMethodException assertEquals(StringUtils.EMPTY, actual.getGroup()); assertEquals("testS", actual.getName()); assertEquals(Constants.Naming.NAMING_MODULE, actual.getType()); - assertEquals(NotifySubscriberRequest.class.getSimpleName(), actual.getProperties().getProperty( - com.alibaba.nacos.plugin.auth.constant.Constants.Resource.REQUEST_CLASS)); + assertEquals(NotifySubscriberRequest.class.getSimpleName(), actual.getProperties() + .getProperty(com.alibaba.nacos.plugin.auth.constant.Constants.Resource.REQUEST_CLASS)); } @Test @Secured() - public void testParseWithoutDataIdForNamingRequest() throws NoSuchMethodException { + void testParseWithoutDataIdForNamingRequest() throws NoSuchMethodException { Secured secured = getMethodSecure(); AbstractNamingRequest request = mockNamingRequest("testNs", "testG", null); Resource actual = resourceParser.parse(request, secured); @@ -134,13 +134,13 @@ public void testParseWithoutDataIdForNamingRequest() throws NoSuchMethodExceptio assertEquals("testG", actual.getGroup()); assertEquals(StringUtils.EMPTY, actual.getName()); assertEquals(Constants.Naming.NAMING_MODULE, actual.getType()); - assertEquals(MockNamingRequest.class.getSimpleName(), actual.getProperties().getProperty( - com.alibaba.nacos.plugin.auth.constant.Constants.Resource.REQUEST_CLASS)); + assertEquals(MockNamingRequest.class.getSimpleName(), actual.getProperties() + .getProperty(com.alibaba.nacos.plugin.auth.constant.Constants.Resource.REQUEST_CLASS)); } @Test @Secured() - public void testParseWithoutDataIdForOtherRequest() throws NoSuchMethodException { + void testParseWithoutDataIdForOtherRequest() throws NoSuchMethodException { Secured secured = getMethodSecure(); Request request = mockOtherRequest("testNs", "testG", null); Resource actual = resourceParser.parse(request, secured); @@ -148,8 +148,8 @@ public void testParseWithoutDataIdForOtherRequest() throws NoSuchMethodException assertEquals("testG", actual.getGroup()); assertEquals(StringUtils.EMPTY, actual.getName()); assertEquals(Constants.Naming.NAMING_MODULE, actual.getType()); - assertEquals(NotifySubscriberRequest.class.getSimpleName(), actual.getProperties().getProperty( - com.alibaba.nacos.plugin.auth.constant.Constants.Resource.REQUEST_CLASS)); + assertEquals(NotifySubscriberRequest.class.getSimpleName(), actual.getProperties() + .getProperty(com.alibaba.nacos.plugin.auth.constant.Constants.Resource.REQUEST_CLASS)); } private AbstractNamingRequest mockNamingRequest(String testNs, String testG, String testS) { @@ -172,7 +172,7 @@ private Secured getMethodSecure() throws NoSuchMethodException { StackTraceElement[] traces = new Exception().getStackTrace(); StackTraceElement callerElement = traces[1]; String methodName = callerElement.getMethodName(); - Method method = this.getClass().getMethod(methodName); + Method method = this.getClass().getDeclaredMethod(methodName); return method.getAnnotation(Secured.class); } diff --git a/auth/src/test/java/com/alibaba/nacos/auth/parser/http/ConfigHttpResourceParserTest.java b/auth/src/test/java/com/alibaba/nacos/auth/parser/http/ConfigHttpResourceParserTest.java index a9297c3c229..600dd64ed63 100644 --- a/auth/src/test/java/com/alibaba/nacos/auth/parser/http/ConfigHttpResourceParserTest.java +++ b/auth/src/test/java/com/alibaba/nacos/auth/parser/http/ConfigHttpResourceParserTest.java @@ -20,53 +20,85 @@ import com.alibaba.nacos.auth.annotation.Secured; import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.plugin.auth.api.Resource; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import javax.servlet.http.HttpServletRequest; - import java.lang.reflect.Method; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.eq; -@RunWith(MockitoJUnitRunner.class) -public class ConfigHttpResourceParserTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class ConfigHttpResourceParserTest { @Mock private HttpServletRequest request; private ConfigHttpResourceParser resourceParser; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { resourceParser = new ConfigHttpResourceParser(); } @Test @Secured(signType = Constants.Config.CONFIG_MODULE) - public void testParseWithFullContext() throws NoSuchMethodException { + void testParseWithFullContext() throws NoSuchMethodException { Secured secured = getMethodSecure(); Mockito.when(request.getParameter(eq("tenant"))).thenReturn("testNs"); Mockito.when(request.getParameter(eq(Constants.GROUP))).thenReturn("testG"); - Mockito.when(request.getParameter(eq(Constants.DATAID))).thenReturn("testD"); + Mockito.when(request.getParameter(eq(Constants.DATA_ID))).thenReturn("testD"); + Resource actual = resourceParser.parse(request, secured); + assertEquals("testNs", actual.getNamespaceId()); + assertEquals("testG", actual.getGroup()); + assertEquals("testD", actual.getName()); + assertEquals(Constants.Config.CONFIG_MODULE, actual.getType()); + } + + @Test + @Secured(signType = Constants.Config.CONFIG_MODULE) + void testParseWithNamespaceId() throws NoSuchMethodException { + Secured secured = getMethodSecure(); + Mockito.when(request.getParameter(eq("namespaceId"))).thenReturn("testNs"); + Mockito.when(request.getParameter(eq(Constants.GROUP))).thenReturn("testG"); + Mockito.when(request.getParameter(eq(Constants.DATA_ID))).thenReturn("testD"); Resource actual = resourceParser.parse(request, secured); assertEquals("testNs", actual.getNamespaceId()); assertEquals("testG", actual.getGroup()); assertEquals("testD", actual.getName()); assertEquals(Constants.Config.CONFIG_MODULE, actual.getType()); } + + @Test + @Secured(signType = Constants.Config.CONFIG_MODULE) + void testParseWithNamespaceIdFirst() throws NoSuchMethodException { + Secured secured = getMethodSecure(); + Mockito.when(request.getParameter(eq("tenant"))).thenReturn("testNs"); + Mockito.when(request.getParameter(eq("namespaceId"))).thenReturn("testNsFirst"); + Mockito.when(request.getParameter(eq(Constants.GROUP))).thenReturn("testG"); + Mockito.when(request.getParameter(eq(Constants.DATA_ID))).thenReturn("testD"); + Resource actual = resourceParser.parse(request, secured); + assertEquals("testNsFirst", actual.getNamespaceId()); + assertEquals("testG", actual.getGroup()); + assertEquals("testD", actual.getName()); + assertEquals(Constants.Config.CONFIG_MODULE, actual.getType()); + } @Test @Secured(signType = Constants.Config.CONFIG_MODULE) - public void testParseWithoutNamespace() throws NoSuchMethodException { + void testParseWithoutNamespace() throws NoSuchMethodException { Secured secured = getMethodSecure(); Mockito.when(request.getParameter(eq(Constants.GROUP))).thenReturn("testG"); - Mockito.when(request.getParameter(eq(Constants.DATAID))).thenReturn("testD"); + Mockito.when(request.getParameter(eq(Constants.DATA_ID))).thenReturn("testD"); Resource actual = resourceParser.parse(request, secured); assertEquals(StringUtils.EMPTY, actual.getNamespaceId()); assertEquals("testG", actual.getGroup()); @@ -76,10 +108,10 @@ public void testParseWithoutNamespace() throws NoSuchMethodException { @Test @Secured(signType = Constants.Config.CONFIG_MODULE) - public void testParseWithoutGroup() throws NoSuchMethodException { + void testParseWithoutGroup() throws NoSuchMethodException { Secured secured = getMethodSecure(); Mockito.when(request.getParameter(eq("tenant"))).thenReturn("testNs"); - Mockito.when(request.getParameter(eq(Constants.DATAID))).thenReturn("testD"); + Mockito.when(request.getParameter(eq(Constants.DATA_ID))).thenReturn("testD"); Resource actual = resourceParser.parse(request, secured); assertEquals("testNs", actual.getNamespaceId()); assertEquals(StringUtils.EMPTY, actual.getGroup()); @@ -89,7 +121,7 @@ public void testParseWithoutGroup() throws NoSuchMethodException { @Test @Secured(signType = Constants.Config.CONFIG_MODULE) - public void testParseWithoutDataId() throws NoSuchMethodException { + void testParseWithoutDataId() throws NoSuchMethodException { Secured secured = getMethodSecure(); Mockito.when(request.getParameter(eq("tenant"))).thenReturn("testNs"); Mockito.when(request.getParameter(eq(Constants.GROUP))).thenReturn("testG"); @@ -104,7 +136,7 @@ private Secured getMethodSecure() throws NoSuchMethodException { StackTraceElement[] traces = new Exception().getStackTrace(); StackTraceElement callerElement = traces[1]; String methodName = callerElement.getMethodName(); - Method method = this.getClass().getMethod(methodName); + Method method = this.getClass().getDeclaredMethod(methodName); return method.getAnnotation(Secured.class); } } diff --git a/auth/src/test/java/com/alibaba/nacos/auth/parser/http/NamingHttpResourceParserTest.java b/auth/src/test/java/com/alibaba/nacos/auth/parser/http/NamingHttpResourceParserTest.java index d0ca3815c35..c740f7c60c1 100644 --- a/auth/src/test/java/com/alibaba/nacos/auth/parser/http/NamingHttpResourceParserTest.java +++ b/auth/src/test/java/com/alibaba/nacos/auth/parser/http/NamingHttpResourceParserTest.java @@ -21,37 +21,40 @@ import com.alibaba.nacos.auth.annotation.Secured; import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.plugin.auth.api.Resource; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import javax.servlet.http.HttpServletRequest; - import java.lang.reflect.Method; -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; import static org.mockito.ArgumentMatchers.eq; -@RunWith(MockitoJUnitRunner.class) -public class NamingHttpResourceParserTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class NamingHttpResourceParserTest { @Mock private HttpServletRequest request; private NamingHttpResourceParser resourceParser; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { resourceParser = new NamingHttpResourceParser(); } @Test @Secured() - public void testParseWithFullContext() throws NoSuchMethodException { + void testParseWithFullContext() throws NoSuchMethodException { Secured secured = getMethodSecure(); Mockito.when(request.getParameter(eq(CommonParams.NAMESPACE_ID))).thenReturn("testNs"); Mockito.when(request.getParameter(eq(CommonParams.GROUP_NAME))).thenReturn("testG"); @@ -65,7 +68,7 @@ public void testParseWithFullContext() throws NoSuchMethodException { @Test @Secured() - public void testParseWithoutNamespace() throws NoSuchMethodException { + void testParseWithoutNamespace() throws NoSuchMethodException { Secured secured = getMethodSecure(); Mockito.when(request.getParameter(eq(CommonParams.GROUP_NAME))).thenReturn("testG"); Mockito.when(request.getParameter(eq(CommonParams.SERVICE_NAME))).thenReturn("testS"); @@ -78,7 +81,7 @@ public void testParseWithoutNamespace() throws NoSuchMethodException { @Test @Secured() - public void testParseWithoutGroup() throws NoSuchMethodException { + void testParseWithoutGroup() throws NoSuchMethodException { Secured secured = getMethodSecure(); Mockito.when(request.getParameter(eq(CommonParams.NAMESPACE_ID))).thenReturn("testNs"); Mockito.when(request.getParameter(eq(CommonParams.SERVICE_NAME))).thenReturn("testS"); @@ -91,7 +94,7 @@ public void testParseWithoutGroup() throws NoSuchMethodException { @Test @Secured() - public void testParseWithGroupInService() throws NoSuchMethodException { + void testParseWithGroupInService() throws NoSuchMethodException { Secured secured = getMethodSecure(); Mockito.when(request.getParameter(eq(CommonParams.NAMESPACE_ID))).thenReturn("testNs"); Mockito.when(request.getParameter(eq(CommonParams.SERVICE_NAME))).thenReturn("testG@@testS"); @@ -104,7 +107,7 @@ public void testParseWithGroupInService() throws NoSuchMethodException { @Test @Secured() - public void testParseWithoutService() throws NoSuchMethodException { + void testParseWithoutService() throws NoSuchMethodException { Secured secured = getMethodSecure(); Mockito.when(request.getParameter(eq(CommonParams.NAMESPACE_ID))).thenReturn("testNs"); Mockito.when(request.getParameter(eq(CommonParams.GROUP_NAME))).thenReturn("testG"); @@ -117,7 +120,7 @@ public void testParseWithoutService() throws NoSuchMethodException { @Test @Secured() - public void testParseWithoutGroupAndService() throws NoSuchMethodException { + void testParseWithoutGroupAndService() throws NoSuchMethodException { Secured secured = getMethodSecure(); Mockito.when(request.getParameter(eq(CommonParams.NAMESPACE_ID))).thenReturn("testNs"); Resource actual = resourceParser.parse(request, secured); @@ -129,7 +132,7 @@ public void testParseWithoutGroupAndService() throws NoSuchMethodException { @Test @Secured(tags = {"testTag"}) - public void testParseWithTags() throws NoSuchMethodException { + void testParseWithTags() throws NoSuchMethodException { Secured secured = getMethodSecure(); Mockito.when(request.getParameter(eq(CommonParams.NAMESPACE_ID))).thenReturn("testNs"); Mockito.when(request.getParameter(eq(CommonParams.GROUP_NAME))).thenReturn("testG"); @@ -146,7 +149,7 @@ private Secured getMethodSecure() throws NoSuchMethodException { StackTraceElement[] traces = new Exception().getStackTrace(); StackTraceElement callerElement = traces[1]; String methodName = callerElement.getMethodName(); - Method method = this.getClass().getMethod(methodName); + Method method = this.getClass().getDeclaredMethod(methodName); return method.getAnnotation(Secured.class); } } diff --git a/auth/src/test/resources/META-INF/services/com.alibaba.nacos.plugin.auth.spi.server.AuthPluginService b/auth/src/test/resources/META-INF/services/com.alibaba.nacos.plugin.auth.spi.server.AuthPluginService index 028c68cb82c..9cbb51e25e1 100644 --- a/auth/src/test/resources/META-INF/services/com.alibaba.nacos.plugin.auth.spi.server.AuthPluginService +++ b/auth/src/test/resources/META-INF/services/com.alibaba.nacos.plugin.auth.spi.server.AuthPluginService @@ -15,3 +15,4 @@ # com.alibaba.nacos.auth.mock.MockAuthPluginService +com.alibaba.nacos.auth.mock.MockAuthPluginServiceB diff --git a/client/pom.xml b/client/pom.xml index 759ed87e39a..d1a32feb191 100644 --- a/client/pom.xml +++ b/client/pom.xml @@ -64,13 +64,16 @@ com.alibaba.nacos nacos-logback-adapter-12 - ${project.version} + + + + com.alibaba.nacos + logback-adapter com.alibaba.nacos nacos-log4j2-adapter - ${project.version} diff --git a/client/src/main/java/com/alibaba/nacos/client/auth/impl/NacosClientAuthServiceImpl.java b/client/src/main/java/com/alibaba/nacos/client/auth/impl/NacosClientAuthServiceImpl.java index 9b4b8898068..c374c1a9b77 100644 --- a/client/src/main/java/com/alibaba/nacos/client/auth/impl/NacosClientAuthServiceImpl.java +++ b/client/src/main/java/com/alibaba/nacos/client/auth/impl/NacosClientAuthServiceImpl.java @@ -88,10 +88,11 @@ public Boolean login(Properties properties) { tokenTtl = Long.parseLong(identityContext.getParameter(NacosAuthLoginConstant.TOKENTTL)); tokenRefreshWindow = tokenTtl / 10; lastRefreshTime = System.currentTimeMillis(); - - loginIdentityContext = new LoginIdentityContext(); - loginIdentityContext.setParameter(NacosAuthLoginConstant.ACCESSTOKEN, + + LoginIdentityContext newCtx = new LoginIdentityContext(); + newCtx.setParameter(NacosAuthLoginConstant.ACCESSTOKEN, identityContext.getParameter(NacosAuthLoginConstant.ACCESSTOKEN)); + this.loginIdentityContext = newCtx; } return true; } diff --git a/client/src/main/java/com/alibaba/nacos/client/auth/ram/RamClientAuthServiceImpl.java b/client/src/main/java/com/alibaba/nacos/client/auth/ram/RamClientAuthServiceImpl.java index 70289cdd971..e66565d084a 100644 --- a/client/src/main/java/com/alibaba/nacos/client/auth/ram/RamClientAuthServiceImpl.java +++ b/client/src/main/java/com/alibaba/nacos/client/auth/ram/RamClientAuthServiceImpl.java @@ -22,6 +22,7 @@ import com.alibaba.nacos.client.auth.ram.injector.AbstractResourceInjector; import com.alibaba.nacos.client.auth.ram.injector.ConfigResourceInjector; import com.alibaba.nacos.client.auth.ram.injector.NamingResourceInjector; +import com.alibaba.nacos.client.auth.ram.utils.RamUtil; import com.alibaba.nacos.client.auth.ram.utils.SpasAdapter; import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext; @@ -63,6 +64,7 @@ public Boolean login(Properties properties) { loadRoleName(properties); loadAccessKey(properties); loadSecretKey(properties); + loadRegionId(properties); return true; } @@ -75,13 +77,16 @@ private void loadRoleName(Properties properties) { } private void loadAccessKey(Properties properties) { - String accessKey = properties.getProperty(PropertyKeyConst.ACCESS_KEY); - ramContext.setAccessKey(StringUtils.isBlank(accessKey) ? SpasAdapter.getAk() : accessKey); + ramContext.setAccessKey(RamUtil.getAccessKey(properties)); } private void loadSecretKey(Properties properties) { - String secretKey = properties.getProperty(PropertyKeyConst.SECRET_KEY); - ramContext.setSecretKey(StringUtils.isBlank(secretKey) ? SpasAdapter.getSk() : secretKey); + ramContext.setSecretKey(RamUtil.getSecretKey(properties)); + } + + private void loadRegionId(Properties properties) { + String regionId = properties.getProperty(PropertyKeyConst.SIGNATURE_REGION_ID); + ramContext.setRegionId(regionId); } @Override diff --git a/client/src/main/java/com/alibaba/nacos/client/auth/ram/RamConstants.java b/client/src/main/java/com/alibaba/nacos/client/auth/ram/RamConstants.java new file mode 100644 index 00000000000..0604630b20b --- /dev/null +++ b/client/src/main/java/com/alibaba/nacos/client/auth/ram/RamConstants.java @@ -0,0 +1,34 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.client.auth.ram; + +/** + * Ram auth plugin constants. + * + * @author xiweng.yy + */ +public class RamConstants { + + public static final String SIGNATURE_VERSION = "signatureVersion"; + + public static final String V4 = "v4"; + + public static final String SIGNATURE_V4_METHOD = "HmacSHA256"; + + public static final String SIGNATURE_V4_PRODUCE = "mse-nacos"; + +} diff --git a/client/src/main/java/com/alibaba/nacos/client/auth/ram/RamContext.java b/client/src/main/java/com/alibaba/nacos/client/auth/ram/RamContext.java index c7ed4a5735e..a9d73bb5339 100644 --- a/client/src/main/java/com/alibaba/nacos/client/auth/ram/RamContext.java +++ b/client/src/main/java/com/alibaba/nacos/client/auth/ram/RamContext.java @@ -31,6 +31,8 @@ public class RamContext { private String ramRoleName; + private String regionId; + public String getAccessKey() { return accessKey; } @@ -55,6 +57,14 @@ public void setRamRoleName(String ramRoleName) { this.ramRoleName = ramRoleName; } + public String getRegionId() { + return regionId; + } + + public void setRegionId(String regionId) { + this.regionId = regionId; + } + public boolean validate() { return StringUtils.isNotBlank(ramRoleName) || StringUtils.isNotBlank(accessKey) && StringUtils .isNotBlank(secretKey); diff --git a/client/src/main/java/com/alibaba/nacos/client/auth/ram/injector/AbstractResourceInjector.java b/client/src/main/java/com/alibaba/nacos/client/auth/ram/injector/AbstractResourceInjector.java index 3467f393aa4..41590ab14f5 100644 --- a/client/src/main/java/com/alibaba/nacos/client/auth/ram/injector/AbstractResourceInjector.java +++ b/client/src/main/java/com/alibaba/nacos/client/auth/ram/injector/AbstractResourceInjector.java @@ -16,8 +16,8 @@ package com.alibaba.nacos.client.auth.ram.injector; -import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext; import com.alibaba.nacos.client.auth.ram.RamContext; +import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext; import com.alibaba.nacos.plugin.auth.api.RequestResource; /** diff --git a/client/src/main/java/com/alibaba/nacos/client/auth/ram/injector/ConfigResourceInjector.java b/client/src/main/java/com/alibaba/nacos/client/auth/ram/injector/ConfigResourceInjector.java index f8d12577be4..5b2cbeee9a7 100644 --- a/client/src/main/java/com/alibaba/nacos/client/auth/ram/injector/ConfigResourceInjector.java +++ b/client/src/main/java/com/alibaba/nacos/client/auth/ram/injector/ConfigResourceInjector.java @@ -16,11 +16,13 @@ package com.alibaba.nacos.client.auth.ram.injector; +import com.alibaba.nacos.client.auth.ram.RamConstants; import com.alibaba.nacos.client.auth.ram.RamContext; import com.alibaba.nacos.client.auth.ram.identify.IdentifyConstants; import com.alibaba.nacos.client.auth.ram.identify.StsConfig; import com.alibaba.nacos.client.auth.ram.identify.StsCredential; import com.alibaba.nacos.client.auth.ram.identify.StsCredentialHolder; +import com.alibaba.nacos.client.auth.ram.utils.CalculateV4SigningKeyUtil; import com.alibaba.nacos.client.auth.ram.utils.SpasAdapter; import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext; @@ -54,8 +56,14 @@ public void doInject(RequestResource resource, RamContext context, LoginIdentity if (StringUtils.isNotEmpty(accessKey) && StringUtils.isNotBlank(secretKey)) { result.setParameter(ACCESS_KEY_HEADER, accessKey); } + String signatureKey = secretKey; + if (StringUtils.isNotEmpty(context.getRegionId())) { + signatureKey = CalculateV4SigningKeyUtil + .finalSigningKeyStringWithDefaultInfo(secretKey, context.getRegionId()); + result.setParameter(RamConstants.SIGNATURE_VERSION, RamConstants.V4); + } Map signHeaders = SpasAdapter - .getSignHeaders(getResource(resource.getNamespace(), resource.getGroup()), secretKey); + .getSignHeaders(getResource(resource.getNamespace(), resource.getGroup()), signatureKey); result.setParameters(signHeaders); } diff --git a/client/src/main/java/com/alibaba/nacos/client/auth/ram/injector/NamingResourceInjector.java b/client/src/main/java/com/alibaba/nacos/client/auth/ram/injector/NamingResourceInjector.java index fa90cc0d780..42e11510552 100644 --- a/client/src/main/java/com/alibaba/nacos/client/auth/ram/injector/NamingResourceInjector.java +++ b/client/src/main/java/com/alibaba/nacos/client/auth/ram/injector/NamingResourceInjector.java @@ -18,15 +18,17 @@ import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.naming.utils.NamingUtils; +import com.alibaba.nacos.client.auth.ram.RamConstants; +import com.alibaba.nacos.client.auth.ram.RamContext; import com.alibaba.nacos.client.auth.ram.identify.IdentifyConstants; import com.alibaba.nacos.client.auth.ram.identify.StsConfig; import com.alibaba.nacos.client.auth.ram.identify.StsCredential; import com.alibaba.nacos.client.auth.ram.identify.StsCredentialHolder; -import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext; -import com.alibaba.nacos.client.auth.ram.RamContext; -import com.alibaba.nacos.plugin.auth.api.RequestResource; +import com.alibaba.nacos.client.auth.ram.utils.CalculateV4SigningKeyUtil; import com.alibaba.nacos.client.auth.ram.utils.SignUtil; import com.alibaba.nacos.common.utils.StringUtils; +import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext; +import com.alibaba.nacos.plugin.auth.api.RequestResource; import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER; @@ -56,8 +58,14 @@ public void doInject(RequestResource resource, RamContext context, LoginIdentity secretKey = stsCredential.getAccessKeySecret(); result.setParameter(IdentifyConstants.SECURITY_TOKEN_HEADER, stsCredential.getSecurityToken()); } + String signatureKey = secretKey; + if (StringUtils.isNotEmpty(context.getRegionId())) { + signatureKey = CalculateV4SigningKeyUtil + .finalSigningKeyStringWithDefaultInfo(secretKey, context.getRegionId()); + result.setParameter(RamConstants.SIGNATURE_VERSION, RamConstants.V4); + } String signData = getSignData(getGroupedServiceName(resource)); - String signature = SignUtil.sign(signData, secretKey); + String signature = SignUtil.sign(signData, signatureKey); result.setParameter(SIGNATURE_FILED, signature); result.setParameter(DATA_FILED, signData); result.setParameter(AK_FILED, accessKey); @@ -68,7 +76,8 @@ public void doInject(RequestResource resource, RamContext context, LoginIdentity } private String getGroupedServiceName(RequestResource resource) { - if (resource.getResource().contains(Constants.SERVICE_INFO_SPLITER) || StringUtils.isBlank(resource.getGroup())) { + if (resource.getResource().contains(Constants.SERVICE_INFO_SPLITER) || StringUtils + .isBlank(resource.getGroup())) { return resource.getResource(); } return NamingUtils.getGroupedNameOptional(resource.getResource(), resource.getGroup()); diff --git a/client/src/main/java/com/alibaba/nacos/client/auth/ram/utils/CalculateV4SigningKeyUtil.java b/client/src/main/java/com/alibaba/nacos/client/auth/ram/utils/CalculateV4SigningKeyUtil.java new file mode 100644 index 00000000000..2a157177fb7 --- /dev/null +++ b/client/src/main/java/com/alibaba/nacos/client/auth/ram/utils/CalculateV4SigningKeyUtil.java @@ -0,0 +1,112 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.client.auth.ram.utils; + +import com.alibaba.nacos.client.auth.ram.RamConstants; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.Base64; + +/** + * CalculateV4SigningKeyUtil. + * + * @author xiweng.yy + */ +public class CalculateV4SigningKeyUtil { + + private static final String PREFIX = "aliyun_v4"; + + private static final String CONSTANT = "aliyun_v4_request"; + + private static final DateTimeFormatter V4_SIGN_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd"); + + private static final ZoneId UTC_0 = ZoneId.of("GMT+00:00"); + + private static byte[] firstSigningKey(String secret, String date, String signMethod) + throws NoSuchAlgorithmException, InvalidKeyException { + Mac mac = Mac.getInstance(signMethod); + mac.init(new SecretKeySpec((PREFIX + secret).getBytes(StandardCharsets.UTF_8), signMethod)); + return mac.doFinal(date.getBytes(StandardCharsets.UTF_8)); + } + + private static byte[] regionSigningKey(String secret, String date, String region, String signMethod) + throws NoSuchAlgorithmException, InvalidKeyException { + byte[] firstSignkey = firstSigningKey(secret, date, signMethod); + Mac mac = Mac.getInstance(signMethod); + mac.init(new SecretKeySpec(firstSignkey, signMethod)); + return mac.doFinal(region.getBytes(StandardCharsets.UTF_8)); + } + + private static byte[] finalSigningKey(String secret, String date, String region, String productCode, + String signMethod) { + try { + byte[] secondSignkey = regionSigningKey(secret, date, region, signMethod); + Mac mac = Mac.getInstance(signMethod); + mac.init(new SecretKeySpec(secondSignkey, signMethod)); + byte[] thirdSigningKey = mac.doFinal(productCode.getBytes(StandardCharsets.UTF_8)); + // 计算最终派生秘钥 + mac = Mac.getInstance(signMethod); + mac.init(new SecretKeySpec(thirdSigningKey, signMethod)); + return mac.doFinal(CONSTANT.getBytes(StandardCharsets.UTF_8)); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException("unsupported Algorithm:" + signMethod); + } catch (InvalidKeyException e) { + throw new RuntimeException("InvalidKey"); + } + } + + /** + * Return V4 signature key with base64 encode. + * + * @param secret secret key + * @param date date with utc format, like 20211222 + * @param region region id + * @param productCode cloud product code + * @param signMethod sign method + * @return V4 signature key with base64 encode + */ + public static String finalSigningKeyString(String secret, String date, String region, String productCode, + String signMethod) { + return Base64.getEncoder().encodeToString(finalSigningKey(secret, date, region, productCode, signMethod)); + } + + /** + * Return V4 signature key with base64 encode for some default information. + * + *
  • + *
      date = current date
    + *
      produceCode = mse
    + *
      signMethod = HMAC-SHA256
    + *
  • + * + * @param secret secret key + * @param region region id + * @return V4 signature key with base64 encode + */ + public static String finalSigningKeyStringWithDefaultInfo(String secret, String region) { + String signDate = LocalDateTime.now(UTC_0).format(V4_SIGN_DATE_FORMATTER); + return finalSigningKeyString(secret, signDate, region, RamConstants.SIGNATURE_V4_PRODUCE, + RamConstants.SIGNATURE_V4_METHOD); + } +} diff --git a/client/src/main/java/com/alibaba/nacos/client/auth/ram/utils/RamUtil.java b/client/src/main/java/com/alibaba/nacos/client/auth/ram/utils/RamUtil.java new file mode 100644 index 00000000000..ee3db5018e3 --- /dev/null +++ b/client/src/main/java/com/alibaba/nacos/client/auth/ram/utils/RamUtil.java @@ -0,0 +1,58 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.client.auth.ram.utils; + +import com.alibaba.nacos.api.PropertyKeyConst; +import com.alibaba.nacos.api.SystemPropertyKeyConst; +import com.alibaba.nacos.api.common.Constants; +import com.alibaba.nacos.common.utils.StringUtils; + +import java.util.Properties; + +/** + * Util to get ram info, such as AK, SK and RAM role. + * + * @author xiweng.yy + */ +public class RamUtil { + + public static String getAccessKey(Properties properties) { + boolean isUseRamInfoParsing = Boolean.parseBoolean(properties + .getProperty(PropertyKeyConst.IS_USE_RAM_INFO_PARSING, + System.getProperty(SystemPropertyKeyConst.IS_USE_RAM_INFO_PARSING, + Constants.DEFAULT_USE_RAM_INFO_PARSING))); + + String result = properties.getProperty(PropertyKeyConst.ACCESS_KEY); + if (isUseRamInfoParsing && StringUtils.isBlank(result)) { + result = SpasAdapter.getAk(); + } + return result; + } + + public static String getSecretKey(Properties properties) { + boolean isUseRamInfoParsing = Boolean.parseBoolean(properties + .getProperty(PropertyKeyConst.IS_USE_RAM_INFO_PARSING, + System.getProperty(SystemPropertyKeyConst.IS_USE_RAM_INFO_PARSING, + Constants.DEFAULT_USE_RAM_INFO_PARSING))); + + String result = properties.getProperty(PropertyKeyConst.SECRET_KEY); + if (isUseRamInfoParsing && StringUtils.isBlank(result)) { + result = SpasAdapter.getSk(); + } + return result; + } +} diff --git a/client/src/main/java/com/alibaba/nacos/client/config/NacosConfigService.java b/client/src/main/java/com/alibaba/nacos/client/config/NacosConfigService.java index 3867e26f417..14100627403 100644 --- a/client/src/main/java/com/alibaba/nacos/client/config/NacosConfigService.java +++ b/client/src/main/java/com/alibaba/nacos/client/config/NacosConfigService.java @@ -76,6 +76,7 @@ public class NacosConfigService implements ConfigService { public NacosConfigService(Properties properties) throws NacosException { PreInitUtils.asyncPreLoadCostComponent(); final NacosClientProperties clientProperties = NacosClientProperties.PROTOTYPE.derive(properties); + LOGGER.info(ParamUtil.getInputParameters(clientProperties.asProperties())); ValidatorUtils.checkInitParam(clientProperties); initNamespace(clientProperties); diff --git a/client/src/main/java/com/alibaba/nacos/client/config/impl/ClientWorker.java b/client/src/main/java/com/alibaba/nacos/client/config/impl/ClientWorker.java index 17e43f7d132..61b05615716 100644 --- a/client/src/main/java/com/alibaba/nacos/client/config/impl/ClientWorker.java +++ b/client/src/main/java/com/alibaba/nacos/client/config/impl/ClientWorker.java @@ -61,6 +61,7 @@ import com.alibaba.nacos.common.remote.client.RpcClient; import com.alibaba.nacos.common.remote.client.RpcClientFactory; import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig; +import com.alibaba.nacos.common.remote.client.RpcClientTlsConfigFactory; import com.alibaba.nacos.common.remote.client.ServerListFactory; import com.alibaba.nacos.common.utils.ConnLabelsUtils; import com.alibaba.nacos.common.utils.ConvertUtils; @@ -128,6 +129,8 @@ public class ClientWorker implements Closeable { */ private final AtomicReference> cacheMap = new AtomicReference<>(new HashMap<>()); + private final DefaultLabelsCollectorManager defaultLabelsCollectorManager = new DefaultLabelsCollectorManager(); + private Map appLables = new HashMap<>(); private final ConfigFilterChainManager configFilterChainManager; @@ -579,8 +582,6 @@ public boolean isHealthServer() { return agent.isHealthServer(); } - private static DefaultLabelsCollectorManager defaultLabelsCollectorManager = new DefaultLabelsCollectorManager(); - public class ConfigRpcTransportClient extends ConfigTransportClient { Map multiTaskExecutor = new HashMap<>(); @@ -1088,18 +1089,19 @@ private boolean checkListenCache(Map> listenCachesMap) t private RpcClient ensureRpcClient(String taskId) throws NacosException { synchronized (ClientWorker.this) { - Map labels = getLabels(); Map newLabels = new HashMap<>(labels); newLabels.put("taskId", taskId); + RpcClientTlsConfig clientTlsConfig = RpcClientTlsConfigFactory.getInstance() + .createSdkConfig(properties); RpcClient rpcClient = RpcClientFactory.createClient(uuid + "_config-" + taskId, getConnectionType(), - newLabels, this.properties, RpcClientTlsConfig.properties(this.properties)); + newLabels, clientTlsConfig); if (rpcClient.isWaitInitiated()) { initRpcClientHandler(rpcClient); rpcClient.setTenant(getTenant()); rpcClient.start(); } - + return rpcClient; } diff --git a/client/src/main/java/com/alibaba/nacos/client/config/impl/ServerListManager.java b/client/src/main/java/com/alibaba/nacos/client/config/impl/ServerListManager.java index b3904b01bf5..52b1ad886bb 100644 --- a/client/src/main/java/com/alibaba/nacos/client/config/impl/ServerListManager.java +++ b/client/src/main/java/com/alibaba/nacos/client/config/impl/ServerListManager.java @@ -293,7 +293,8 @@ private void initEndpointPort(NacosClientProperties properties) { } private void initServerListName(NacosClientProperties properties) { - String serverListNameTmp = properties.getProperty(PropertyKeyConst.CLUSTER_NAME); + String serverListNameTmp = properties.getProperty(PropertyKeyConst.ENDPOINT_CLUSTER_NAME, + properties.getProperty(PropertyKeyConst.CLUSTER_NAME)); if (!StringUtils.isBlank(serverListNameTmp)) { this.serverListName = serverListNameTmp; } @@ -317,7 +318,7 @@ private void initEndpoint(final NacosClientProperties properties) { if (StringUtils.isNotBlank(endpointUrl)) { this.serverAddrsStr = ""; } - this.endpoint = endpointUrl; + endpointTmp = endpointUrl; } this.endpoint = StringUtils.isNotBlank(endpointTmp) ? endpointTmp : ""; } diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java b/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java index da7983574ee..7bab2fa7f60 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java @@ -24,6 +24,7 @@ import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; import com.alibaba.nacos.api.naming.pojo.ServiceInfo; +import com.alibaba.nacos.api.naming.selector.NamingSelector; import com.alibaba.nacos.api.naming.utils.NamingUtils; import com.alibaba.nacos.api.selector.AbstractSelector; import com.alibaba.nacos.client.env.NacosClientProperties; @@ -31,11 +32,15 @@ import com.alibaba.nacos.client.naming.core.Balancer; import com.alibaba.nacos.client.naming.event.InstancesChangeEvent; import com.alibaba.nacos.client.naming.event.InstancesChangeNotifier; +import com.alibaba.nacos.client.naming.event.InstancesDiff; import com.alibaba.nacos.client.naming.remote.NamingClientProxy; import com.alibaba.nacos.client.naming.remote.NamingClientProxyDelegate; +import com.alibaba.nacos.client.naming.selector.NamingSelectorFactory; +import com.alibaba.nacos.client.naming.selector.NamingSelectorWrapper; import com.alibaba.nacos.client.naming.utils.CollectionUtils; import com.alibaba.nacos.client.naming.utils.InitUtils; import com.alibaba.nacos.client.naming.utils.UtilAndComs; +import com.alibaba.nacos.client.utils.ParamUtil; import com.alibaba.nacos.client.utils.PreInitUtils; import com.alibaba.nacos.client.utils.ValidatorUtils; import com.alibaba.nacos.common.notify.NotifyCenter; @@ -48,6 +53,7 @@ import java.util.Properties; import java.util.UUID; +import static com.alibaba.nacos.client.naming.selector.NamingSelectorFactory.getUniqueClusterString; import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER; /** @@ -93,6 +99,7 @@ public NacosNamingService(Properties properties) throws NacosException { private void init(Properties properties) throws NacosException { PreInitUtils.asyncPreLoadCostComponent(); final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties); + NAMING_LOGGER.info(ParamUtil.getInputParameters(nacosClientProperties.asProperties())); ValidatorUtils.checkInitParam(nacosClientProperties); this.namespace = InitUtils.initNamespaceForNaming(nacosClientProperties); InitUtils.initSerialization(); @@ -415,12 +422,30 @@ public void subscribe(String serviceName, List clusters, EventListener l @Override public void subscribe(String serviceName, String groupName, List clusters, EventListener listener) throws NacosException { - if (null == listener) { + NamingSelector clusterSelector = NamingSelectorFactory.newClusterSelector(clusters); + doSubscribe(serviceName, groupName, getUniqueClusterString(clusters), clusterSelector, listener); + } + + @Override + public void subscribe(String serviceName, NamingSelector selector, EventListener listener) throws NacosException { + subscribe(serviceName, Constants.DEFAULT_GROUP, selector, listener); + } + + @Override + public void subscribe(String serviceName, String groupName, NamingSelector selector, EventListener listener) + throws NacosException { + doSubscribe(serviceName, groupName, Constants.NULL, selector, listener); + } + + private void doSubscribe(String serviceName, String groupName, String clusters, NamingSelector selector, + EventListener listener) throws NacosException { + if (selector == null || listener == null) { return; } - String clusterString = StringUtils.join(clusters, ","); - changeNotifier.registerListener(groupName, serviceName, clusterString, listener); - clientProxy.subscribe(serviceName, groupName, clusterString); + NamingSelectorWrapper wrapper = new NamingSelectorWrapper(serviceName, groupName, clusters, selector, listener); + notifyIfSubscribed(serviceName, groupName, wrapper); + changeNotifier.registerListener(groupName, serviceName, wrapper); + clientProxy.subscribe(serviceName, groupName, Constants.NULL); } @Override @@ -441,10 +466,30 @@ public void unsubscribe(String serviceName, List clusters, EventListener @Override public void unsubscribe(String serviceName, String groupName, List clusters, EventListener listener) throws NacosException { - String clustersString = StringUtils.join(clusters, ","); - changeNotifier.deregisterListener(groupName, serviceName, clustersString, listener); - if (!changeNotifier.isSubscribed(groupName, serviceName, clustersString)) { - clientProxy.unsubscribe(serviceName, groupName, clustersString); + NamingSelector clusterSelector = NamingSelectorFactory.newClusterSelector(clusters); + unsubscribe(serviceName, groupName, clusterSelector, listener); + } + + @Override + public void unsubscribe(String serviceName, NamingSelector selector, EventListener listener) throws NacosException { + unsubscribe(serviceName, Constants.DEFAULT_GROUP, selector, listener); + } + + @Override + public void unsubscribe(String serviceName, String groupName, NamingSelector selector, EventListener listener) + throws NacosException { + doUnsubscribe(serviceName, groupName, selector, listener); + } + + private void doUnsubscribe(String serviceName, String groupName, NamingSelector selector, EventListener listener) + throws NacosException { + if (selector == null || listener == null) { + return; + } + NamingSelectorWrapper wrapper = new NamingSelectorWrapper(selector, listener); + changeNotifier.deregisterListener(groupName, serviceName, wrapper); + if (!changeNotifier.isSubscribed(groupName, serviceName)) { + clientProxy.unsubscribe(serviceName, groupName, Constants.NULL); } } @@ -485,7 +530,6 @@ public void shutDown() throws NacosException { serviceInfoHolder.shutdown(); clientProxy.shutdown(); NotifyCenter.deregisterSubscriber(changeNotifier); - } private void batchCheckAndStripGroupNamePrefix(List instances, String groupName) throws NacosException { @@ -500,9 +544,31 @@ private void checkAndStripGroupNamePrefix(Instance instance, String groupName) t String groupNameOfInstance = NamingUtils.getGroupName(serviceName); if (!groupName.equals(groupNameOfInstance)) { throw new NacosException(NacosException.CLIENT_INVALID_PARAM, String.format( - "wrong group name prefix of instance service name! it should be: %s, Instance: %s", groupName, instance)); + "wrong group name prefix of instance service name! it should be: %s, Instance: %s", groupName, + instance)); } instance.setServiceName(NamingUtils.getServiceName(serviceName)); } } + + private void notifyIfSubscribed(String serviceName, String groupName, NamingSelectorWrapper wrapper) { + if (changeNotifier.isSubscribed(groupName, serviceName)) { + NAMING_LOGGER.warn( + "Duplicate subscribe for groupName: {}, serviceName: {}; directly use current cached to notify.", + groupName, serviceName); + ServiceInfo serviceInfo = serviceInfoHolder.getServiceInfo(serviceName, groupName, Constants.NULL); + InstancesChangeEvent event = transferToEvent(serviceInfo); + wrapper.notifyListener(event); + } + } + + private InstancesChangeEvent transferToEvent(ServiceInfo serviceInfo) { + if (serviceInfo == null) { + return null; + } + InstancesDiff diff = new InstancesDiff(); + diff.setAddedInstances(serviceInfo.getHosts()); + return new InstancesChangeEvent(notifierEventScope, serviceInfo.getName(), serviceInfo.getGroupName(), + serviceInfo.getClusters(), serviceInfo.getHosts(), diff); + } } diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/backups/FailoverReactor.java b/client/src/main/java/com/alibaba/nacos/client/naming/backups/FailoverReactor.java index b254dac7b72..988db01b5c7 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/backups/FailoverReactor.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/backups/FailoverReactor.java @@ -18,25 +18,25 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.pojo.ServiceInfo; +import com.alibaba.nacos.client.naming.cache.InstancesDiffer; import com.alibaba.nacos.client.naming.cache.ServiceInfoHolder; import com.alibaba.nacos.client.naming.event.InstancesChangeEvent; +import com.alibaba.nacos.client.naming.event.InstancesDiff; import com.alibaba.nacos.common.executor.NameThreadFactory; import com.alibaba.nacos.common.lifecycle.Closeable; import com.alibaba.nacos.common.notify.NotifyCenter; import com.alibaba.nacos.common.spi.NacosServiceLoader; import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.common.utils.ThreadUtils; +import io.micrometer.core.instrument.Gauge; +import io.micrometer.core.instrument.ImmutableTag; import io.micrometer.core.instrument.Metrics; -import io.micrometer.core.instrument.Meter; import io.micrometer.core.instrument.Tag; -import io.micrometer.core.instrument.ImmutableTag; -import io.micrometer.core.instrument.Gauge; -import java.util.Map; -import java.util.HashMap; +import java.util.ArrayList; import java.util.Collection; import java.util.List; -import java.util.ArrayList; +import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; @@ -59,15 +59,16 @@ public class FailoverReactor implements Closeable { private final ScheduledExecutorService executorService; + private final InstancesDiffer instancesDiffer; + private FailoverDataSource failoverDataSource; private String notifierEventScope; - private Map meterMap = new HashMap<>(10); - public FailoverReactor(ServiceInfoHolder serviceInfoHolder, String notifierEventScope) { this.serviceInfoHolder = serviceInfoHolder; this.notifierEventScope = notifierEventScope; + this.instancesDiffer = new InstancesDiffer(); Collection dataSources = NacosServiceLoader.load(FailoverDataSource.class); for (FailoverDataSource dataSource : dataSources) { failoverDataSource = dataSource; @@ -106,11 +107,12 @@ public void run() { for (Map.Entry entry : failoverData.entrySet()) { ServiceInfo newService = (ServiceInfo) entry.getValue().getData(); ServiceInfo oldService = serviceMap.get(entry.getKey()); - if (serviceInfoHolder.isChangedServiceInfo(oldService, newService)) { + InstancesDiff diff = instancesDiffer.doDiff(oldService, newService); + if (diff.hasDifferent()) { NAMING_LOGGER.info("[NA] failoverdata isChangedServiceInfo. newService:{}", JacksonUtils.toJson(newService)); NotifyCenter.publishEvent(new InstancesChangeEvent(notifierEventScope, newService.getName(), - newService.getGroupName(), newService.getClusters(), newService.getHosts())); + newService.getGroupName(), newService.getClusters(), newService.getHosts(), diff)); } failoverMap.put(entry.getKey(), (ServiceInfo) entry.getValue().getData()); } @@ -130,12 +132,12 @@ public void run() { ServiceInfo oldService = entry.getValue(); ServiceInfo newService = serviceInfoMap.get(entry.getKey()); if (newService != null) { - boolean changed = serviceInfoHolder.isChangedServiceInfo(oldService, newService); - if (changed) { + InstancesDiff diff = instancesDiffer.doDiff(oldService, newService); + if (diff.hasDifferent()) { NotifyCenter.publishEvent( new InstancesChangeEvent(notifierEventScope, newService.getName(), newService.getGroupName(), newService.getClusters(), - newService.getHosts())); + newService.getHosts(), diff)); } } } diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/backups/datasource/DiskFailoverDataSource.java b/client/src/main/java/com/alibaba/nacos/client/naming/backups/datasource/DiskFailoverDataSource.java index 63a5d85abbf..e55568c35a2 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/backups/datasource/DiskFailoverDataSource.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/backups/datasource/DiskFailoverDataSource.java @@ -21,10 +21,10 @@ import com.alibaba.nacos.client.naming.backups.FailoverDataSource; import com.alibaba.nacos.client.naming.backups.FailoverSwitch; import com.alibaba.nacos.client.naming.backups.NamingFailoverData; -import com.alibaba.nacos.client.utils.ConcurrentDiskUtil; import com.alibaba.nacos.client.naming.cache.DiskCache; import com.alibaba.nacos.client.naming.utils.CacheDirUtil; import com.alibaba.nacos.client.naming.utils.UtilAndComs; +import com.alibaba.nacos.client.utils.ConcurrentDiskUtil; import com.alibaba.nacos.common.utils.StringUtils; import java.io.File; @@ -51,16 +51,21 @@ public class DiskFailoverDataSource implements FailoverDataSource { private static final String FAILOVER_MODE_PARAM = "failover-mode"; - private Map serviceMap = new ConcurrentHashMap<>(); + private static final FailoverSwitch FAILOVER_SWITCH_FALSE = new FailoverSwitch(Boolean.FALSE); + + private static final FailoverSwitch FAILOVER_SWITCH_TRUE = new FailoverSwitch(Boolean.TRUE); private final Map switchParams = new ConcurrentHashMap<>(); + private Map serviceMap = new ConcurrentHashMap<>(); + private String failoverDir; private long lastModifiedMillis = 0L; public DiskFailoverDataSource() { failoverDir = CacheDirUtil.getCacheDir() + FAILOVER_DIR; + switchParams.put(FAILOVER_MODE_PARAM, Boolean.FALSE.toString()); } class FailoverFileReader implements Runnable { @@ -107,15 +112,15 @@ public FailoverSwitch getSwitch() { File switchFile = Paths.get(failoverDir, UtilAndComs.FAILOVER_SWITCH).toFile(); if (!switchFile.exists()) { NAMING_LOGGER.debug("failover switch is not found, {}", switchFile.getName()); - return new FailoverSwitch(Boolean.FALSE); + switchParams.put(FAILOVER_MODE_PARAM, Boolean.FALSE.toString()); + return FAILOVER_SWITCH_FALSE; } long modified = switchFile.lastModified(); if (lastModifiedMillis < modified) { lastModifiedMillis = modified; - String failover = ConcurrentDiskUtil - .getFileContent(switchFile.getPath(), Charset.defaultCharset().toString()); + String failover = ConcurrentDiskUtil.getFileContent(switchFile.getPath(), Charset.defaultCharset().toString()); if (!StringUtils.isEmpty(failover)) { String[] lines = failover.split(DiskCache.getLineSeparator()); @@ -125,21 +130,22 @@ public FailoverSwitch getSwitch() { switchParams.put(FAILOVER_MODE_PARAM, Boolean.TRUE.toString()); NAMING_LOGGER.info("failover-mode is on"); new FailoverFileReader().run(); - return new FailoverSwitch(Boolean.TRUE); + return FAILOVER_SWITCH_TRUE; } else if (NO_FAILOVER_MODE.equals(line1)) { switchParams.put(FAILOVER_MODE_PARAM, Boolean.FALSE.toString()); NAMING_LOGGER.info("failover-mode is off"); + return FAILOVER_SWITCH_FALSE; } } } } + return switchParams.get(FAILOVER_MODE_PARAM).equals(Boolean.TRUE.toString()) ? FAILOVER_SWITCH_TRUE : FAILOVER_SWITCH_FALSE; } catch (Throwable e) { NAMING_LOGGER.error("[NA] failed to read failover switch.", e); + switchParams.put(FAILOVER_MODE_PARAM, Boolean.FALSE.toString()); + return FAILOVER_SWITCH_FALSE; } - - switchParams.put(FAILOVER_MODE_PARAM, Boolean.FALSE.toString()); - return new FailoverSwitch(Boolean.FALSE); } @Override @@ -149,5 +155,4 @@ public Map getFailoverData() { } return new ConcurrentHashMap<>(0); } - -} \ No newline at end of file +} diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/cache/InstancesDiffer.java b/client/src/main/java/com/alibaba/nacos/client/naming/cache/InstancesDiffer.java new file mode 100644 index 00000000000..5b77d0631a6 --- /dev/null +++ b/client/src/main/java/com/alibaba/nacos/client/naming/cache/InstancesDiffer.java @@ -0,0 +1,119 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.client.naming.cache; + +import com.alibaba.nacos.api.naming.pojo.Instance; +import com.alibaba.nacos.api.naming.pojo.ServiceInfo; +import com.alibaba.nacos.client.naming.event.InstancesDiff; +import com.alibaba.nacos.common.utils.JacksonUtils; +import com.alibaba.nacos.common.utils.StringUtils; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER; + +/** + * The instance list differ for nacos naming. + * + * @author xiweng.yy + */ +public final class InstancesDiffer { + + /** + * Do instance different for input service info. + * + * @param oldService old service info + * @param newService new service info + * @return {@link InstancesDiff} of the differences between old and new service info. + */ + public InstancesDiff doDiff(ServiceInfo oldService, ServiceInfo newService) { + InstancesDiff instancesDiff = new InstancesDiff(); + if (null == oldService) { + NAMING_LOGGER.info("init new ips({}) service: {} -> {}", newService.ipCount(), newService.getKey(), + JacksonUtils.toJson(newService.getHosts())); + instancesDiff.setAddedInstances(newService.getHosts()); + return instancesDiff; + } + if (oldService.getLastRefTime() > newService.getLastRefTime()) { + NAMING_LOGGER.warn("out of date data received, old-t: {}, new-t: {}", oldService.getLastRefTime(), + newService.getLastRefTime()); + return instancesDiff; + } + + Map oldHostMap = new HashMap<>(oldService.getHosts().size()); + for (Instance host : oldService.getHosts()) { + oldHostMap.put(host.toInetAddr(), host); + } + Map newHostMap = new HashMap<>(newService.getHosts().size()); + for (Instance host : newService.getHosts()) { + newHostMap.put(host.toInetAddr(), host); + } + + Set modHosts = new HashSet<>(); + Set newHosts = new HashSet<>(); + Set remvHosts = new HashSet<>(); + + List> newServiceHosts = new ArrayList<>(newHostMap.entrySet()); + for (Map.Entry entry : newServiceHosts) { + Instance host = entry.getValue(); + String key = entry.getKey(); + if (oldHostMap.containsKey(key) && !StringUtils.equals(host.toString(), oldHostMap.get(key).toString())) { + modHosts.add(host); + continue; + } + + if (!oldHostMap.containsKey(key)) { + newHosts.add(host); + } + } + + for (Map.Entry entry : oldHostMap.entrySet()) { + Instance host = entry.getValue(); + String key = entry.getKey(); + if (newHostMap.containsKey(key)) { + continue; + } + + //add to remove hosts + remvHosts.add(host); + } + + if (newHosts.size() > 0) { + NAMING_LOGGER.info("new ips({}) service: {} -> {}", newHosts.size(), newService.getKey(), + JacksonUtils.toJson(newHosts)); + instancesDiff.setAddedInstances(newHosts); + } + + if (remvHosts.size() > 0) { + NAMING_LOGGER.info("removed ips({}) service: {} -> {}", remvHosts.size(), newService.getKey(), + JacksonUtils.toJson(remvHosts)); + instancesDiff.setRemovedInstances(remvHosts); + } + + if (modHosts.size() > 0) { + NAMING_LOGGER.info("modified ips({}) service: {} -> {}", modHosts.size(), newService.getKey(), + JacksonUtils.toJson(modHosts)); + instancesDiff.setModifiedInstances(modHosts); + } + return instancesDiff; + } +} diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/cache/ServiceInfoHolder.java b/client/src/main/java/com/alibaba/nacos/client/naming/cache/ServiceInfoHolder.java index a59222c30fb..3baf109d915 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/cache/ServiceInfoHolder.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/cache/ServiceInfoHolder.java @@ -18,13 +18,13 @@ import com.alibaba.nacos.api.PropertyKeyConst; import com.alibaba.nacos.api.exception.NacosException; -import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ServiceInfo; import com.alibaba.nacos.api.naming.utils.NamingUtils; import com.alibaba.nacos.client.env.NacosClientProperties; import com.alibaba.nacos.client.monitor.MetricsMonitor; import com.alibaba.nacos.client.naming.backups.FailoverReactor; import com.alibaba.nacos.client.naming.event.InstancesChangeEvent; +import com.alibaba.nacos.client.naming.event.InstancesDiff; import com.alibaba.nacos.client.naming.utils.CacheDirUtil; import com.alibaba.nacos.common.lifecycle.Closeable; import com.alibaba.nacos.common.notify.NotifyCenter; @@ -32,12 +32,7 @@ import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.common.utils.StringUtils; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; import java.util.Map; -import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -56,12 +51,15 @@ public class ServiceInfoHolder implements Closeable { private final boolean pushEmptyProtection; + private final InstancesDiffer instancesDiffer; + private String cacheDir; private String notifierEventScope; public ServiceInfoHolder(String namespace, String notifierEventScope, NacosClientProperties properties) { cacheDir = CacheDirUtil.initCacheDir(namespace, properties); + instancesDiffer = new InstancesDiffer(); if (isLoadCacheAtStart(properties)) { this.serviceInfoMap = new ConcurrentHashMap<>(DiskCache.read(this.cacheDir)); } else { @@ -130,23 +128,24 @@ public ServiceInfo processServiceInfo(ServiceInfo serviceInfo) { ServiceInfo oldService = serviceInfoMap.get(serviceInfo.getKey()); if (isEmptyOrErrorPush(serviceInfo)) { //empty or error push, just ignore - NAMING_LOGGER.warn("process service info but found empty or error push, serviceKey: {}, " + NAMING_LOGGER.warn("process service info but found empty or error push, serviceKey: {}, " + "pushEmptyProtection: {}, hosts: {}", serviceKey, pushEmptyProtection, serviceInfo.getHosts()); return oldService; } serviceInfoMap.put(serviceInfo.getKey(), serviceInfo); - boolean changed = isChangedServiceInfo(oldService, serviceInfo); + InstancesDiff diff = getServiceInfoDiff(oldService, serviceInfo); if (StringUtils.isBlank(serviceInfo.getJsonFromServer())) { serviceInfo.setJsonFromServer(JacksonUtils.toJson(serviceInfo)); } MetricsMonitor.getServiceInfoMapSizeMonitor().set(serviceInfoMap.size()); - if (changed) { + if (diff.hasDifferent()) { NAMING_LOGGER.info("current ips:({}) service: {} -> {}", serviceInfo.ipCount(), serviceInfo.getKey(), JacksonUtils.toJson(serviceInfo.getHosts())); + if (!failoverReactor.isFailoverSwitch(serviceKey)) { NotifyCenter.publishEvent( new InstancesChangeEvent(notifierEventScope, serviceInfo.getName(), serviceInfo.getGroupName(), - serviceInfo.getClusters(), serviceInfo.getHosts())); + serviceInfo.getClusters(), serviceInfo.getHosts(), diff)); } DiskCache.write(serviceInfo, cacheDir); } @@ -157,81 +156,8 @@ private boolean isEmptyOrErrorPush(ServiceInfo serviceInfo) { return null == serviceInfo.getHosts() || (pushEmptyProtection && !serviceInfo.validate()); } - /** - * isChangedServiceInfo. - * - * @param oldService old service data - * @param newService new service data - * @return - */ - public boolean isChangedServiceInfo(ServiceInfo oldService, ServiceInfo newService) { - if (null == oldService) { - NAMING_LOGGER.info("init new ips({}) service: {} -> {}", newService.ipCount(), newService.getKey(), - JacksonUtils.toJson(newService.getHosts())); - return true; - } - if (oldService.getLastRefTime() > newService.getLastRefTime()) { - NAMING_LOGGER.warn("out of date data received, old-t: {}, new-t: {}", oldService.getLastRefTime(), - newService.getLastRefTime()); - return false; - } - boolean changed = false; - Map oldHostMap = new HashMap<>(oldService.getHosts().size()); - for (Instance host : oldService.getHosts()) { - oldHostMap.put(host.toInetAddr(), host); - } - Map newHostMap = new HashMap<>(newService.getHosts().size()); - for (Instance host : newService.getHosts()) { - newHostMap.put(host.toInetAddr(), host); - } - - Set modHosts = new HashSet<>(); - Set newHosts = new HashSet<>(); - Set remvHosts = new HashSet<>(); - - List> newServiceHosts = new ArrayList<>(newHostMap.entrySet()); - for (Map.Entry entry : newServiceHosts) { - Instance host = entry.getValue(); - String key = entry.getKey(); - if (oldHostMap.containsKey(key) && !StringUtils.equals(host.toString(), oldHostMap.get(key).toString())) { - modHosts.add(host); - continue; - } - - if (!oldHostMap.containsKey(key)) { - newHosts.add(host); - } - } - - for (Map.Entry entry : oldHostMap.entrySet()) { - Instance host = entry.getValue(); - String key = entry.getKey(); - if (newHostMap.containsKey(key)) { - continue; - } - - //add to remove hosts - remvHosts.add(host); - } - - if (newHosts.size() > 0) { - changed = true; - NAMING_LOGGER.info("new ips({}) service: {} -> {}", newHosts.size(), newService.getKey(), - JacksonUtils.toJson(newHosts)); - } - - if (remvHosts.size() > 0) { - changed = true; - NAMING_LOGGER.info("removed ips({}) service: {} -> {}", remvHosts.size(), newService.getKey(), - JacksonUtils.toJson(remvHosts)); - } - - if (modHosts.size() > 0) { - changed = true; - NAMING_LOGGER.info("modified ips({}) service: {} -> {}", modHosts.size(), newService.getKey(), - JacksonUtils.toJson(modHosts)); - } - return changed; + private InstancesDiff getServiceInfoDiff(ServiceInfo oldService, ServiceInfo newService) { + return instancesDiffer.doDiff(oldService, newService); } public String getCacheDir() { diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/core/ServerListManager.java b/client/src/main/java/com/alibaba/nacos/client/naming/core/ServerListManager.java index 6555a5d8b19..3aa70dce4bd 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/core/ServerListManager.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/core/ServerListManager.java @@ -111,7 +111,7 @@ private void initServerAddr(NacosClientProperties properties) { if (!StringUtils.isBlank(contentPathTmp)) { this.contentPath = contentPathTmp; } - String serverListNameTmp = properties.getProperty(PropertyKeyConst.CLUSTER_NAME); + String serverListNameTmp = properties.getProperty(PropertyKeyConst.ENDPOINT_CLUSTER_NAME); if (!StringUtils.isBlank(serverListNameTmp)) { this.serverListName = serverListNameTmp; } diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/core/ServiceInfoUpdateService.java b/client/src/main/java/com/alibaba/nacos/client/naming/core/ServiceInfoUpdateService.java index daebbacf771..909bfdbd659 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/core/ServiceInfoUpdateService.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/core/ServiceInfoUpdateService.java @@ -183,7 +183,7 @@ public void run() { long delayTime = DEFAULT_DELAY; try { - if (!changeNotifier.isSubscribed(groupName, serviceName, clusters) && !futureMap.containsKey( + if (!changeNotifier.isSubscribed(groupName, serviceName) && !futureMap.containsKey( serviceKey)) { NAMING_LOGGER.info("update task is stopped, service:{}, clusters:{}", groupedServiceName, clusters); isCancel = true; diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/event/InstancesChangeEvent.java b/client/src/main/java/com/alibaba/nacos/client/naming/event/InstancesChangeEvent.java index 87cd8953882..4d7be6b06cd 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/event/InstancesChangeEvent.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/event/InstancesChangeEvent.java @@ -40,13 +40,16 @@ public class InstancesChangeEvent extends Event { private final String clusters; private final List hosts; + + private InstancesDiff instancesDiff; - public InstancesChangeEvent(String eventScope, String serviceName, String groupName, String clusters, List hosts) { + public InstancesChangeEvent(String eventScope, String serviceName, String groupName, String clusters, List hosts, InstancesDiff diff) { this.eventScope = eventScope; this.serviceName = serviceName; this.groupName = groupName; this.clusters = clusters; this.hosts = hosts; + this.instancesDiff = diff; } public String getServiceName() { @@ -64,7 +67,11 @@ public String getClusters() { public List getHosts() { return hosts; } - + + public InstancesDiff getInstancesDiff() { + return instancesDiff; + } + @Override public String scope() { return this.eventScope; diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/event/InstancesChangeNotifier.java b/client/src/main/java/com/alibaba/nacos/client/naming/event/InstancesChangeNotifier.java index da1b743ed72..8c9c7500cfa 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/event/InstancesChangeNotifier.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/event/InstancesChangeNotifier.java @@ -16,22 +16,18 @@ package com.alibaba.nacos.client.naming.event; -import com.alibaba.nacos.api.naming.listener.AbstractEventListener; -import com.alibaba.nacos.api.naming.listener.EventListener; -import com.alibaba.nacos.api.naming.listener.NamingEvent; import com.alibaba.nacos.api.naming.pojo.ServiceInfo; import com.alibaba.nacos.api.naming.utils.NamingUtils; +import com.alibaba.nacos.client.naming.selector.NamingSelectorWrapper; +import com.alibaba.nacos.client.selector.SelectorManager; import com.alibaba.nacos.common.JustForTest; import com.alibaba.nacos.common.notify.Event; import com.alibaba.nacos.common.notify.listener.Subscriber; -import com.alibaba.nacos.common.utils.CollectionUtils; -import com.alibaba.nacos.common.utils.ConcurrentHashSet; import java.util.ArrayList; +import java.util.Collection; import java.util.List; -import java.util.Map; import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; /** * A subscriber to notify eventListener callback. @@ -43,7 +39,7 @@ public class InstancesChangeNotifier extends Subscriber { private final String eventScope; - private final Map> listenerMap = new ConcurrentHashMap<>(); + private final SelectorManager selectorManager = new SelectorManager<>(); @JustForTest public InstancesChangeNotifier() { @@ -59,13 +55,14 @@ public InstancesChangeNotifier(String eventScope) { * * @param groupName group name * @param serviceName serviceName - * @param clusters clusters, concat by ','. such as 'xxx,yyy' - * @param listener custom listener + * @param wrapper selectorWrapper */ - public void registerListener(String groupName, String serviceName, String clusters, EventListener listener) { - String key = ServiceInfo.getKey(NamingUtils.getGroupedName(serviceName, groupName), clusters); - ConcurrentHashSet eventListeners = listenerMap.computeIfAbsent(key, keyInner -> new ConcurrentHashSet<>()); - eventListeners.add(listener); + public void registerListener(String groupName, String serviceName, NamingSelectorWrapper wrapper) { + if (wrapper == null) { + return; + } + String subId = NamingUtils.getGroupedName(serviceName, groupName); + selectorManager.addSelectorWrapper(subId, wrapper); } /** @@ -73,38 +70,31 @@ public void registerListener(String groupName, String serviceName, String cluste * * @param groupName group name * @param serviceName serviceName - * @param clusters clusters, concat by ','. such as 'xxx,yyy' - * @param listener custom listener + * @param wrapper selectorWrapper */ - public void deregisterListener(String groupName, String serviceName, String clusters, EventListener listener) { - String key = ServiceInfo.getKey(NamingUtils.getGroupedName(serviceName, groupName), clusters); - ConcurrentHashSet eventListeners = listenerMap.get(key); - if (eventListeners == null) { + public void deregisterListener(String groupName, String serviceName, NamingSelectorWrapper wrapper) { + if (wrapper == null) { return; } - eventListeners.remove(listener); - if (CollectionUtils.isEmpty(eventListeners)) { - listenerMap.remove(key); - } + String subId = NamingUtils.getGroupedName(serviceName, groupName); + selectorManager.removeSelectorWrapper(subId, wrapper); } /** - * check serviceName,clusters is subscribed. + * check serviceName,groupName is subscribed. * * @param groupName group name * @param serviceName serviceName - * @param clusters clusters, concat by ','. such as 'xxx,yyy' * @return is serviceName,clusters subscribed */ - public boolean isSubscribed(String groupName, String serviceName, String clusters) { - String key = ServiceInfo.getKey(NamingUtils.getGroupedName(serviceName, groupName), clusters); - ConcurrentHashSet eventListeners = listenerMap.get(key); - return CollectionUtils.isNotEmpty(eventListeners); + public boolean isSubscribed(String groupName, String serviceName) { + String subId = NamingUtils.getGroupedName(serviceName, groupName); + return selectorManager.isSubscribed(subId); } public List getSubscribeServices() { List serviceInfos = new ArrayList<>(); - for (String key : listenerMap.keySet()) { + for (String key : selectorManager.getSubscriptions()) { serviceInfos.add(ServiceInfo.fromKey(key)); } return serviceInfos; @@ -112,26 +102,11 @@ public List getSubscribeServices() { @Override public void onEvent(InstancesChangeEvent event) { - String key = ServiceInfo - .getKey(NamingUtils.getGroupedName(event.getServiceName(), event.getGroupName()), event.getClusters()); - ConcurrentHashSet eventListeners = listenerMap.get(key); - if (CollectionUtils.isEmpty(eventListeners)) { - return; + String subId = NamingUtils.getGroupedName(event.getServiceName(), event.getGroupName()); + Collection selectorWrappers = selectorManager.getSelectorWrappers(subId); + for (NamingSelectorWrapper selectorWrapper : selectorWrappers) { + selectorWrapper.notifyListener(event); } - for (final EventListener listener : eventListeners) { - final com.alibaba.nacos.api.naming.listener.Event namingEvent = transferToNamingEvent(event); - if (listener instanceof AbstractEventListener && ((AbstractEventListener) listener).getExecutor() != null) { - ((AbstractEventListener) listener).getExecutor().execute(() -> listener.onEvent(namingEvent)); - } else { - listener.onEvent(namingEvent); - } - } - } - - private com.alibaba.nacos.api.naming.listener.Event transferToNamingEvent( - InstancesChangeEvent instancesChangeEvent) { - return new NamingEvent(instancesChangeEvent.getServiceName(), instancesChangeEvent.getGroupName(), - instancesChangeEvent.getClusters(), instancesChangeEvent.getHosts()); } @Override diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/event/InstancesDiff.java b/client/src/main/java/com/alibaba/nacos/client/naming/event/InstancesDiff.java new file mode 100644 index 00000000000..5026499f6eb --- /dev/null +++ b/client/src/main/java/com/alibaba/nacos/client/naming/event/InstancesDiff.java @@ -0,0 +1,117 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.client.naming.event; + +import com.alibaba.nacos.api.naming.pojo.Instance; +import com.alibaba.nacos.common.utils.CollectionUtils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * The differences in instances compared to the last callback. + * + * @author lideyou + */ +public class InstancesDiff { + + private final List addedInstances = new ArrayList<>(); + + private final List removedInstances = new ArrayList<>(); + + private final List modifiedInstances = new ArrayList<>(); + + public InstancesDiff() { + } + + public InstancesDiff(List addedInstances, List removedInstances, + List modifiedInstances) { + setAddedInstances(addedInstances); + setRemovedInstances(removedInstances); + setModifiedInstances(modifiedInstances); + } + + public List getAddedInstances() { + return addedInstances; + } + + public void setAddedInstances(Collection addedInstances) { + this.addedInstances.clear(); + if (CollectionUtils.isNotEmpty(addedInstances)) { + this.addedInstances.addAll(addedInstances); + } + } + + public List getRemovedInstances() { + return removedInstances; + } + + public void setRemovedInstances(Collection removedInstances) { + this.removedInstances.clear(); + if (CollectionUtils.isNotEmpty(removedInstances)) { + this.removedInstances.addAll(removedInstances); + } + } + + public List getModifiedInstances() { + return modifiedInstances; + } + + public void setModifiedInstances(Collection modifiedInstances) { + this.modifiedInstances.clear(); + if (CollectionUtils.isNotEmpty(modifiedInstances)) { + this.modifiedInstances.addAll(modifiedInstances); + } + } + + /** + * Check if any instances have changed. + * + * @return true if there are instances that have changed + */ + public boolean hasDifferent() { + return isAdded() || isRemoved() || isModified(); + } + + /** + * Check if any instances have been added. + * + * @return true if there are instances that have been added. + */ + public boolean isAdded() { + return CollectionUtils.isNotEmpty(this.addedInstances); + } + + /** + * Check if any instances have been added. + * + * @return true if there are instances that have been added. + */ + public boolean isRemoved() { + return CollectionUtils.isNotEmpty(this.removedInstances); + } + + /** + * Check if any instances have been added. + * + * @return true if there are instances that have been added. + */ + public boolean isModified() { + return CollectionUtils.isNotEmpty(this.modifiedInstances); + } +} diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/listener/AbstractNamingChangeListener.java b/client/src/main/java/com/alibaba/nacos/client/naming/listener/AbstractNamingChangeListener.java new file mode 100644 index 00000000000..93214735951 --- /dev/null +++ b/client/src/main/java/com/alibaba/nacos/client/naming/listener/AbstractNamingChangeListener.java @@ -0,0 +1,42 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.client.naming.listener; + +import com.alibaba.nacos.api.naming.listener.AbstractEventListener; +import com.alibaba.nacos.api.naming.listener.Event; + +/** + * Listener for NamingChangeEvent. + * + * @author lideyou + */ +public abstract class AbstractNamingChangeListener extends AbstractEventListener { + + @Override + public final void onEvent(Event event) { + if (event instanceof NamingChangeEvent) { + onChange((NamingChangeEvent) event); + } + } + + /** + * Callback when instances have changed. + * + * @param event NamingChangeEvent + */ + public abstract void onChange(NamingChangeEvent event); +} diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/listener/NamingChangeEvent.java b/client/src/main/java/com/alibaba/nacos/client/naming/listener/NamingChangeEvent.java new file mode 100644 index 00000000000..62b4dbf33b1 --- /dev/null +++ b/client/src/main/java/com/alibaba/nacos/client/naming/listener/NamingChangeEvent.java @@ -0,0 +1,68 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.client.naming.listener; + +import com.alibaba.nacos.api.naming.listener.NamingEvent; +import com.alibaba.nacos.api.naming.pojo.Instance; +import com.alibaba.nacos.client.naming.event.InstancesDiff; + +import java.util.List; + +/** + * Naming Event with instance change information. + * + * @author lideyou + */ +public class NamingChangeEvent extends NamingEvent { + + private final InstancesDiff instancesDiff; + + public NamingChangeEvent(String serviceName, List instances, InstancesDiff instancesDiff) { + super(serviceName, instances); + this.instancesDiff = instancesDiff; + } + + public NamingChangeEvent(String serviceName, String groupName, String clusters, List instances, + InstancesDiff instancesDiff) { + super(serviceName, groupName, clusters, instances); + this.instancesDiff = instancesDiff; + } + + public boolean isAdded() { + return this.instancesDiff.isAdded(); + } + + public boolean isRemoved() { + return this.instancesDiff.isRemoved(); + } + + public boolean isModified() { + return this.instancesDiff.isModified(); + } + + public List getAddedInstances() { + return this.instancesDiff.getAddedInstances(); + } + + public List getRemovedInstances() { + return this.instancesDiff.getRemovedInstances(); + } + + public List getModifiedInstances() { + return this.instancesDiff.getModifiedInstances(); + } +} diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/remote/gprc/NamingGrpcClientProxy.java b/client/src/main/java/com/alibaba/nacos/client/naming/remote/gprc/NamingGrpcClientProxy.java index f02379dbb97..a240d5d747d 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/remote/gprc/NamingGrpcClientProxy.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/remote/gprc/NamingGrpcClientProxy.java @@ -58,7 +58,7 @@ import com.alibaba.nacos.common.remote.ConnectionType; import com.alibaba.nacos.common.remote.client.RpcClient; import com.alibaba.nacos.common.remote.client.RpcClientFactory; -import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig; +import com.alibaba.nacos.common.remote.client.RpcClientTlsConfigFactory; import com.alibaba.nacos.common.remote.client.ServerListFactory; import com.alibaba.nacos.common.utils.CollectionUtils; import com.alibaba.nacos.common.utils.JacksonUtils; @@ -104,7 +104,7 @@ public NamingGrpcClientProxy(String namespaceId, SecurityProxy securityProxy, Se labels.put(RemoteConstants.LABEL_MODULE, RemoteConstants.LABEL_MODULE_NAMING); labels.put(Constants.APPNAME, AppNameUtils.getAppName()); this.rpcClient = RpcClientFactory.createClient(uuid, ConnectionType.GRPC, labels, - RpcClientTlsConfig.properties(properties.asProperties())); + RpcClientTlsConfigFactory.getInstance().createSdkConfig(properties.asProperties())); this.redoService = new NamingGrpcRedoService(this, properties); NAMING_LOGGER.info("Create naming rpc client for uuid->{}", uuid); start(serverListFactory, serviceInfoHolder); diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/selector/DefaultNamingSelector.java b/client/src/main/java/com/alibaba/nacos/client/naming/selector/DefaultNamingSelector.java new file mode 100644 index 00000000000..ad15508df7c --- /dev/null +++ b/client/src/main/java/com/alibaba/nacos/client/naming/selector/DefaultNamingSelector.java @@ -0,0 +1,52 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.client.naming.selector; + +import com.alibaba.nacos.api.naming.pojo.Instance; +import com.alibaba.nacos.api.naming.selector.NamingContext; +import com.alibaba.nacos.api.naming.selector.NamingResult; +import com.alibaba.nacos.api.naming.selector.NamingSelector; + +import java.util.Collections; +import java.util.List; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +/** + * Default naming selector. + * + * @author lideyou + */ +public class DefaultNamingSelector implements NamingSelector { + + private final Predicate filter; + + public DefaultNamingSelector(Predicate filter) { + this.filter = filter; + } + + @Override + public NamingResult select(NamingContext context) { + List instances = doFilter(context.getInstances()); + return () -> instances; + } + + private List doFilter(List instances) { + return instances == null ? Collections.emptyList() + : instances.stream().filter(filter).collect(Collectors.toList()); + } +} diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/selector/NamingListenerInvoker.java b/client/src/main/java/com/alibaba/nacos/client/naming/selector/NamingListenerInvoker.java new file mode 100644 index 00000000000..9e7c948481e --- /dev/null +++ b/client/src/main/java/com/alibaba/nacos/client/naming/selector/NamingListenerInvoker.java @@ -0,0 +1,74 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.client.naming.selector; + +import com.alibaba.nacos.api.naming.listener.AbstractEventListener; +import com.alibaba.nacos.api.naming.listener.EventListener; +import com.alibaba.nacos.api.naming.listener.NamingEvent; +import com.alibaba.nacos.client.selector.ListenerInvoker; + +import java.util.Objects; + +import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER; + +/** + * Naming listener invoker. + * + * @author lideyou + */ +public class NamingListenerInvoker implements ListenerInvoker { + + private final EventListener listener; + + public NamingListenerInvoker(EventListener listener) { + this.listener = listener; + } + + @Override + public void invoke(NamingEvent event) { + logInvoke(event); + if (listener instanceof AbstractEventListener && ((AbstractEventListener) listener).getExecutor() != null) { + ((AbstractEventListener) listener).getExecutor().execute(() -> listener.onEvent(event)); + } else { + listener.onEvent(event); + } + } + + private void logInvoke(NamingEvent event) { + NAMING_LOGGER.info("Invoke event groupName: {}, serviceName: {} to Listener: {}", event.getGroupName(), + event.getServiceName(), listener.toString()); + } + + @Override + public boolean equals(Object o) { + if (o == null || getClass() != o.getClass()) { + return false; + } + + if (this == o) { + return true; + } + + NamingListenerInvoker that = (NamingListenerInvoker) o; + return Objects.equals(listener, that.listener); + } + + @Override + public int hashCode() { + return Objects.hashCode(listener); + } +} diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/selector/NamingSelectorFactory.java b/client/src/main/java/com/alibaba/nacos/client/naming/selector/NamingSelectorFactory.java new file mode 100644 index 00000000000..6f93447d068 --- /dev/null +++ b/client/src/main/java/com/alibaba/nacos/client/naming/selector/NamingSelectorFactory.java @@ -0,0 +1,150 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.client.naming.selector; + +import com.alibaba.nacos.api.naming.pojo.Instance; +import com.alibaba.nacos.api.naming.selector.NamingSelector; +import com.alibaba.nacos.common.utils.CollectionUtils; +import com.alibaba.nacos.common.utils.StringUtils; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.TreeSet; +import java.util.function.Predicate; +import java.util.regex.Pattern; + +/** + * Selectors factory. + * + * @author lideyou + */ +public final class NamingSelectorFactory { + + public static final NamingSelector EMPTY_SELECTOR = context -> context::getInstances; + + public static final NamingSelector HEALTHY_SELECTOR = new DefaultNamingSelector(Instance::isHealthy); + + /** + * Cluster selector. + */ + private static class ClusterSelector extends DefaultNamingSelector { + + private final String clusterString; + + public ClusterSelector(Predicate filter, String clusterString) { + super(filter); + this.clusterString = clusterString; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClusterSelector that = (ClusterSelector) o; + return Objects.equals(this.clusterString, that.clusterString); + } + + @Override + public int hashCode() { + return Objects.hashCode(this.clusterString); + } + } + + private NamingSelectorFactory() { + } + + /** + * Create a cluster selector. + * + * @param clusters target cluster + * @return cluster selector + */ + public static NamingSelector newClusterSelector(Collection clusters) { + if (CollectionUtils.isNotEmpty(clusters)) { + final Set set = new HashSet<>(clusters); + Predicate filter = instance -> set.contains(instance.getClusterName()); + String clusterString = getUniqueClusterString(clusters); + return new ClusterSelector(filter, clusterString); + } else { + return EMPTY_SELECTOR; + } + } + + /** + * Create a IP selector. + * + * @param regex regular expression of IP + * @return IP selector + */ + public static NamingSelector newIpSelector(String regex) { + if (regex == null) { + throw new IllegalArgumentException("The parameter 'regex' cannot be null."); + } + return new DefaultNamingSelector(instance -> Pattern.matches(regex, instance.getIp())); + } + + /** + * Create a metadata selector. + * + * @param metadata metadata that needs to be matched + * @return metadata selector + */ + public static NamingSelector newMetadataSelector(Map metadata) { + return newMetadataSelector(metadata, false); + } + + /** + * Create a metadata selector. + * + * @param metadata target metadata + * @param isAny true if any of the metadata needs to be matched, false if all the metadata need to be matched. + * @return metadata selector + */ + public static NamingSelector newMetadataSelector(Map metadata, boolean isAny) { + if (metadata == null) { + throw new IllegalArgumentException("The parameter 'metadata' cannot be null."); + } + + Predicate filter = instance -> instance.getMetadata().size() >= metadata.size(); + + for (Map.Entry entry : metadata.entrySet()) { + Predicate nextFilter = instance -> { + Map map = instance.getMetadata(); + return Objects.equals(map.get(entry.getKey()), entry.getValue()); + }; + if (isAny) { + filter = filter.or(nextFilter); + } else { + filter = filter.and(nextFilter); + } + } + return new DefaultNamingSelector(filter); + } + + public static String getUniqueClusterString(Collection cluster) { + TreeSet treeSet = new TreeSet<>(cluster); + return StringUtils.join(treeSet, ","); + } + +} diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/selector/NamingSelectorWrapper.java b/client/src/main/java/com/alibaba/nacos/client/naming/selector/NamingSelectorWrapper.java new file mode 100644 index 00000000000..412b120f03a --- /dev/null +++ b/client/src/main/java/com/alibaba/nacos/client/naming/selector/NamingSelectorWrapper.java @@ -0,0 +1,134 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.client.naming.selector; + +import com.alibaba.nacos.api.naming.listener.EventListener; +import com.alibaba.nacos.api.naming.listener.NamingEvent; +import com.alibaba.nacos.api.naming.pojo.Instance; +import com.alibaba.nacos.api.naming.selector.NamingContext; +import com.alibaba.nacos.api.naming.selector.NamingSelector; +import com.alibaba.nacos.client.naming.event.InstancesChangeEvent; +import com.alibaba.nacos.client.naming.event.InstancesDiff; +import com.alibaba.nacos.client.naming.listener.NamingChangeEvent; +import com.alibaba.nacos.client.selector.AbstractSelectorWrapper; +import com.alibaba.nacos.common.utils.CollectionUtils; + +import java.util.Collections; +import java.util.List; + +/** + * Naming selector wrapper. + * + * @author lideyou + */ +public class NamingSelectorWrapper extends AbstractSelectorWrapper { + + private String serviceName; + + private String groupName; + + private String clusters; + + private final InnerNamingContext namingContext = new InnerNamingContext(); + + private class InnerNamingContext implements NamingContext { + + private List instances; + + @Override + public String getServiceName() { + return serviceName; + } + + @Override + public String getGroupName() { + return groupName; + } + + @Override + public String getClusters() { + return clusters; + } + + @Override + public List getInstances() { + return instances; + } + + private void setInstances(List instances) { + this.instances = instances; + } + } + + public NamingSelectorWrapper(NamingSelector selector, EventListener listener) { + super(selector, new NamingListenerInvoker(listener)); + } + + public NamingSelectorWrapper(String serviceName, String groupName, String clusters, NamingSelector selector, + EventListener listener) { + this(selector, listener); + this.serviceName = serviceName; + this.groupName = groupName; + this.clusters = clusters; + } + + @Override + protected boolean isSelectable(InstancesChangeEvent event) { + return event != null && event.getHosts() != null && event.getInstancesDiff() != null; + } + + @Override + public boolean isCallable(NamingEvent event) { + if (event == null) { + return false; + } + NamingChangeEvent changeEvent = (NamingChangeEvent) event; + return changeEvent.isAdded() || changeEvent.isRemoved() || changeEvent.isModified(); + } + + @Override + protected NamingEvent buildListenerEvent(InstancesChangeEvent event) { + List currentIns = Collections.emptyList(); + if (CollectionUtils.isNotEmpty(event.getHosts())) { + currentIns = doSelect(event.getHosts()); + } + + InstancesDiff diff = event.getInstancesDiff(); + InstancesDiff newDiff = new InstancesDiff(); + if (diff.isAdded()) { + newDiff.setAddedInstances(doSelect(diff.getAddedInstances())); + } + if (diff.isRemoved()) { + newDiff.setRemovedInstances(doSelect(diff.getRemovedInstances())); + } + if (diff.isModified()) { + newDiff.setModifiedInstances(doSelect(diff.getModifiedInstances())); + } + + return new NamingChangeEvent(serviceName, groupName, clusters, currentIns, newDiff); + } + + private List doSelect(List instances) { + NamingContext context = getNamingContext(instances); + return this.getSelector().select(context).getResult(); + } + + private NamingContext getNamingContext(final List instances) { + namingContext.setInstances(instances); + return namingContext; + } +} diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/utils/CacheDirUtil.java b/client/src/main/java/com/alibaba/nacos/client/naming/utils/CacheDirUtil.java index 7c879509fcf..1abaaafbb41 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/utils/CacheDirUtil.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/utils/CacheDirUtil.java @@ -49,7 +49,7 @@ public class CacheDirUtil { */ public static String initCacheDir(String namespace, NacosClientProperties properties) { - String jmSnapshotPath = System.getProperty(JM_SNAPSHOT_PATH_PROPERTY); + String jmSnapshotPath = properties.getProperty(JM_SNAPSHOT_PATH_PROPERTY); String namingCacheRegistryDir = ""; if (properties.getProperty(PropertyKeyConst.NAMING_CACHE_REGISTRY_DIR) != null) { @@ -62,7 +62,7 @@ public static String initCacheDir(String namespace, NacosClientProperties proper + FILE_PATH_NAMING + File.separator + namespace; } else { cacheDir = - System.getProperty(USER_HOME_PROPERTY) + File.separator + FILE_PATH_NACOS + namingCacheRegistryDir + properties.getProperty(USER_HOME_PROPERTY) + File.separator + FILE_PATH_NACOS + namingCacheRegistryDir + File.separator + FILE_PATH_NAMING + File.separator + namespace; } diff --git a/client/src/main/java/com/alibaba/nacos/client/selector/AbstractSelectorWrapper.java b/client/src/main/java/com/alibaba/nacos/client/selector/AbstractSelectorWrapper.java new file mode 100644 index 00000000000..edbab0810b7 --- /dev/null +++ b/client/src/main/java/com/alibaba/nacos/client/selector/AbstractSelectorWrapper.java @@ -0,0 +1,106 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.client.selector; + +import com.alibaba.nacos.api.selector.client.Selector; +import com.alibaba.nacos.common.notify.Event; + +import java.util.Objects; + +/** + * Selector Wrapper. + * + * @param the type of selector + * @param the type of original event + * @param the type of listener callback event + * @author lideyou + */ +public abstract class AbstractSelectorWrapper, E, T extends Event> { + + private final S selector; + + private final ListenerInvoker listener; + + public AbstractSelectorWrapper(S selector, ListenerInvoker listener) { + this.selector = selector; + this.listener = listener; + } + + /** + * Check whether the event can be callback. + * + * @param event original event + * @return true if the event can be callback + */ + protected abstract boolean isSelectable(T event); + + /** + * Check whether the result can be callback. + * + * @param event select result + * @return true if the result can be callback + */ + protected abstract boolean isCallable(E event); + + /** + * Build an event received by the listener. + * + * @param event original event + * @return listener event + */ + protected abstract E buildListenerEvent(T event); + + /** + * Notify listener. + * + * @param event original event + */ + public void notifyListener(T event) { + if (!isSelectable(event)) { + return; + } + E newEvent = buildListenerEvent(event); + if (isCallable(newEvent)) { + listener.invoke(newEvent); + } + } + + public ListenerInvoker getListener() { + return this.listener; + } + + public S getSelector() { + return this.selector; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AbstractSelectorWrapper that = (AbstractSelectorWrapper) o; + return Objects.equals(selector, that.selector) && Objects.equals(listener, that.listener); + } + + @Override + public int hashCode() { + return Objects.hash(selector, listener); + } +} diff --git a/client/src/main/java/com/alibaba/nacos/client/selector/ListenerInvoker.java b/client/src/main/java/com/alibaba/nacos/client/selector/ListenerInvoker.java new file mode 100644 index 00000000000..81996eea736 --- /dev/null +++ b/client/src/main/java/com/alibaba/nacos/client/selector/ListenerInvoker.java @@ -0,0 +1,33 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.client.selector; + +/** + * Listener invoker. + * + * @param the type of event received by the listener + * @author lideyou + */ +public interface ListenerInvoker { + + /** + * Invoke inner listener. + * + * @param event event + */ + void invoke(E event); +} diff --git a/client/src/main/java/com/alibaba/nacos/client/selector/SelectorManager.java b/client/src/main/java/com/alibaba/nacos/client/selector/SelectorManager.java new file mode 100644 index 00000000000..deda8f62e07 --- /dev/null +++ b/client/src/main/java/com/alibaba/nacos/client/selector/SelectorManager.java @@ -0,0 +1,103 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.client.selector; + +import com.alibaba.nacos.common.utils.CollectionUtils; +import com.alibaba.nacos.common.utils.ConcurrentHashSet; + +import java.util.Collections; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Selector Manager. + * + * @param the type of selector wrapper + * @author lideyou + */ +public class SelectorManager> { + + Map> selectorMap = new ConcurrentHashMap<>(); + + /** + * Add a selectorWrapper to subId. + * + * @param subId subscription id + * @param wrapper selector wrapper + */ + public void addSelectorWrapper(String subId, S wrapper) { + selectorMap.compute(subId, (k, v) -> { + if (v == null) { + v = new ConcurrentHashSet<>(); + } + v.add(wrapper); + return v; + }); + } + + /** + * Get all SelectorWrappers by id. + * + * @param subId subscription id + * @return the set of SelectorWrappers + */ + public Set getSelectorWrappers(String subId) { + return selectorMap.getOrDefault(subId, Collections.emptySet()); + } + + /** + * Remove a SelectorWrapper by id. + * + * @param subId subscription id + * @param wrapper selector wrapper + */ + public void removeSelectorWrapper(String subId, S wrapper) { + selectorMap.computeIfPresent(subId, (k, v) -> { + v.remove(wrapper); + return v.isEmpty() ? null : v; + }); + } + + /** + * Remove a subscription by id. + * + * @param subId subscription id + */ + public void removeSubscription(String subId) { + selectorMap.remove(subId); + } + + /** + * Get all subscriptions. + * + * @return all subscriptions + */ + public Set getSubscriptions() { + return selectorMap.keySet(); + } + + /** + * Determine whether subId is subscribed. + * + * @param subId subscription id + * @return true if is subscribed + */ + public boolean isSubscribed(String subId) { + return CollectionUtils.isNotEmpty(this.getSelectorWrappers(subId)); + } +} diff --git a/client/src/main/java/com/alibaba/nacos/client/utils/ParamUtil.java b/client/src/main/java/com/alibaba/nacos/client/utils/ParamUtil.java index 13f7192671d..11f3927e40e 100644 --- a/client/src/main/java/com/alibaba/nacos/client/utils/ParamUtil.java +++ b/client/src/main/java/com/alibaba/nacos/client/utils/ParamUtil.java @@ -20,11 +20,13 @@ import com.alibaba.nacos.api.SystemPropertyKeyConst; import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.client.env.NacosClientProperties; +import com.alibaba.nacos.common.utils.ConvertUtils; import com.alibaba.nacos.common.utils.MD5Utils; import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.common.utils.VersionUtils; import org.slf4j.Logger; +import java.util.Properties; import java.util.regex.Pattern; /** @@ -80,8 +82,8 @@ public class ParamUtil { // Client identity information appKey = NacosClientProperties.PROTOTYPE.getProperty(NACOS_CLIENT_APP_KEY, BLANK_STR); - defaultContextPath = NacosClientProperties.PROTOTYPE - .getProperty(NACOS_CLIENT_CONTEXTPATH_KEY, DEFAULT_NACOS_CLIENT_CONTEXTPATH); + defaultContextPath = NacosClientProperties.PROTOTYPE.getProperty(NACOS_CLIENT_CONTEXTPATH_KEY, + DEFAULT_NACOS_CLIENT_CONTEXTPATH); appName = AppNameUtils.getAppName(); @@ -111,8 +113,8 @@ private static int initConnectionTimeout() { private static double initPerTaskConfigSize() { try { - return Double.parseDouble(NacosClientProperties.PROTOTYPE - .getProperty(PER_TASK_CONFIG_SIZE_KEY, DEFAULT_PER_TASK_CONFIG_SIZE_KEY)); + return Double.parseDouble(NacosClientProperties.PROTOTYPE.getProperty(PER_TASK_CONFIG_SIZE_KEY, + DEFAULT_PER_TASK_CONFIG_SIZE_KEY)); } catch (NumberFormatException e) { LOGGER.error("[PER_TASK_CONFIG_SIZE] PER_TASK_CONFIG_SIZE invalid", e); throw new IllegalArgumentException("invalid PER_TASK_CONFIG_SIZE, expected value type double", e); @@ -217,8 +219,8 @@ public static String parsingEndpointRule(String endpointUrl) { // If entered in the configuration file, the priority in ENV will be given priority. if (endpointUrl == null || !PATTERN.matcher(endpointUrl).find()) { // skip retrieve from system property and retrieve directly from system env - String endpointUrlSource = NacosClientProperties.PROTOTYPE - .getProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_URL); + String endpointUrlSource = NacosClientProperties.PROTOTYPE.getProperty( + PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_URL); if (StringUtils.isNotBlank(endpointUrlSource)) { endpointUrl = endpointUrlSource; } @@ -234,10 +236,10 @@ public static String parsingEndpointRule(String endpointUrl) { endpointUrl = endpointUrl.substring(0, defStartOf); } - String endpointUrlSource = TemplateUtils - .stringBlankAndThenExecute(NacosClientProperties.PROTOTYPE.getProperty(endpointUrl), - () -> NacosClientProperties.PROTOTYPE - .getProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_URL)); + String endpointUrlSource = TemplateUtils.stringBlankAndThenExecute( + NacosClientProperties.PROTOTYPE.getProperty(endpointUrl), + () -> NacosClientProperties.PROTOTYPE.getProperty( + PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_URL)); if (StringUtils.isBlank(endpointUrlSource)) { if (StringUtils.isNotBlank(defaultEndpointUrl)) { @@ -264,4 +266,41 @@ public static String simplyEnvNameIfOverLimit(String envName) { } return envName; } + + public static String getInputParameters(Properties properties) { + boolean logAllParameters = ConvertUtils.toBoolean(properties.getProperty(PropertyKeyConst.LOG_ALL_PROPERTIES), + false); + StringBuilder result = new StringBuilder(); + if (logAllParameters) { + result.append( + "Log nacos client init properties with Full mode, This mode is only used for debugging and troubleshooting. "); + result.append( + "Please close this mode by removing properties `logAllProperties` after finishing debug or troubleshoot.\n"); + result.append("Nacos client all init properties: \n"); + properties.forEach( + (key, value) -> result.append("\t").append(key.toString()).append("=").append(value.toString()) + .append("\n")); + } else { + result.append("Nacos client key init properties: \n"); + appendKeyParameters(result, properties, PropertyKeyConst.SERVER_ADDR); + appendKeyParameters(result, properties, PropertyKeyConst.NAMESPACE); + appendKeyParameters(result, properties, PropertyKeyConst.ENDPOINT); + appendKeyParameters(result, properties, PropertyKeyConst.ENDPOINT_PORT); + appendKeyParameters(result, properties, PropertyKeyConst.USERNAME); + appendKeyParameters(result, properties, PropertyKeyConst.PASSWORD); + appendKeyParameters(result, properties, PropertyKeyConst.ACCESS_KEY); + appendKeyParameters(result, properties, PropertyKeyConst.SECRET_KEY); + appendKeyParameters(result, properties, PropertyKeyConst.RAM_ROLE_NAME); + appendKeyParameters(result, properties, PropertyKeyConst.SIGNATURE_REGION_ID); + } + return result.toString(); + } + + private static void appendKeyParameters(StringBuilder result, Properties properties, String propertyKey) { + String propertyValue = properties.getProperty(propertyKey); + if (StringUtils.isBlank(propertyValue)) { + return; + } + result.append("\t").append(propertyKey).append("=").append(propertyValue).append("\n"); + } } 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..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,57 +25,60 @@ 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; -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() { 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<>(); @@ -86,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()) { @@ -101,33 +104,34 @@ 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; } }; 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() { @@ -136,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; @@ -149,24 +153,26 @@ 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); - return new Response() { }; + 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); - return new Response() { }; + 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..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 @@ -18,25 +18,25 @@ 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)); @@ -45,7 +45,7 @@ public void testInitCurrentNodeAbilities() { } @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..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 @@ -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); @@ -67,16 +70,16 @@ public 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); - 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(); @@ -84,17 +87,17 @@ public 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); 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<>(); @@ -107,16 +110,16 @@ public 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); - 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}"); @@ -150,21 +153,22 @@ public 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 - 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 +185,14 @@ 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}"); @@ -196,21 +201,22 @@ public 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 - 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\"}"); @@ -219,14 +225,14 @@ public 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); //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..efb780c6565 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,27 +17,29 @@ 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.api.exception.NacosException; 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 com.alibaba.nacos.plugin.auth.api.LoginIdentityContext; +import com.alibaba.nacos.plugin.auth.api.RequestResource; +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.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"; @@ -54,11 +56,11 @@ public class RamClientAuthServiceImplTest { private RequestResource resource; - @Before - public void setUp() throws Exception { + @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"); @@ -70,8 +72,13 @@ public void setUp() throws Exception { resource = new RequestResource(); } + @AfterEach + void tearDown() throws NacosException { + ramClientAuthService.shutdown(); + } + @Test - public void testLoginWithAkSk() { + void testLoginWithAkSk() { assertTrue(ramClientAuthService.login(akSkProperties)); assertEquals(PropertyKeyConst.ACCESS_KEY, ramContext.getAccessKey()); assertEquals(PropertyKeyConst.SECRET_KEY, ramContext.getSecretKey()); @@ -83,26 +90,26 @@ public void testLoginWithAkSk() { } @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()); @@ -110,7 +117,7 @@ public void testGetLoginIdentityContextWithoutInjector() { } @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..f3160c3e5cc 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,51 @@ 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 { + CredentialService.freeInstance(); + CredentialService.freeInstance(APP_NAME); } - @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"); @@ -70,21 +72,21 @@ public void testGetInstance3() throws NoSuchFieldException, IllegalAccessExcepti } @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"); @@ -97,24 +99,24 @@ public void testFree() throws NoSuchFieldException, IllegalAccessException { } @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 +126,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..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 @@ -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; @@ -59,18 +59,18 @@ public class CredentialWatcherTest { 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); - 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); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { credentialWatcher.stop(); System.clearProperty("spas.identity"); System.clearProperty(IdentifyConstants.ENV_ACCESS_KEY); @@ -79,16 +79,16 @@ public void tearDown() throws Exception { } @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<>(""); @@ -108,7 +108,7 @@ public void testLoadCredentialByEnv() throws InvocationTargetException, IllegalA } @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<>(""); @@ -128,7 +128,7 @@ public void testLoadCredentialByIdentityFile() throws InvocationTargetException, } @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<>(""); @@ -151,7 +151,7 @@ public void testLoadCredentialByInvalidIdentityFile() throws InvocationTargetExc * 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()); @@ -166,7 +166,7 @@ public void testLoadCredentialByDockerFile() } @Test - public void testLoadCredentialByFileWithIoException() + void testLoadCredentialByFileWithIoException() throws IOException, InvocationTargetException, IllegalAccessException { InputStream propertiesIS = mock(InputStream.class); when(propertiesIS.read(any())).thenThrow(new IOException("test")); @@ -179,8 +179,7 @@ public void testLoadCredentialByFileWithIoException() } @Test - public 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 919aacf0582..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 @@ -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; -public class CredentialsTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +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..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 @@ -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; @@ -49,8 +50,8 @@ 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"); @@ -59,8 +60,8 @@ public void setUp() throws Exception { 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"); @@ -77,7 +78,7 @@ private void clearForSts() throws NoSuchFieldException, IllegalAccessException { } @Test - public void testGetStsCredentialFromCache() throws NoSuchFieldException, IllegalAccessException { + void testGetStsCredentialFromCache() throws NoSuchFieldException, IllegalAccessException { StsCredential stsCredential = buildMockStsCredential(); setStsCredential(stsCredential); assertEquals(stsCredential, StsCredentialHolder.getInstance().getStsCredential()); @@ -90,14 +91,14 @@ private void setStsCredential(StsCredential stsCredential) throws NoSuchFieldExc } @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); @@ -107,20 +108,24 @@ public void testGetStsCredentialFromRequest() throws Exception { 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..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 @@ -16,23 +16,24 @@ 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() { - injector = new AbstractResourceInjector() { }; + @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..531d67d90bd 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 @@ -17,6 +17,7 @@ package com.alibaba.nacos.client.auth.ram.injector; import com.alibaba.nacos.api.PropertyKeyConst; +import com.alibaba.nacos.client.auth.ram.RamConstants; import com.alibaba.nacos.client.auth.ram.RamContext; import com.alibaba.nacos.client.auth.ram.identify.IdentifyConstants; import com.alibaba.nacos.client.auth.ram.identify.StsConfig; @@ -25,15 +26,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; @@ -47,8 +50,8 @@ public class ConfigResourceInjectorTest { 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); @@ -64,66 +67,78 @@ public void setUp() throws Exception { 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)); + } + + @Test + void testDoInjectForV4Sign() { + LoginIdentityContext actual = new LoginIdentityContext(); + ramContext.setRegionId("cn-hangzhou"); + configResourceInjector.doInject(resource, ramContext, actual); + assertEquals(4, actual.getAllKey().size()); + assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("Spas-AccessKey")); + assertEquals(RamConstants.V4, actual.getParameter(RamConstants.SIGNATURE_VERSION)); + assertTrue(actual.getAllKey().contains("Timestamp")); + assertTrue(actual.getAllKey().contains("Spas-Signature")); } 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..fd1c06d3f16 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 @@ -17,22 +17,26 @@ package com.alibaba.nacos.client.auth.ram.injector; import com.alibaba.nacos.api.PropertyKeyConst; +import com.alibaba.nacos.client.auth.ram.RamConstants; import com.alibaba.nacos.client.auth.ram.RamContext; import com.alibaba.nacos.client.auth.ram.identify.StsConfig; import com.alibaba.nacos.client.auth.ram.identify.StsCredential; import com.alibaba.nacos.client.auth.ram.identify.StsCredentialHolder; +import com.alibaba.nacos.client.auth.ram.utils.CalculateV4SigningKeyUtil; 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; @@ -42,8 +46,8 @@ public class NamingResourceInjectorTest { 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); @@ -52,81 +56,97 @@ public void setUp() throws Exception { 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); + 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); - 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(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); + 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); - 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(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); + 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"); - 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(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); + 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"); - 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(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()); + } + + @Test + void testDoInjectForV4Sign() throws Exception { + resource = RequestResource.namingBuilder().setResource("test@@aaa").setGroup("group").build(); + LoginIdentityContext actual = new LoginIdentityContext(); + ramContext.setRegionId("cn-hangzhou"); + namingResourceInjector.doInject(resource, ramContext, actual); + assertEquals(4, actual.getAllKey().size()); + assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("ak")); + assertEquals(RamConstants.V4, actual.getParameter(RamConstants.SIGNATURE_VERSION)); + assertTrue(actual.getParameter("data").endsWith("@@test@@aaa")); + String signatureKey = CalculateV4SigningKeyUtil.finalSigningKeyStringWithDefaultInfo( + PropertyKeyConst.SECRET_KEY, "cn-hangzhou"); + String expectSign = SignUtil.sign(actual.getParameter("data"), signatureKey); + assertEquals(expectSign, actual.getParameter("signature")); } private void prepareForSts() throws NoSuchFieldException, IllegalAccessException { diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/CalculateV4SigningKeyUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/CalculateV4SigningKeyUtilTest.java new file mode 100644 index 00000000000..ac10a4fd581 --- /dev/null +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/CalculateV4SigningKeyUtilTest.java @@ -0,0 +1,38 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.client.auth.ram.utils; + +import com.alibaba.nacos.client.auth.ram.RamConstants; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class CalculateV4SigningKeyUtilTest { + + @Test + void testFinalSigningKeyStringWithException() { + assertThrows(RuntimeException.class, + () -> CalculateV4SigningKeyUtil.finalSigningKeyString("", "2021-01-01", "cn-hangzhou", + RamConstants.SIGNATURE_V4_PRODUCE, "non-exist")); + } + + @Test + void testFinalSigningKeyStringWithDefaultInfo() { + assertNotNull(CalculateV4SigningKeyUtil.finalSigningKeyStringWithDefaultInfo("", "cn-hangzhou")); + } +} \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/RamUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/RamUtilTest.java new file mode 100644 index 00000000000..1e767042b0d --- /dev/null +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/RamUtilTest.java @@ -0,0 +1,69 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.client.auth.ram.utils; + +import com.alibaba.nacos.api.PropertyKeyConst; +import com.alibaba.nacos.client.auth.ram.identify.CredentialService; +import com.alibaba.nacos.client.auth.ram.identify.Credentials; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Properties; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +public class RamUtilTest { + + private Properties properties; + + @BeforeEach + public void setUp() throws Exception { + SpasAdapter.freeCredentialInstance(); + Credentials credentials = new Credentials("spasAk", "spasSk", "spasNamespaceId"); + CredentialService.getInstance().setStaticCredential(credentials); + properties = new Properties(); + properties.setProperty(PropertyKeyConst.ACCESS_KEY, "userAk"); + properties.setProperty(PropertyKeyConst.SECRET_KEY, "userSk"); + } + + @AfterEach + public void tearDown() throws Exception { + SpasAdapter.freeCredentialInstance(); + } + + @Test + public void testGetAccessKeyWithUserAkSk() { + assertEquals("userAk", RamUtil.getAccessKey(properties)); + assertEquals("userSk", RamUtil.getSecretKey(properties)); + } + + @Test + public void testGetAccessKeyWithSpasAkSk() { + assertEquals("spasAk", RamUtil.getAccessKey(new Properties())); + assertEquals("spasSk", RamUtil.getSecretKey(new Properties())); + } + + @Test + public void testGetAccessKeyWithoutSpasAkSk() { + Properties properties1 = new Properties(); + properties1.setProperty(PropertyKeyConst.IS_USE_RAM_INFO_PARSING, "false"); + assertNull(RamUtil.getAccessKey(properties1)); + assertNull(RamUtil.getSecretKey(properties1)); + } +} \ No newline at end of file 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..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 @@ -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..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 @@ -16,73 +16,76 @@ 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"), - map3.get("Spas-Signature")); + 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..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 @@ -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; @@ -56,8 +58,8 @@ private void setFinal(Field field, Object ins, Object newValue) throws Exception } - @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); @@ -65,13 +67,13 @@ public void mock() throws Exception { 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,57 +83,52 @@ 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 = ""; - 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; 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 = ""; - 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; 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(); } @@ -139,17 +136,15 @@ public void testGetConfigFromLocalCache() throws NacosException { } @Test - public void testGetConfig403() throws NacosException { + void testGetConfig403() throws NacosException { final String dataId = "1localcache403"; 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. @@ -158,9 +153,9 @@ 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(); @@ -168,7 +163,7 @@ public void testGetConfig403() throws NacosException { } @Test - public void testGetConfigAndSignListener() throws NacosException { + void testGetConfigAndSignListener() throws NacosException { final String dataId = "1"; final String group = "2"; final String tenant = ""; @@ -214,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); @@ -225,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; } @@ -238,14 +232,13 @@ 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)); + 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() { @@ -265,42 +258,38 @@ public void receiveConfigInfo(String configInfo) { } @Test - public void testPublishConfig() throws NacosException { + void testPublishConfig() throws NacosException { String dataId = "1"; String group = "2"; 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); - Assert.assertTrue(b); + 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 - public void testPublishConfig2() throws NacosException { + void testPublishConfig2() throws NacosException { String dataId = "1"; String group = "2"; String content = "123"; 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); - Assert.assertTrue(b); + 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 - public void testPublishConfigCas() throws NacosException { + void testPublishConfigCas() throws NacosException { String dataId = "1"; String group = "2"; String content = "123"; @@ -308,18 +297,16 @@ public 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); - Assert.assertTrue(b); + 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 - public void testPublishConfigCas2() throws NacosException { + void testPublishConfigCas2() throws NacosException { String dataId = "1"; String group = "2"; String content = "123"; @@ -327,18 +314,16 @@ public 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); - Assert.assertTrue(b); + 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 - public void testRemoveConfig() throws NacosException { + void testRemoveConfig() throws NacosException { String dataId = "1"; String group = "2"; String tenant = ""; @@ -346,13 +331,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() { @@ -372,23 +357,21 @@ public void receiveConfigInfo(String configInfo) { } @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..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 @@ -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; -public class GroupKeyTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); +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 { @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..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 @@ -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; -public class ConfigContextTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +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..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,22 +21,22 @@ import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.plugin.encryption.EncryptionPluginManager; import com.alibaba.nacos.plugin.encryption.spi.EncryptionPluginService; +import org.apache.commons.codec.binary.Base64; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; -import java.nio.charset.StandardCharsets; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; 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 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.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * AES encryption algorithm testing dataId with prefix cipher. @@ -45,8 +45,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; @@ -55,8 +55,8 @@ 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"; @@ -150,30 +150,32 @@ private String aesDecrypt(String content, String key) { } @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); - 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); 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 +183,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..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 @@ -22,15 +22,63 @@ 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 { + + @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 { @@ -83,51 +131,4 @@ public String getFilterName() { return name; } } - - @Test - public 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 - Assert.assertEquals(1, configContext.getParameter("filter1")); - Assert.assertEquals(2, configContext.getParameter("filter2")); - Assert.assertEquals(3, configContext.getParameter("filter3")); - - //order - List orders = (List) configContext.getParameter("orders"); - Assert.assertEquals(Arrays.asList(1, 2, 3), orders); - } - - @Test - public 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(); - - Assert.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..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 @@ -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; -public class ConfigFilterChainTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +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..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 @@ -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; -public class ConfigRequestTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +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..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 @@ -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; -public class ConfigResponseTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +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..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 @@ -19,13 +19,67 @@ 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 { + + @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 { @@ -104,56 +158,4 @@ public boolean isShutdown() { return shutdown; } } - - @Test - public 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); - - Assert.assertEquals(name, metricsHttpAgent.getName()); - Assert.assertEquals(encode, metricsHttpAgent.getEncode()); - Assert.assertEquals(tenant, metricsHttpAgent.getTenant()); - Assert.assertEquals(namespace, metricsHttpAgent.getNamespace()); - } - - @Test - public 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(); - Assert.assertTrue(mockHttpAgent.isStart()); - - metricsHttpAgent.shutdown(); - Assert.assertTrue(mockHttpAgent.isShutdown()); - } - - @Test - public 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); - Assert.assertEquals("get /aa", result1.getMessage()); - final HttpRestResult result2 = metricsHttpAgent - .httpPost("/aa", new HashMap(), new HashMap(), "UTF-8", 1L); - Assert.assertEquals("post /aa", result2.getMessage()); - - final HttpRestResult result3 = metricsHttpAgent - .httpDelete("/aa", new HashMap(), new HashMap(), "UTF-8", 1L); - Assert.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..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 @@ -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"; @@ -67,8 +75,8 @@ public class ServerHttpAgentTest { 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); @@ -82,49 +90,49 @@ private void injectRestTemplate() throws NoSuchFieldException, IllegalAccessExce 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); @@ -133,148 +141,164 @@ 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); + HttpRestResult actual = serverHttpAgent.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), + "UTF-8", 1000); + 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()); 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); - Assert.assertEquals(mockResult, actual); + HttpRestResult actual = serverHttpAgent.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), + "UTF-8", 1000); + 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); + HttpRestResult actual = serverHttpAgent.httpPost("/test", Collections.emptyMap(), + Collections.emptyMap(), "UTF-8", 1000); + 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()); 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); - Assert.assertEquals(mockResult, actual); + HttpRestResult actual = serverHttpAgent.httpPost("/test", Collections.emptyMap(), + Collections.emptyMap(), "UTF-8", 1000); + 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); + HttpRestResult actual = serverHttpAgent.httpDelete("/test", Collections.emptyMap(), + Collections.emptyMap(), "UTF-8", 1000); + 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()); 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); - Assert.assertEquals(mockResult, actual); + HttpRestResult actual = serverHttpAgent.httpDelete("/test", Collections.emptyMap(), + Collections.emptyMap(), "UTF-8", 1000); + 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..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 @@ -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 4e0632351a3..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 @@ -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,24 +78,24 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.times; -@RunWith(MockitoJUnitRunner.class) -public class ClientWorkerTest { +@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; - - @Before - public void before() { + @BeforeEach + void before() { rpcClientFactoryMockedStatic = Mockito.mockStatic(RpcClientFactory.class); rpcClientFactoryMockedStatic.when( @@ -101,7 +103,7 @@ public void before() { any(RpcClientTlsConfig.class))).thenReturn(rpcClient); rpcClientFactoryMockedStatic.when( () -> RpcClientFactory.createClient(anyString(), any(ConnectionType.class), any(Map.class), - any(Properties.class), any(RpcClientTlsConfig.class))).thenReturn(rpcClient); + any(RpcClientTlsConfig.class))).thenReturn(rpcClient); localConfigInfoProcessorMockedStatic = Mockito.mockStatic(LocalConfigInfoProcessor.class); Properties properties = new Properties(); properties.put(PropertyKeyConst.NAMESPACE, TEST_NAMESPACE); @@ -116,25 +118,25 @@ 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); @@ -150,21 +152,21 @@ public void receiveConfigInfo(String configInfo) { } }; - clientWorker.addListeners(dataId, group, Arrays.asList(listener)); + 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); @@ -181,36 +183,36 @@ public void receiveConfigInfo(String configInfo) { String dataId = "a"; String group = "b"; - clientWorker.addTenantListeners(dataId, group, Arrays.asList(listener)); + 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, Arrays.asList(listener)); + 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"; @@ -377,7 +379,7 @@ public void testHandleConfigChangeReqeust() throws Exception { } @Test - public void testHandleClientMetricsReqeust() throws Exception { + void testHandleClientMetricsReqeust() throws Exception { Properties prop = new Properties(); String tenant = "c"; @@ -419,14 +421,14 @@ public void testHandleClientMetricsReqeust() throws Exception { .get(ClientConfigMetricRequest.MetricsKey.build(ClientConfigMetricRequest.MetricsKey.CACHE_DATA, GroupKey.getKeyTenant(dataId, group, tenant)).toString()).textValue(); - int colonIndex = metricValues.toString().lastIndexOf(":"); - Assert.assertEquals(content, metricValues.substring(0, colonIndex)); - Assert.assertEquals(md5, metricValues.substring(colonIndex + 1, metricValues.toString().length())); + int colonIndex = metricValues.lastIndexOf(":"); + 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,7 +443,7 @@ 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.assertEquals(null, configResponse.getContent()); + assertNull(configResponse.getContent()); localConfigInfoProcessorMockedStatic.verify( () -> LocalConfigInfoProcessor.saveSnapshot(eq(clientWorker.getAgentName()), eq(dataId), eq(group), eq(tenant), eq(null)), times(1)); @@ -449,7 +451,7 @@ public void testGeConfigConfigNotFound() throws NacosException { } @Test - public void testGeConfigConfigConflict() throws NacosException { + void testGeConfigConfigConflict() throws NacosException { Properties prop = new Properties(); ServerListManager agent = Mockito.mock(ServerListManager.class); @@ -465,14 +467,14 @@ 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); @@ -483,14 +485,14 @@ public void testShutdown() throws NacosException, NoSuchFieldException, IllegalA 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.assertEquals(null, 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); @@ -552,13 +554,13 @@ public void receiveConfigInfo(String configInfo) { configContext.setGroup(group); configContext.setTenant(tenant); ConfigChangeBatchListenResponse response = new ConfigChangeBatchListenResponse(); - response.setChangedConfigs(Arrays.asList(configContext)); + response.setChangedConfigs(Collections.singletonList(configContext)); RpcClient rpcClientInner = Mockito.mock(RpcClient.class); Mockito.when(rpcClientInner.isWaitInitiated()).thenReturn(true, false); rpcClientFactoryMockedStatic.when( () -> RpcClientFactory.createClient(anyString(), any(ConnectionType.class), any(Map.class), - any(Properties.class), any(RpcClientTlsConfig.class))).thenReturn(rpcClientInner); + any(RpcClientTlsConfig.class))).thenReturn(rpcClientInner); // mock listen and remove listen request Mockito.when(rpcClientInner.request(any(ConfigBatchListenRequest.class), anyLong())) .thenReturn(response, response); @@ -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()); } @@ -616,7 +618,7 @@ private CacheData useLocalCache(ConfigFilterChainManager filter, String envName, } @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); @@ -630,14 +632,14 @@ public void testIsHealthServer() throws NacosException, NoSuchFieldException, Il declaredField.setAccessible(true); declaredField.set(clientWorker, client); - Assert.assertEquals(true, clientWorker.isHealthServer()); + assertTrue(clientWorker.isHealthServer()); Mockito.when(client.isHealthServer()).thenReturn(Boolean.FALSE); - Assert.assertEquals(false, clientWorker.isHealthServer()); + 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,17 +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() - throws NacosException, IllegalAccessException, NoSuchFieldException { + void testAddListenersEnsureCacheDataSafe() throws NacosException, IllegalAccessException, NoSuchFieldException { String dataId = "testDataId"; String group = "testGroup"; // 将key-cacheData插入到cacheMap中 @@ -696,7 +697,7 @@ public void testAddListenersEnsureCacheDataSafe() } @Test - public void testAddTenantListenersEnsureCacheDataSafe() + void testAddTenantListenersEnsureCacheDataSafe() throws NacosException, IllegalAccessException, NoSuchFieldException { String dataId = "testDataId"; String group = "testGroup"; @@ -729,7 +730,7 @@ public void testAddTenantListenersEnsureCacheDataSafe() } @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..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 @@ -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..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 @@ -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; -public class ConfigHttpClientManagerTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +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..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 @@ -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; -public class LimiterTest { +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +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..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 @@ -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..7915ede5284 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,17 +28,23 @@ 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; -public class ServerListManagerTest { +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()); } @@ -47,26 +52,26 @@ public void testStart() throws NacosException { } @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")); } { 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); - Assert.assertEquals("aaa", mgr2.getContentPath()); + assertEquals("aaa", mgr2.getContentPath()); } - + // Test https { Properties properties = new Properties(); @@ -74,56 +79,58 @@ 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()); } { 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); - 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()); } - + { 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); - 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()); } - + { 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); - 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 +138,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 +165,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 +180,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 +200,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 +231,40 @@ 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 testWithEndpointClusterName() throws NacosException { + Properties properties = new Properties(); + String endpoint = "127.0.0.1"; + properties.setProperty(PropertyKeyConst.ENDPOINT, endpoint); + String endpointPort = "9090"; + properties.setProperty(PropertyKeyConst.ENDPOINT_PORT, endpointPort); + String testEndpointClusterName = "testEndpointClusterName"; + properties.setProperty(PropertyKeyConst.ENDPOINT_CLUSTER_NAME, testEndpointClusterName); + String testClusterName = "testClusterName"; + properties.setProperty(PropertyKeyConst.CLUSTER_NAME, testClusterName); + String endpointContextPath = "/endpointContextPath"; + properties.setProperty(PropertyKeyConst.ENDPOINT_CONTEXT_PATH, endpointContextPath); + String contextPath = "/contextPath"; + properties.setProperty(PropertyKeyConst.CONTEXT_PATH, contextPath); + final NacosClientProperties clientProperties = NacosClientProperties.PROTOTYPE.derive(properties); + ServerListManager serverListManager = new ServerListManager(clientProperties); + assertTrue(serverListManager.addressServerUrl.contains(endpointContextPath)); + assertTrue(serverListManager.getName().contains("endpointContextPath")); + + assertTrue(serverListManager.addressServerUrl.contains(testEndpointClusterName)); + assertTrue(serverListManager.getName().contains(testEndpointClusterName)); + + assertFalse(serverListManager.addressServerUrl.contains(testClusterName)); + assertFalse(serverListManager.getName().contains(testClusterName)); + + } + + @Test + void testWithoutEndpointContextPath() throws NacosException { Properties properties = new Properties(); String endpoint = "127.0.0.1"; properties.setProperty(PropertyKeyConst.ENDPOINT, endpoint); @@ -240,9 +275,22 @@ 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")); + } + + @Test + void testUseEndpointParsingRule() throws NacosException { + System.setProperty("nacos.endpoint", "127.0.0.1"); + Properties properties = new Properties(); + properties.setProperty(PropertyKeyConst.ENDPOINT, "${nacos.endpoint}"); + properties.setProperty(PropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, "true"); + properties.setProperty(PropertyKeyConst.ENDPOINT_PORT, "9090"); + final NacosClientProperties clientProperties = NacosClientProperties.PROTOTYPE.derive(properties); + ServerListManager serverListManager = new ServerListManager(clientProperties); + String addressServerUrl = serverListManager.addressServerUrl; + assertTrue(addressServerUrl.startsWith("http://127.0.0.1")); } } \ 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..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 @@ -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..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 @@ -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..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 @@ -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..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 @@ -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; -public class ContentUtilsTest { - - @Rule - public ExpectedException exceptionRule = ExpectedException.none(); +class ContentUtilsTest { @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..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 @@ -18,27 +18,29 @@ 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); @@ -46,17 +48,17 @@ public void tearDown() throws NoSuchFieldException, IllegalAccessException { } @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..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 @@ -19,39 +19,39 @@ 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"; @@ -59,29 +59,31 @@ public void testCheckTdg() throws NacosException { } @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,33 +176,34 @@ 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"; @@ -209,60 +212,65 @@ public void testCheckParam2() throws NacosException { } @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..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 @@ -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; -public class SnapShotSwitchTest { +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +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..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 @@ -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 { +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 { - @BeforeClass - public static void init() { + @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,40 @@ 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..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 @@ -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 { + @AfterAll + static void teardown() { + System.clearProperty(Constants.SysEnv.NACOS_ENV_FIRST); + } + + @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() { - 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); @@ -83,7 +83,7 @@ private void assertOrder(List order, SourceType... sourceTypes) { } @Test - public void testGetPropertyFromEnv() { + void testGetPropertyFromEnv() { System.setProperty("testFromSource", "jvm"); NacosClientProperties properties = SearchableProperties.INSTANCE.derive(); properties.setProperty("testFromSource", "properties"); @@ -91,7 +91,7 @@ public void testGetPropertyFromEnv() { } @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..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 @@ -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"); @@ -50,42 +50,42 @@ public void setUp() throws Exception { } @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..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 @@ -16,42 +16,45 @@ 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)); @@ -59,49 +62,57 @@ public void testConvertBooleanTrue() { } @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)); + 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..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 @@ -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; @@ -43,8 +43,8 @@ public class NacosLoggingTest { 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"); @@ -53,13 +53,13 @@ public void setUp() throws NoSuchFieldException, IllegalAccessException { } @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); @@ -69,7 +69,7 @@ public void testLoadConfiguration() throws NoSuchFieldException, IllegalAccessEx } @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..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 @@ -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; @@ -58,18 +58,18 @@ public class NacosNamingMaintainServiceTest { 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"); - + 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); @@ -84,18 +84,18 @@ public void setUp() throws Exception { 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"; @@ -107,7 +107,7 @@ public void testUpdateInstance1() throws NacosException { } @Test - public void testUpdateInstance2() throws NacosException { + void testUpdateInstance2() throws NacosException { //given String serviceName = "service1"; Instance instance = new Instance(); @@ -118,7 +118,7 @@ public void testUpdateInstance2() throws NacosException { } @Test - public void testQueryService1() throws NacosException { + void testQueryService1() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -129,7 +129,7 @@ public void testQueryService1() throws NacosException { } @Test - public void testQueryService2() throws NacosException { + void testQueryService2() throws NacosException { //given String serviceName = "service1"; Instance instance = new Instance(); @@ -140,7 +140,7 @@ public void testQueryService2() throws NacosException { } @Test - public void testCreateService1() throws NacosException { + void testCreateService1() throws NacosException { //given String serviceName = "service1"; //when @@ -157,7 +157,7 @@ public boolean matches(Service service) { } @Test - public void testCreateService2() throws NacosException { + void testCreateService2() throws NacosException { //given String serviceName = "service1"; String groupName = "groupName"; @@ -175,7 +175,7 @@ public boolean matches(Service service) { } @Test - public void testCreateService3() throws NacosException { + void testCreateService3() throws NacosException { //given String serviceName = "service1"; String groupName = "groupName"; @@ -194,7 +194,7 @@ public boolean matches(Service service) { } @Test - public void testCreateService5() throws NacosException { + void testCreateService5() throws NacosException { //given String serviceName = "service1"; String groupName = "groupName"; @@ -214,7 +214,7 @@ public boolean matches(Service service) { } @Test - public void testCreateService4() throws NacosException { + void testCreateService4() throws NacosException { //given Service service = new Service(); AbstractSelector selector = new NoneSelector(); @@ -225,7 +225,7 @@ public void testCreateService4() throws NacosException { } @Test - public void testDeleteService1() throws NacosException { + void testDeleteService1() throws NacosException { //given String serviceName = "service1"; //when @@ -235,7 +235,7 @@ public void testDeleteService1() throws NacosException { } @Test - public void testDeleteService2() throws NacosException { + void testDeleteService2() throws NacosException { //given String serviceName = "service1"; String groupName = "groupName"; @@ -246,7 +246,7 @@ public void testDeleteService2() throws NacosException { } @Test - public void testUpdateService1() throws NacosException { + void testUpdateService1() throws NacosException { //given String serviceName = "service1"; String groupName = "groupName"; @@ -265,7 +265,7 @@ public boolean matches(Service service) { } @Test - public void testUpdateService2() throws NacosException { + void testUpdateService2() throws NacosException { //given String serviceName = "service1"; String groupName = "groupName"; @@ -287,7 +287,7 @@ public boolean matches(Service service) { } @Test - public void testUpdateService3() throws NacosException { + void testUpdateService3() throws NacosException { //given Service service = new Service(); AbstractSelector selector = new NoneSelector(); @@ -298,7 +298,7 @@ public void testUpdateService3() throws NacosException { } @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..7b1b0275bf0 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 @@ -30,17 +30,16 @@ import com.alibaba.nacos.client.naming.event.InstancesChangeNotifier; import com.alibaba.nacos.client.naming.remote.NamingClientProxy; import com.alibaba.nacos.client.naming.remote.http.NamingHttpClientProxy; +import com.alibaba.nacos.client.naming.selector.NamingSelectorFactory; +import com.alibaba.nacos.client.naming.selector.NamingSelectorWrapper; 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 +48,11 @@ import java.util.List; import java.util.Properties; -import static org.junit.Assert.assertEquals; +import static com.alibaba.nacos.client.naming.selector.NamingSelectorFactory.getUniqueClusterString; +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 +63,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; @@ -77,8 +77,8 @@ public class NacosNamingServiceTest { 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"); @@ -86,8 +86,8 @@ public void before() throws NoSuchFieldException, NacosException, IllegalAccessE injectMocks(client); } - @After - public void tearDown() throws NacosException { + @AfterEach + void tearDown() throws NacosException { client.shutDown(); } @@ -118,7 +118,7 @@ private void injectMocks(NacosNamingService client) throws NoSuchFieldException, } @Test - public void testRegisterInstance1() throws NacosException { + void testRegisterInstance1() throws NacosException { //given String serviceName = "service1"; String ip = "1.1.1.1"; @@ -133,7 +133,7 @@ public void testRegisterInstance1() throws NacosException { } @Test - public void testBatchRegisterInstance() throws NacosException { + void testBatchRegisterInstance() throws NacosException { Instance instance = new Instance(); String serviceName = "service1"; String ip = "1.1.1.1"; @@ -152,7 +152,7 @@ public void testBatchRegisterInstance() throws NacosException { } @Test - public void testBatchRegisterInstanceWithGroupNamePrefix() throws NacosException { + void testBatchRegisterInstanceWithGroupNamePrefix() throws NacosException { Instance instance = new Instance(); String serviceName = "service1"; String ip = "1.1.1.1"; @@ -171,7 +171,7 @@ public void testBatchRegisterInstanceWithGroupNamePrefix() throws NacosException } @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 +186,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 +207,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"; @@ -229,7 +229,7 @@ public void testRegisterInstance2() throws NacosException { } @Test - public void testRegisterInstance3() throws NacosException { + void testRegisterInstance3() throws NacosException { //given String serviceName = "service1"; String clusterName = "cluster1"; @@ -245,7 +245,7 @@ public void testRegisterInstance3() throws NacosException { } @Test - public void testRegisterInstance4() throws NacosException { + void testRegisterInstance4() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -262,7 +262,7 @@ public void testRegisterInstance4() throws NacosException { } @Test - public void testRegisterInstance5() throws NacosException { + void testRegisterInstance5() throws NacosException { //given String serviceName = "service1"; Instance instance = new Instance(); @@ -273,7 +273,7 @@ public void testRegisterInstance5() throws NacosException { } @Test - public void testRegisterInstance6() throws NacosException { + void testRegisterInstance6() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -285,22 +285,23 @@ public void testRegisterInstance6() throws NacosException { } @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"; @@ -315,7 +316,7 @@ public void testDeregisterInstance1() throws NacosException { } @Test - public void testDeregisterInstance2() throws NacosException { + void testDeregisterInstance2() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -331,7 +332,7 @@ public void testDeregisterInstance2() throws NacosException { } @Test - public void testDeregisterInstance3() throws NacosException { + void testDeregisterInstance3() throws NacosException { //given String serviceName = "service1"; String clusterName = "cluster1"; @@ -347,7 +348,7 @@ public void testDeregisterInstance3() throws NacosException { } @Test - public void testDeregisterInstance4() throws NacosException { + void testDeregisterInstance4() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -364,7 +365,7 @@ public void testDeregisterInstance4() throws NacosException { } @Test - public void testDeregisterInstance5() throws NacosException { + void testDeregisterInstance5() throws NacosException { //given String serviceName = "service1"; Instance instance = new Instance(); @@ -375,7 +376,7 @@ public void testDeregisterInstance5() throws NacosException { } @Test - public void testDeregisterInstance6() throws NacosException { + void testDeregisterInstance6() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -387,7 +388,7 @@ public void testDeregisterInstance6() throws NacosException { } @Test - public void testGetAllInstances1() throws NacosException { + void testGetAllInstances1() throws NacosException { //given String serviceName = "service1"; //when @@ -397,7 +398,7 @@ public void testGetAllInstances1() throws NacosException { } @Test - public void testGetAllInstances2() throws NacosException { + void testGetAllInstances2() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -408,7 +409,7 @@ public void testGetAllInstances2() throws NacosException { } @Test - public void testGetAllInstances3() throws NacosException { + void testGetAllInstances3() throws NacosException { //given String serviceName = "service1"; //when @@ -418,7 +419,7 @@ public void testGetAllInstances3() throws NacosException { } @Test - public void testGetAllInstances4() throws NacosException { + void testGetAllInstances4() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -430,7 +431,7 @@ public void testGetAllInstances4() throws NacosException { } @Test - public void testGetAllInstances5() throws NacosException { + void testGetAllInstances5() throws NacosException { //given String serviceName = "service1"; List clusterList = Arrays.asList("cluster1", "cluster2"); @@ -441,7 +442,7 @@ public void testGetAllInstances5() throws NacosException { } @Test - public void testGetAllInstances6() throws NacosException { + void testGetAllInstances6() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -454,19 +455,19 @@ public void testGetAllInstances6() throws NacosException { } @Test - public void testGetAllInstances7() throws NacosException { + void testGetAllInstances7() throws NacosException { //given String serviceName = "service1"; List clusterList = Arrays.asList("cluster1", "cluster2"); //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 - public void testGetAllInstances8() throws NacosException { + void testGetAllInstances8() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -478,7 +479,7 @@ public void testGetAllInstances8() throws NacosException { } @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())); @@ -490,7 +491,7 @@ public void testGetAllInstanceFromFailover() throws NacosException { } @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); @@ -500,7 +501,7 @@ public void testGetAllInstanceFromFailoverEmpty() throws NacosException { } @Test - public void testSelectInstances1() throws NacosException { + void testSelectInstances1() throws NacosException { //given String serviceName = "service1"; //when @@ -510,7 +511,7 @@ public void testSelectInstances1() throws NacosException { } @Test - public void testSelectInstances2() throws NacosException { + void testSelectInstances2() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -521,7 +522,7 @@ public void testSelectInstances2() throws NacosException { } @Test - public void testSelectInstances3() throws NacosException { + void testSelectInstances3() throws NacosException { //given String serviceName = "service1"; //when @@ -531,7 +532,7 @@ public void testSelectInstances3() throws NacosException { } @Test - public void testSelectInstances4() throws NacosException { + void testSelectInstances4() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -543,7 +544,7 @@ public void testSelectInstances4() throws NacosException { } @Test - public void testSelectInstances5() throws NacosException { + void testSelectInstances5() throws NacosException { //given String serviceName = "service1"; List clusterList = Arrays.asList("cluster1", "cluster2"); @@ -554,7 +555,7 @@ public void testSelectInstances5() throws NacosException { } @Test - public void testSelectInstances6() throws NacosException { + void testSelectInstances6() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -567,19 +568,19 @@ public void testSelectInstances6() throws NacosException { } @Test - public void testSelectInstances7() throws NacosException { + void testSelectInstances7() throws NacosException { //given String serviceName = "service1"; List clusterList = Arrays.asList("cluster1", "cluster2"); //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 - public void testSelectInstances8() throws NacosException { + void testSelectInstances8() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -591,7 +592,7 @@ public void testSelectInstances8() throws NacosException { } @Test - public void testSelectInstancesWithHealthyFlag() throws NacosException { + void testSelectInstancesWithHealthyFlag() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setHealthy(true); @@ -623,11 +624,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"); @@ -646,7 +647,7 @@ public void testSelectOneHealthyInstance1() throws NacosException { } @Test - public void testSelectOneHealthyInstance2() throws NacosException { + void testSelectOneHealthyInstance2() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setIp("1.1.1.1"); @@ -666,7 +667,7 @@ public void testSelectOneHealthyInstance2() throws NacosException { } @Test - public void testSelectOneHealthyInstance3() throws NacosException { + void testSelectOneHealthyInstance3() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setIp("1.1.1.1"); @@ -675,8 +676,8 @@ public 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 @@ -686,7 +687,7 @@ public void testSelectOneHealthyInstance3() throws NacosException { } @Test - public void testSelectOneHealthyInstance4() throws NacosException { + void testSelectOneHealthyInstance4() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setIp("1.1.1.1"); @@ -695,8 +696,8 @@ public 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"; @@ -708,7 +709,7 @@ public void testSelectOneHealthyInstance4() throws NacosException { } @Test - public void testSelectOneHealthyInstance5() throws NacosException { + void testSelectOneHealthyInstance5() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setIp("1.1.1.1"); @@ -728,7 +729,7 @@ public void testSelectOneHealthyInstance5() throws NacosException { } @Test - public void testSelectOneHealthyInstance6() throws NacosException { + void testSelectOneHealthyInstance6() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setIp("1.1.1.1"); @@ -750,7 +751,7 @@ public void testSelectOneHealthyInstance6() throws NacosException { } @Test - public void testSelectOneHealthyInstance7() throws NacosException { + void testSelectOneHealthyInstance7() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setIp("1.1.1.1"); @@ -759,20 +760,20 @@ public 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 - public void testSelectOneHealthyInstance8() throws NacosException { + void testSelectOneHealthyInstance8() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setIp("1.1.1.1"); @@ -781,8 +782,8 @@ public 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"; @@ -794,7 +795,7 @@ public void testSelectOneHealthyInstance8() throws NacosException { } @Test - public void testSubscribe1() throws NacosException { + void testSubscribe1() throws NacosException { //given String serviceName = "service1"; EventListener listener = event -> { @@ -802,13 +803,15 @@ public void testSubscribe1() throws NacosException { }; //when client.subscribe(serviceName, listener); + NamingSelectorWrapper wrapper = new NamingSelectorWrapper(serviceName, Constants.DEFAULT_GROUP, Constants.NULL, + NamingSelectorFactory.newClusterSelector(Collections.emptyList()), listener); //then - verify(changeNotifier, times(1)).registerListener(Constants.DEFAULT_GROUP, serviceName, "", listener); + verify(changeNotifier, times(1)).registerListener(Constants.DEFAULT_GROUP, serviceName, wrapper); 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"; @@ -817,13 +820,15 @@ public void testSubscribe2() throws NacosException { }; //when client.subscribe(serviceName, groupName, listener); + NamingSelectorWrapper wrapper = new NamingSelectorWrapper(serviceName, groupName, Constants.NULL, + NamingSelectorFactory.newClusterSelector(Collections.emptyList()), listener); //then - verify(changeNotifier, times(1)).registerListener(groupName, serviceName, "", listener); + verify(changeNotifier, times(1)).registerListener(groupName, serviceName, wrapper); 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"); @@ -832,14 +837,15 @@ public void testSubscribe3() throws NacosException { }; //when client.subscribe(serviceName, clusterList, listener); + NamingSelectorWrapper wrapper = new NamingSelectorWrapper(serviceName, Constants.DEFAULT_GROUP, Constants.NULL, + NamingSelectorFactory.newClusterSelector(clusterList), listener); //then - verify(changeNotifier, times(1)) - .registerListener(Constants.DEFAULT_GROUP, serviceName, "cluster1,cluster2", listener); - verify(proxy, times(1)).subscribe(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2"); + verify(changeNotifier, times(1)).registerListener(Constants.DEFAULT_GROUP, serviceName, wrapper); + verify(proxy, times(1)).subscribe(serviceName, Constants.DEFAULT_GROUP, Constants.NULL); } @Test - public void testSubscribe4() throws NacosException { + void testSubscribe4() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -849,67 +855,99 @@ public void testSubscribe4() throws NacosException { }; //when client.subscribe(serviceName, groupName, clusterList, listener); + NamingSelectorWrapper wrapper = new NamingSelectorWrapper(serviceName, groupName, + getUniqueClusterString(clusterList), NamingSelectorFactory.newClusterSelector(clusterList), listener); //then - verify(changeNotifier, times(1)).registerListener(groupName, serviceName, "cluster1,cluster2", listener); - verify(proxy, times(1)).subscribe(serviceName, groupName, "cluster1,cluster2"); + verify(changeNotifier, times(1)).registerListener(groupName, serviceName, wrapper); + verify(proxy, times(1)).subscribe(serviceName, groupName, Constants.NULL); + } + + @Test + public void testSubscribe5() throws NacosException { + String serviceName = "service1"; + String groupName = "group1"; + EventListener listener = event -> { + + }; + //when + client.subscribe(serviceName, groupName, NamingSelectorFactory.HEALTHY_SELECTOR, listener); + NamingSelectorWrapper wrapper = new NamingSelectorWrapper(serviceName, groupName, Constants.NULL, + NamingSelectorFactory.HEALTHY_SELECTOR, listener); + //then + verify(changeNotifier, times(1)).registerListener(groupName, serviceName, wrapper); + verify(proxy, times(1)).subscribe(serviceName, groupName, Constants.NULL); } @Test - public void testSubscribeWithNullListener() throws NacosException { + void testSubscribeWithNullListener() throws NacosException { String serviceName = "service1"; String groupName = "group1"; //when client.subscribe(serviceName, groupName, null); //then - verify(changeNotifier, never()).registerListener(groupName, serviceName, "", null); + verify(changeNotifier, never()).registerListener(groupName, serviceName, + new NamingSelectorWrapper(NamingSelectorFactory.newIpSelector(""), null)); verify(proxy, never()).subscribe(serviceName, groupName, ""); } @Test - public void testUnSubscribe1() throws NacosException { + void testUnSubscribe1() throws NacosException { //given String serviceName = "service1"; EventListener listener = event -> { }; + when(changeNotifier.isSubscribed(Constants.DEFAULT_GROUP, serviceName)).thenReturn(false); + //when client.unsubscribe(serviceName, listener); //then - verify(changeNotifier, times(1)).deregisterListener(Constants.DEFAULT_GROUP, serviceName, "", listener); - verify(proxy, times(1)).unsubscribe(serviceName, Constants.DEFAULT_GROUP, ""); + NamingSelectorWrapper wrapper = new NamingSelectorWrapper( + NamingSelectorFactory.newClusterSelector(Collections.emptyList()), listener); + verify(changeNotifier, times(1)).deregisterListener(Constants.DEFAULT_GROUP, serviceName, wrapper); + verify(proxy, times(1)).unsubscribe(serviceName, Constants.DEFAULT_GROUP, Constants.NULL); } @Test - public void testUnSubscribe2() throws NacosException { + void testUnSubscribe2() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; EventListener listener = event -> { }; + when(changeNotifier.isSubscribed(groupName, serviceName)).thenReturn(false); + + //when client.unsubscribe(serviceName, groupName, listener); + NamingSelectorWrapper wrapper = new NamingSelectorWrapper( + NamingSelectorFactory.newClusterSelector(Collections.emptyList()), listener); //then - verify(changeNotifier, times(1)).deregisterListener(groupName, serviceName, "", listener); - verify(proxy, times(1)).unsubscribe(serviceName, groupName, ""); + verify(changeNotifier, times(1)).deregisterListener(groupName, serviceName, wrapper); + verify(proxy, times(1)).unsubscribe(serviceName, groupName, Constants.NULL); } @Test - public void testUnSubscribe3() throws NacosException { + void testUnSubscribe3() throws NacosException { //given String serviceName = "service1"; List clusterList = Arrays.asList("cluster1", "cluster2"); EventListener listener = event -> { }; + when(changeNotifier.isSubscribed(Constants.DEFAULT_GROUP, serviceName)).thenReturn(false); + + //when client.unsubscribe(serviceName, clusterList, listener); + NamingSelectorWrapper wrapper = new NamingSelectorWrapper(NamingSelectorFactory.newClusterSelector(clusterList), + listener); //then - verify(changeNotifier, times(1)) - .deregisterListener(Constants.DEFAULT_GROUP, serviceName, "cluster1,cluster2", listener); - verify(proxy, times(1)).unsubscribe(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2"); + verify(changeNotifier, times(1)).deregisterListener(Constants.DEFAULT_GROUP, serviceName, wrapper); + verify(proxy, times(1)).unsubscribe(serviceName, Constants.DEFAULT_GROUP, Constants.NULL); } @Test - public void testUnSubscribe4() throws NacosException { + void testUnSubscribe4() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -917,14 +955,37 @@ public void testUnSubscribe4() throws NacosException { EventListener listener = event -> { }; + when(changeNotifier.isSubscribed(groupName, serviceName)).thenReturn(false); + + //when client.unsubscribe(serviceName, groupName, clusterList, listener); + NamingSelectorWrapper wrapper = new NamingSelectorWrapper(NamingSelectorFactory.newClusterSelector(clusterList), + listener); + //then + verify(changeNotifier, times(1)).deregisterListener(groupName, serviceName, wrapper); + verify(proxy, times(1)).unsubscribe(serviceName, groupName, Constants.NULL); + } + + @Test + public void testUnSubscribe5() throws NacosException { + //given + String serviceName = "service1"; + String groupName = "group1"; + EventListener listener = event -> { + + }; + when(changeNotifier.isSubscribed(groupName, serviceName)).thenReturn(false); + + //when + client.unsubscribe(serviceName, groupName, NamingSelectorFactory.HEALTHY_SELECTOR, listener); + NamingSelectorWrapper wrapper = new NamingSelectorWrapper(NamingSelectorFactory.HEALTHY_SELECTOR, listener); //then - verify(changeNotifier, times(1)).deregisterListener(groupName, serviceName, "cluster1,cluster2", listener); - verify(proxy, times(1)).unsubscribe(serviceName, groupName, "cluster1,cluster2"); + verify(changeNotifier, times(1)).deregisterListener(groupName, serviceName, wrapper); + verify(proxy, times(1)).unsubscribe(serviceName, groupName, Constants.NULL); } @Test - public void testGetServicesOfServer1() throws NacosException { + void testGetServicesOfServer1() throws NacosException { //given int pageNo = 1; int pageSize = 10; @@ -935,7 +996,7 @@ public void testGetServicesOfServer1() throws NacosException { } @Test - public void testGetServicesOfServer2() throws NacosException { + void testGetServicesOfServer2() throws NacosException { //given int pageNo = 1; int pageSize = 10; @@ -947,7 +1008,7 @@ public void testGetServicesOfServer2() throws NacosException { } @Test - public void testGetServicesOfServer3() throws NacosException { + void testGetServicesOfServer3() throws NacosException { //given int pageNo = 1; int pageSize = 10; @@ -964,7 +1025,7 @@ public String getType() { } @Test - public void testGetServicesOfServer4() throws NacosException { + void testGetServicesOfServer4() throws NacosException { //given int pageNo = 1; int pageSize = 10; @@ -983,7 +1044,7 @@ public String getType() { } @Test - public void testGetSubscribeServices() { + void testGetSubscribeServices() { //when client.getSubscribeServices(); //then @@ -991,7 +1052,7 @@ public void testGetSubscribeServices() { } @Test - public void testGetServerStatus() { + void testGetServerStatus() { //given when(proxy.serverHealthy()).thenReturn(true); //when @@ -1001,7 +1062,7 @@ public void testGetServerStatus() { } @Test - public void testGetServerStatusFail() { + void testGetServerStatusFail() { //given when(proxy.serverHealthy()).thenReturn(false); //when @@ -1011,7 +1072,7 @@ public void testGetServerStatusFail() { } @Test - public void testShutDown() throws NacosException { + void testShutDown() throws NacosException { //when client.shutDown(); //then @@ -1019,7 +1080,7 @@ public void testShutDown() throws NacosException { } @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..2116ea33c9e 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 @@ -17,34 +17,33 @@ package com.alibaba.nacos.client.naming.backups; import com.alibaba.nacos.api.exception.NacosException; +import com.alibaba.nacos.api.naming.pojo.Instance; 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; import java.lang.reflect.Method; -import java.util.Collections; import java.util.HashMap; import java.util.Map; 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.mockito.ArgumentMatchers.any; +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.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class FailoverReactorTest { +@ExtendWith(MockitoExtension.class) +class FailoverReactorTest { @Mock ServiceInfoHolder holder; @@ -54,42 +53,42 @@ public class FailoverReactorTest { 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); when(failoverDataSource.getSwitch()).thenReturn(mockFailoverSwitch); Map map = new HashMap<>(); ServiceInfo serviceInfo = new ServiceInfo("a@@b"); + serviceInfo.addHost(new Instance()); map.put("a@@b", NamingFailoverData.newNamingFailoverData(serviceInfo)); when(failoverDataSource.getFailoverData()).thenReturn(map); - when(holder.isChangedServiceInfo(any(), any())).thenReturn(true); // waiting refresh thread work TimeUnit.MILLISECONDS.sleep(5500); ServiceInfo actual = failoverReactor.getService("a@@b"); @@ -97,7 +96,7 @@ public void testRefreshFromDisabledToEnabled() throws InterruptedException { } @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); @@ -109,8 +108,7 @@ public void testRefreshFromDisabledToEnabledWithException() throws InterruptedEx } @Test - public 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); @@ -120,12 +118,12 @@ public void testRefreshFromEnabledToDisabled() failoverSwitchEnableField.set(failoverReactor, true); Map map = new HashMap<>(); ServiceInfo serviceInfo = new ServiceInfo("a@@b"); + serviceInfo.addHost(new Instance()); map.put("a@@b", serviceInfo); when(holder.getServiceInfoMap()).thenReturn(map); Field serviceMapField = FailoverReactor.class.getDeclaredField("serviceMap"); serviceMapField.setAccessible(true); serviceMapField.set(failoverReactor, map); - when(holder.isChangedServiceInfo(any(), any())).thenReturn(true); // waiting refresh thread work TimeUnit.MILLISECONDS.sleep(5500); ServiceInfo actual = failoverReactor.getService("a@@b"); @@ -133,7 +131,7 @@ public void testRefreshFromEnabledToDisabled() } @Test - public void testFailoverServiceCntMetrics() + void testFailoverServiceCntMetrics() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Method method = FailoverReactor.class.getDeclaredMethod("failoverServiceCntMetrics"); method.setAccessible(true); @@ -142,11 +140,8 @@ public void testFailoverServiceCntMetrics() } @Test - public void testFailoverServiceCntMetricsClear() + void testFailoverServiceCntMetricsClear() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException { - Field field = FailoverReactor.class.getDeclaredField("meterMap"); - field.setAccessible(true); - field.set(failoverReactor, Collections.singletonMap("a", null)); Method method = FailoverReactor.class.getDeclaredMethod("failoverServiceCntMetricsClear"); method.setAccessible(true); method.invoke(failoverReactor); 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..122cd8cfcf9 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,35 +19,34 @@ 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(); @@ -55,8 +54,8 @@ public void testGetSwitchForFailoverDisabled() throws NoSuchFieldException, Ille } @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(); @@ -68,7 +67,7 @@ public void testGetSwitchForFailoverEnabled() throws NoSuchFieldException, Illeg } @Test - public void testGetFailoverDataForFailoverDisabled() { + void testGetFailoverDataForFailoverDisabled() { Map actual = dataSource.getFailoverData(); assertTrue(actual.isEmpty()); } @@ -78,4 +77,20 @@ private void injectFailOverDir(String failoverDir) throws NoSuchFieldException, failoverDirField.setAccessible(true); failoverDirField.set(dataSource, failoverDir); } -} \ No newline at end of file + + @Test + void testGetSwitchForFailoverEnabledKeep() throws NoSuchFieldException, IllegalAccessException { + String dir = DiskFailoverDataSourceTest.class.getResource("/").getPath() + "/failover_test/enabled"; + injectFailOverDir(dir); + assertTrue(dataSource.getSwitch().getEnabled()); + assertTrue(dataSource.getSwitch().getEnabled()); + } + + @Test + void testGetSwitchForFailoverDisabledKeep() throws NoSuchFieldException, IllegalAccessException { + String dir = DiskFailoverDataSourceTest.class.getResource("/").getPath() + "/failover_test/disabled"; + injectFailOverDir(dir); + assertFalse(dataSource.getSwitch().getEnabled()); + assertFalse(dataSource.getSwitch().getEnabled()); + } +} 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..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 @@ -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,11 +28,12 @@ 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/"; @@ -41,8 +41,8 @@ public class DiskCacheTest { private Instance instance; - @Before - public void setUp() { + @BeforeEach + void setUp() { System.out.println(CACHE_DIR); serviceInfo = new ServiceInfo("G@@testName", "testClusters"); instance = new Instance(); @@ -54,8 +54,8 @@ public void setUp() { 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()) { @@ -66,7 +66,7 @@ public void tearDown() { } @Test - public void testCache() { + void testCache() { DiskCache.write(serviceInfo, CACHE_DIR); Map actual = DiskCache.read(CACHE_DIR); assertEquals(1, actual.size()); @@ -75,7 +75,7 @@ public void testCache() { } @Test - public void testWriteCacheWithErrorPath() { + void testWriteCacheWithErrorPath() { File file = new File(CACHE_DIR, serviceInfo.getKeyEncoded()); try { file.mkdirs(); @@ -87,7 +87,7 @@ public void testWriteCacheWithErrorPath() { } @Test - public void testReadCacheForAllSituation() { + void testReadCacheForAllSituation() { String dir = DiskCacheTest.class.getResource("/").getPath() + "/disk_cache_test"; Map actual = DiskCache.read(dir); assertEquals(2, actual.size()); @@ -98,28 +98,32 @@ public void testReadCacheForAllSituation() { } @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) { @@ -148,8 +152,8 @@ private void assertInstance(Instance actual, Instance expected) { } @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..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 @@ -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) { @@ -96,17 +99,17 @@ private Instance createInstance(String ip, int port) { } @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..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 @@ -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..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 @@ -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; -public class ProtectModeTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +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..58a6b773069 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"; @@ -58,14 +65,14 @@ public class ServerListManagerTest { 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); 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<>(); @@ -74,8 +81,8 @@ public void setUp() throws Exception { 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); @@ -88,191 +95,191 @@ public void tearDown() throws Exception { } } - @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_CLUSTER_NAME, "bbb"); clientProperties.setProperty(PropertyKeyConst.ENDPOINT, "127.0.0.1"); Mockito.reset(nacosRestTemplate); Mockito.when(nacosRestTemplate.get(eq("http://127.0.0.1:8080/aaa/bbb"), any(), any(), any())) .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_CLUSTER_NAME, "bbb"); clientProperties.setProperty(PropertyKeyConst.ENDPOINT, "127.0.0.1"); Mockito.reset(nacosRestTemplate); Mockito.when(nacosRestTemplate.get(eq("http://127.0.0.1:8080/aaa/bbb"), any(), any(), any())) .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"); + clientProperties.setProperty(PropertyKeyConst.ENDPOINT_CLUSTER_NAME, "ccc"); clientProperties.setProperty(PropertyKeyConst.ENDPOINT, "127.0.0.1"); Mockito.reset(nacosRestTemplate); Mockito.when(nacosRestTemplate.get(eq("http://127.0.0.1:8080/aaa/ccc"), any(), any(), any())) .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"); + clientProperties.setProperty(PropertyKeyConst.ENDPOINT_CLUSTER_NAME, "ccc"); clientProperties.setProperty(PropertyKeyConst.ENDPOINT, "127.0.0.1"); Mockito.reset(nacosRestTemplate); Mockito.when(nacosRestTemplate.get(eq("http://127.0.0.1:8080/bbb/ccc"), any(), any(), any())) .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..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 @@ -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"; @@ -67,8 +71,8 @@ public class ServiceInfoUpdateServiceTest { ServiceInfoUpdateService serviceInfoUpdateService; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(); info = new ServiceInfo(); info.setName(serviceName); @@ -78,15 +82,15 @@ public void setUp() throws Exception { 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); @@ -94,7 +98,7 @@ public void testScheduleUpdateWithoutOpen() throws InterruptedException, NacosEx } @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); @@ -104,7 +108,7 @@ public void testScheduleUpdateIfAbsent() throws InterruptedException, NacosExcep } @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); @@ -116,7 +120,7 @@ public void testScheduleUpdateIfAbsentDuplicate() throws InterruptedException, N } @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); @@ -129,7 +133,7 @@ public void testScheduleUpdateIfAbsentUpdateOlder() throws InterruptedException, } @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); @@ -143,43 +147,43 @@ public void testScheduleUpdateIfAbsentUpdateOlderWithInstance() throws Interrupt } @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); 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 - 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); 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 - 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); 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 - 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); @@ -190,7 +194,7 @@ public void testStopScheduleUpdateIfAbsent() throws InterruptedException, NacosE } @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..e6e7cd3bd17 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,18 @@ 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; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class InstancesChangeEventTest { @Test - public void testGetServiceName() { + void testGetServiceName() { String eventScope = "scope-001"; String serviceName = "a"; String groupName = "b"; @@ -34,13 +36,22 @@ public void testGetServiceName() { List hosts = new ArrayList<>(); 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()); + InstancesDiff diff = new InstancesDiff(); + diff.setAddedInstances(hosts); + InstancesChangeEvent event = new InstancesChangeEvent(eventScope, serviceName, groupName, clusters, hosts, + diff); + 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)); + InstancesDiff diff1 = event.getInstancesDiff(); + assertTrue(diff1.hasDifferent()); + assertEquals(diff.getAddedInstances().size(), diff1.getAddedInstances().size()); + assertEquals(diff.getAddedInstances().get(0), diff.getAddedInstances().get(0)); + assertEquals(diff.getRemovedInstances().size(), diff1.getRemovedInstances().size()); + assertEquals(diff.getModifiedInstances().size(), diff1.getModifiedInstances().size()); } } \ 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..4509e71e933 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,140 +20,148 @@ 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 com.alibaba.nacos.api.naming.selector.NamingSelector; +import com.alibaba.nacos.client.naming.selector.DefaultNamingSelector; +import com.alibaba.nacos.client.naming.selector.NamingSelectorFactory; +import com.alibaba.nacos.client.naming.selector.NamingSelectorWrapper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.ArrayList; +import java.util.Collections; 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.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.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; -public class InstancesChangeNotifierTest { +class InstancesChangeNotifierTest { + + private static final String EVENT_SCOPE_CASE = "scope-001"; + + private static final String GROUP_CASE = "a"; + + private static final String SERVICE_NAME_CASE = "b"; + + private static final String CLUSTER_STR_CASE = "c"; + + InstancesChangeNotifier instancesChangeNotifier; + + @BeforeEach + public void setUp() { + instancesChangeNotifier = new InstancesChangeNotifier(EVENT_SCOPE_CASE); + } @Test - public void testRegisterListener() { - String eventScope = "scope-001"; - String group = "a"; - String name = "b"; - String clusters = "c"; - InstancesChangeNotifier instancesChangeNotifier = new InstancesChangeNotifier(eventScope); + void testRegisterListener() { + List clusters = Collections.singletonList(CLUSTER_STR_CASE); EventListener listener = Mockito.mock(EventListener.class); - instancesChangeNotifier.registerListener(group, name, clusters, listener); + NamingSelector selector = NamingSelectorFactory.newClusterSelector(clusters); + NamingSelectorWrapper wrapper = new NamingSelectorWrapper(SERVICE_NAME_CASE, GROUP_CASE, CLUSTER_STR_CASE, + selector, listener); + instancesChangeNotifier.registerListener(GROUP_CASE, SERVICE_NAME_CASE, wrapper); 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_CASE, subscribeServices.get(0).getGroupName()); + assertEquals(SERVICE_NAME_CASE, subscribeServices.get(0).getName()); + assertNull(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)); + InstancesDiff diff = new InstancesDiff(); + diff.setAddedInstances(hosts); + InstancesChangeEvent event = new InstancesChangeEvent(EVENT_SCOPE_CASE, SERVICE_NAME_CASE, GROUP_CASE, + CLUSTER_STR_CASE, hosts, diff); + assertTrue(instancesChangeNotifier.scopeMatches(event)); } @Test - public void testDeregisterListener() { - String eventScope = "scope-001"; - String group = "a"; - String name = "b"; - String clusters = "c"; - InstancesChangeNotifier instancesChangeNotifier = new InstancesChangeNotifier(eventScope); + void testDeregisterListener() { + List clusters = Collections.singletonList(CLUSTER_STR_CASE); EventListener listener = Mockito.mock(EventListener.class); - instancesChangeNotifier.registerListener(group, name, clusters, listener); + NamingSelector selector = NamingSelectorFactory.newClusterSelector(clusters); + NamingSelectorWrapper wrapper = new NamingSelectorWrapper(selector, listener); + instancesChangeNotifier.registerListener(GROUP_CASE, SERVICE_NAME_CASE, wrapper); List subscribeServices = instancesChangeNotifier.getSubscribeServices(); - Assert.assertEquals(1, subscribeServices.size()); + assertEquals(1, subscribeServices.size()); - instancesChangeNotifier.deregisterListener(group, name, clusters, listener); + instancesChangeNotifier.deregisterListener(GROUP_CASE, SERVICE_NAME_CASE, wrapper); List subscribeServices2 = instancesChangeNotifier.getSubscribeServices(); - Assert.assertEquals(0, subscribeServices2.size()); - - instancesChangeNotifier.deregisterListener(group, name, clusters, listener); - Assert.assertEquals(0, subscribeServices2.size()); + assertEquals(0, subscribeServices2.size()); } @Test - public void testIsSubscribed() { - String eventScope = "scope-001"; - String group = "a"; - String name = "b"; - String clusters = "c"; - InstancesChangeNotifier instancesChangeNotifier = new InstancesChangeNotifier(eventScope); + void testIsSubscribed() { + List clusters = Collections.singletonList(CLUSTER_STR_CASE); EventListener listener = Mockito.mock(EventListener.class); - Assert.assertFalse(instancesChangeNotifier.isSubscribed(group, name, clusters)); + NamingSelector selector = NamingSelectorFactory.newClusterSelector(clusters); + assertFalse(instancesChangeNotifier.isSubscribed(GROUP_CASE, SERVICE_NAME_CASE)); - instancesChangeNotifier.registerListener(group, name, clusters, listener); - Assert.assertTrue(instancesChangeNotifier.isSubscribed(group, name, clusters)); + NamingSelectorWrapper wrapper = new NamingSelectorWrapper(SERVICE_NAME_CASE, GROUP_CASE, CLUSTER_STR_CASE, + selector, listener); + instancesChangeNotifier.registerListener(GROUP_CASE, SERVICE_NAME_CASE, wrapper); + assertTrue(instancesChangeNotifier.isSubscribed(GROUP_CASE, SERVICE_NAME_CASE)); } @Test - public void testOnEvent() { - String eventScope = "scope-001"; - String group = "a"; - String name = "b"; - String clusters = "c"; - InstancesChangeNotifier instancesChangeNotifier = new InstancesChangeNotifier(eventScope); + void testOnEvent() { + List clusters = Collections.singletonList(CLUSTER_STR_CASE); + NamingSelector selector = NamingSelectorFactory.newClusterSelector(clusters); EventListener listener = Mockito.mock(EventListener.class); - instancesChangeNotifier.registerListener(group, name, clusters, listener); - InstancesChangeEvent event1 = Mockito.mock(InstancesChangeEvent.class); - when(event1.getClusters()).thenReturn(clusters); - when(event1.getGroupName()).thenReturn(group); - when(event1.getServiceName()).thenReturn(name); - + NamingSelectorWrapper wrapper = new NamingSelectorWrapper(SERVICE_NAME_CASE, GROUP_CASE, CLUSTER_STR_CASE, + selector, listener); + instancesChangeNotifier.registerListener(GROUP_CASE, SERVICE_NAME_CASE, wrapper); + Instance instance = new Instance(); + InstancesDiff diff = new InstancesDiff(null, Collections.singletonList(instance), null); + instance.setClusterName(CLUSTER_STR_CASE); + InstancesChangeEvent event1 = new InstancesChangeEvent(null, SERVICE_NAME_CASE, GROUP_CASE, CLUSTER_STR_CASE, + Collections.emptyList(), diff); instancesChangeNotifier.onEvent(event1); Mockito.verify(listener, times(1)).onEvent(any()); } @Test - public void testOnEventWithoutListener() { - String eventScope = "scope-001"; - String group = "a"; - String name = "b"; - String clusters = "c"; + void testOnEventWithoutListener() { InstancesChangeEvent event1 = Mockito.mock(InstancesChangeEvent.class); - when(event1.getClusters()).thenReturn(clusters); - when(event1.getGroupName()).thenReturn(group); - when(event1.getServiceName()).thenReturn(name); + when(event1.getClusters()).thenReturn(CLUSTER_STR_CASE); + when(event1.getGroupName()).thenReturn(GROUP_CASE); + when(event1.getServiceName()).thenReturn(SERVICE_NAME_CASE); EventListener listener = Mockito.mock(EventListener.class); - InstancesChangeNotifier instancesChangeNotifier = new InstancesChangeNotifier(eventScope); - instancesChangeNotifier.registerListener(group, name + "c", clusters, listener); + instancesChangeNotifier.registerListener(GROUP_CASE, SERVICE_NAME_CASE + "c", new NamingSelectorWrapper( + NamingSelectorFactory.newClusterSelector(Collections.singletonList(CLUSTER_STR_CASE)), listener)); instancesChangeNotifier.onEvent(event1); Mockito.verify(listener, never()).onEvent(any()); } @Test - public void testOnEventByExecutor() { - String eventScope = "scope-001"; - String group = "a"; - String name = "b"; - String clusters = "c"; - InstancesChangeNotifier instancesChangeNotifier = new InstancesChangeNotifier(eventScope); + void testOnEventByExecutor() { AbstractEventListener listener = Mockito.mock(AbstractEventListener.class); Executor executor = mock(Executor.class); when(listener.getExecutor()).thenReturn(executor); - instancesChangeNotifier.registerListener(group, name, clusters, listener); - InstancesChangeEvent event1 = Mockito.mock(InstancesChangeEvent.class); - when(event1.getClusters()).thenReturn(clusters); - when(event1.getGroupName()).thenReturn(group); - when(event1.getServiceName()).thenReturn(name); - - instancesChangeNotifier.onEvent(event1); + instancesChangeNotifier.registerListener(GROUP_CASE, SERVICE_NAME_CASE, + new NamingSelectorWrapper(new DefaultNamingSelector(instance -> true), listener)); + InstancesDiff instancesDiff = new InstancesDiff(); + instancesDiff.setRemovedInstances(Collections.singletonList(new Instance())); + InstancesChangeEvent event = new InstancesChangeEvent(EVENT_SCOPE_CASE, SERVICE_NAME_CASE, GROUP_CASE, + CLUSTER_STR_CASE, new ArrayList<>(), instancesDiff); + instancesChangeNotifier.onEvent(event); Mockito.verify(executor).execute(any()); } @Test - public void testSubscribeType() { - String eventScope = "scope-001"; - InstancesChangeNotifier instancesChangeNotifier = new InstancesChangeNotifier(eventScope); - Assert.assertEquals(InstancesChangeEvent.class, instancesChangeNotifier.subscribeType()); + void testSubscribeType() { + assertEquals(InstancesChangeEvent.class, instancesChangeNotifier.subscribeType()); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesDiffTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesDiffTest.java new file mode 100644 index 00000000000..af3f9ecf6d2 --- /dev/null +++ b/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesDiffTest.java @@ -0,0 +1,112 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.client.naming.event; + +import com.alibaba.nacos.api.naming.pojo.Instance; +import com.alibaba.nacos.api.naming.pojo.builder.InstanceBuilder; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Random; + +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 InstancesDiffTest { + + private static List getInstanceList(int count) { + ArrayList list = new ArrayList<>(count); + for (int i = 0; i < count; i++) { + list.add(new Instance()); + } + return list; + } + + @Test + public void testGetDiff() { + String serviceName = "testService"; + Instance addedIns = InstanceBuilder.newBuilder().setServiceName(serviceName).setClusterName("a").build(); + Instance removedIns = InstanceBuilder.newBuilder().setServiceName(serviceName).setClusterName("b").build(); + Instance modifiedIns = InstanceBuilder.newBuilder().setServiceName(serviceName).setClusterName("c").build(); + + InstancesDiff instancesDiff = new InstancesDiff(); + instancesDiff.setAddedInstances(Collections.singletonList(addedIns)); + instancesDiff.setRemovedInstances(Collections.singletonList(removedIns)); + instancesDiff.setModifiedInstances(Collections.singletonList(modifiedIns)); + + assertTrue(instancesDiff.hasDifferent()); + assertTrue(instancesDiff.isAdded()); + assertTrue(instancesDiff.isRemoved()); + assertTrue(instancesDiff.isModified()); + assertEquals(addedIns, instancesDiff.getAddedInstances().get(0)); + assertEquals(removedIns, instancesDiff.getRemovedInstances().get(0)); + assertEquals(modifiedIns, instancesDiff.getModifiedInstances().get(0)); + } + + @Test + public void testWithFullConstructor() { + Random random = new Random(); + int addedCount = random.nextInt(32) + 1; + int removedCount = random.nextInt(32) + 1; + int modifiedCount = random.nextInt(32) + 1; + InstancesDiff instancesDiff = new InstancesDiff(getInstanceList(addedCount), getInstanceList(removedCount), + getInstanceList(modifiedCount)); + + assertTrue(instancesDiff.hasDifferent()); + assertTrue(instancesDiff.isAdded()); + assertTrue(instancesDiff.isRemoved()); + assertTrue(instancesDiff.isModified()); + assertEquals(addedCount, instancesDiff.getAddedInstances().size()); + assertEquals(removedCount, instancesDiff.getRemovedInstances().size()); + assertEquals(modifiedCount, instancesDiff.getModifiedInstances().size()); + instancesDiff.getAddedInstances().clear(); + instancesDiff.getRemovedInstances().clear(); + instancesDiff.getModifiedInstances().clear(); + assertFalse(instancesDiff.hasDifferent()); + assertFalse(instancesDiff.hasDifferent()); + assertFalse(instancesDiff.isAdded()); + assertFalse(instancesDiff.isRemoved()); + assertFalse(instancesDiff.isModified()); + } + + @Test + public void testWithNoConstructor() { + Random random = new Random(); + int addedCount = random.nextInt(32) + 1; + int removedCount = random.nextInt(32) + 1; + int modifiedCount = random.nextInt(32) + 1; + InstancesDiff instancesDiff = new InstancesDiff(); + instancesDiff.setAddedInstances(getInstanceList(addedCount)); + instancesDiff.setRemovedInstances(getInstanceList(removedCount)); + instancesDiff.setModifiedInstances(getInstanceList(modifiedCount)); + + assertTrue(instancesDiff.hasDifferent()); + assertEquals(addedCount, instancesDiff.getAddedInstances().size()); + assertEquals(removedCount, instancesDiff.getRemovedInstances().size()); + assertEquals(modifiedCount, instancesDiff.getModifiedInstances().size()); + instancesDiff.getAddedInstances().clear(); + instancesDiff.getRemovedInstances().clear(); + instancesDiff.getModifiedInstances().clear(); + assertFalse(instancesDiff.hasDifferent()); + assertFalse(instancesDiff.isAdded()); + assertFalse(instancesDiff.isRemoved()); + assertFalse(instancesDiff.isModified()); + } +} diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/listener/NamingChangeEventTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/listener/NamingChangeEventTest.java new file mode 100644 index 00000000000..7f97bbcbb10 --- /dev/null +++ b/client/src/test/java/com/alibaba/nacos/client/naming/listener/NamingChangeEventTest.java @@ -0,0 +1,136 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.client.naming.listener; + +import com.alibaba.nacos.api.naming.pojo.Instance; +import com.alibaba.nacos.client.naming.event.InstancesDiff; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.Collections; + +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.junit.jupiter.api.Assertions.assertFalse; + +public class NamingChangeEventTest { + + private MockNamingEventListener eventListener; + + private InstancesDiff instancesDiff; + + @BeforeEach + public void setUp() throws Exception { + eventListener = new MockNamingEventListener(); + instancesDiff = new InstancesDiff(); + instancesDiff.setAddedInstances(Arrays.asList(new Instance(), new Instance(), new Instance())); + instancesDiff.setRemovedInstances(Arrays.asList(new Instance(), new Instance())); + instancesDiff.setModifiedInstances(Arrays.asList(new Instance())); + } + + @Test + public void testNamingChangeEventWithSimpleConstructor() { + NamingChangeEvent event = new NamingChangeEvent("serviceName", Collections.EMPTY_LIST, instancesDiff); + assertEquals("serviceName", event.getServiceName()); + assertNull(event.getGroupName()); + assertNull(event.getClusters()); + assertTrue(event.getInstances().isEmpty()); + assertTrue(event.isAdded()); + assertEquals(3, event.getAddedInstances().size()); + assertTrue(event.isRemoved()); + assertEquals(2, event.getRemovedInstances().size()); + assertTrue(event.isModified()); + assertEquals(1, event.getModifiedInstances().size()); + eventListener.onEvent(event); + assertNull(event.getServiceName()); + assertNull(event.getGroupName()); + assertNull(event.getClusters()); + assertNull(event.getInstances()); + assertFalse(event.isAdded()); + assertEquals(0, event.getAddedInstances().size()); + assertFalse(event.isRemoved()); + assertEquals(0, event.getRemovedInstances().size()); + assertFalse(event.isModified()); + assertEquals(0, event.getRemovedInstances().size()); + } + + @Test + public void testNamingChangeEventWithFullConstructor() { + NamingChangeEvent event = new NamingChangeEvent("serviceName", "group", "clusters", Collections.EMPTY_LIST, + instancesDiff); + assertEquals("serviceName", event.getServiceName()); + assertEquals("group", event.getGroupName()); + assertEquals("clusters", event.getClusters()); + assertTrue(event.getInstances().isEmpty()); + assertTrue(event.isAdded()); + assertEquals(3, event.getAddedInstances().size()); + assertTrue(event.isRemoved()); + assertEquals(2, event.getRemovedInstances().size()); + assertTrue(event.isModified()); + assertEquals(1, event.getModifiedInstances().size()); + eventListener.onEvent(event); + assertNull(event.getServiceName()); + assertNull(event.getGroupName()); + assertNull(event.getClusters()); + assertNull(event.getInstances()); + assertFalse(event.isAdded()); + assertEquals(0, event.getAddedInstances().size()); + assertFalse(event.isRemoved()); + assertEquals(0, event.getRemovedInstances().size()); + assertFalse(event.isModified()); + assertEquals(0, event.getRemovedInstances().size()); + } + + @Test + public void testGetChanges() { + NamingChangeEvent event = new NamingChangeEvent("serviceName", Collections.EMPTY_LIST, instancesDiff); + assertTrue(event.isAdded()); + assertEquals(3, event.getAddedInstances().size()); + event.getAddedInstances().clear(); + assertFalse(event.isAdded()); + assertEquals(0, event.getAddedInstances().size()); + + assertTrue(event.isRemoved()); + assertEquals(2, event.getRemovedInstances().size()); + event.getRemovedInstances().clear(); + assertFalse(event.isRemoved()); + assertEquals(0, event.getRemovedInstances().size()); + + assertTrue(event.isModified()); + assertEquals(1, event.getModifiedInstances().size()); + event.getModifiedInstances().clear(); + assertFalse(event.isModified()); + assertEquals(0, event.getRemovedInstances().size()); + } + + private static class MockNamingEventListener extends AbstractNamingChangeListener { + + @Override + public void onChange(NamingChangeEvent event) { + assertNull(getExecutor()); + event.setServiceName(null); + event.setGroupName(null); + event.setClusters(null); + event.setInstances(null); + event.getAddedInstances().clear(); + event.getRemovedInstances().clear(); + event.getModifiedInstances().clear(); + } + } +} 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..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 @@ -31,21 +31,22 @@ 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; @@ -54,16 +55,16 @@ public class AbstractNamingClientProxyTest { * 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")); } /** @@ -72,7 +73,7 @@ public void testGetSecurityHeadersForAccessToken() { * @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..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 @@ -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"; @@ -67,8 +71,8 @@ public class NamingClientProxyDelegateTest { 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); @@ -79,13 +83,13 @@ public void setUp() throws NacosException, NoSuchFieldException, IllegalAccessEx 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(); @@ -99,7 +103,7 @@ public void testRegisterEphemeralServiceByGrpc() throws NacosException { } @Test - public void testBatchRegisterServiceByGrpc() throws NacosException { + void testBatchRegisterServiceByGrpc() throws NacosException { String serviceName = "service1"; String groupName = "group1"; Instance instance = new Instance(); @@ -114,7 +118,7 @@ public void testBatchRegisterServiceByGrpc() throws NacosException { } @Test - public void testBatchDeregisterServiceByGrpc() throws NacosException { + void testBatchDeregisterServiceByGrpc() throws NacosException { String serviceName = "service1"; String groupName = "group1"; List instanceList = new ArrayList<>(); @@ -127,7 +131,7 @@ public void testBatchDeregisterServiceByGrpc() throws NacosException { } @Test - public void testRegisterPersistentServiceByGrpc() throws NacosException { + void testRegisterPersistentServiceByGrpc() throws NacosException { String serviceName = "service1"; String groupName = "group1"; Instance instance = new Instance(); @@ -138,15 +142,14 @@ public 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 - public 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); @@ -167,7 +170,7 @@ public void testRegisterPersistentServiceByHttp() } @Test - public void testDeregisterEphemeralServiceGrpc() throws NacosException { + void testDeregisterEphemeralServiceGrpc() throws NacosException { String serviceName = "service1"; String groupName = "group1"; Instance instance = new Instance(); @@ -182,7 +185,7 @@ public void testDeregisterEphemeralServiceGrpc() throws NacosException { } @Test - public void testDeregisterPersistentServiceGrpc() throws NacosException { + void testDeregisterPersistentServiceGrpc() throws NacosException { String serviceName = "service1"; String groupName = "group1"; Instance instance = new Instance(); @@ -193,15 +196,14 @@ public 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 - public 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); @@ -221,19 +223,17 @@ public void testDeregisterPersistentServiceHttp() } @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"; @@ -242,38 +242,34 @@ public void testQueryInstancesOfService() throws NacosException { } @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; @@ -284,7 +280,7 @@ public void testGetServiceList() throws NacosException { } @Test - public void testSubscribe() throws NacosException { + void testSubscribe() throws NacosException { String serviceName = "service1"; String groupName = "group1"; String clusters = "cluster1"; @@ -295,14 +291,14 @@ 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"; @@ -311,23 +307,23 @@ public void testUnsubscribe() throws NacosException { } @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..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 @@ -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"; @@ -132,11 +135,8 @@ public class NamingGrpcClientProxyTest { 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(); @@ -171,15 +171,15 @@ public void setUp() throws NacosException, NoSuchFieldException, IllegalAccessEx 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) { @@ -191,7 +191,7 @@ public void testRegisterService() throws NacosException { } @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) { @@ -203,39 +203,41 @@ public void testRegisterPersistentService() throws NacosException { } @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()); + void testRegisterServiceThrowsNacosException() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { - throw ex; - } + 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()); + void testRegisterServiceThrowsException() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { - throw ex; - } + 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) { @@ -247,7 +249,7 @@ public void testDeregisterService() throws NacosException { } @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) { @@ -259,7 +261,7 @@ public void testDeregisterPersistentService() throws NacosException { } @Test - public void testDeregisterServiceForBatchRegistered() throws NacosException { + void testDeregisterServiceForBatchRegistered() throws NacosException { try { List instanceList = new ArrayList<>(); instance.setHealthy(true); @@ -286,7 +288,7 @@ public void testDeregisterServiceForBatchRegistered() throws NacosException { } @Test - public void testBatchRegisterService() throws NacosException { + void testBatchRegisterService() throws NacosException { List instanceList = new ArrayList<>(); instance.setHealthy(true); instanceList.add(instance); @@ -303,42 +305,50 @@ public void testBatchRegisterService() throws NacosException { })); } - @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); @@ -365,7 +375,7 @@ public void testBatchDeregisterService() throws NacosException { } @Test - public void testBatchDeregisterServiceWithOtherPortInstance() throws NacosException { + void testBatchDeregisterServiceWithOtherPortInstance() throws NacosException { try { List instanceList = new ArrayList<>(); instance.setHealthy(true); @@ -395,29 +405,29 @@ public void testBatchDeregisterServiceWithOtherPortInstance() throws NacosExcept } @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(); @@ -425,13 +435,13 @@ public void testCreateService() throws Exception { } @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(); @@ -439,7 +449,7 @@ public void testUpdateService() throws NacosException { } @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); @@ -486,16 +496,16 @@ public 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 - 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); @@ -506,53 +516,53 @@ public void testIsSubscribed() throws NacosException { } @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() { - 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)); + void testIsAbilitySupportedByServer1() { + 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 - public 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)); + void testIsAbilitySupportedByServer2() { + 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 - public 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)); + void testIsAbilitySupportedByServer3() { + 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 - public 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)); + void testIsAbilitySupportedByServer4() { + 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 - 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); @@ -566,14 +576,14 @@ public void testShutdownWithException() throws NoSuchFieldException, IllegalAcce } @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..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 @@ -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,14 @@ 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( - 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 23681502af4..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,20 +18,20 @@ 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; 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"; @@ -58,8 +58,8 @@ public class NamingGrpcRedoServiceTest { 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); @@ -68,56 +68,56 @@ public void setUp() throws Exception { 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); - + 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 - 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"); 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 - 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); @@ -133,7 +133,7 @@ public void testOnDisConnect() { } @Test - public void testCacheInstanceForRedo() { + void testCacheInstanceForRedo() { ConcurrentMap registeredInstances = getInstanceRedoDataMap(); assertTrue(registeredInstances.isEmpty()); Instance instance = new Instance(); @@ -149,7 +149,7 @@ public void testCacheInstanceForRedo() { } @Test - public void testCacheInstanceForRedoByBatchInstanceRedoData() { + void testCacheInstanceForRedoByBatchInstanceRedoData() { ConcurrentMap registeredInstances = getInstanceRedoDataMap(); assertTrue(registeredInstances.isEmpty()); Instance instance = new Instance(); @@ -167,7 +167,7 @@ public void testCacheInstanceForRedoByBatchInstanceRedoData() { } @Test - public void testInstanceRegistered() { + void testInstanceRegistered() { ConcurrentMap registeredInstances = getInstanceRedoDataMap(); redoService.cacheInstanceForRedo(SERVICE, GROUP, new Instance()); redoService.instanceRegistered(SERVICE, GROUP); @@ -176,7 +176,7 @@ public void testInstanceRegistered() { } @Test - public void testInstanceDeregister() { + void testInstanceDeregister() { ConcurrentMap registeredInstances = getInstanceRedoDataMap(); redoService.cacheInstanceForRedo(SERVICE, GROUP, new Instance()); redoService.instanceDeregister(SERVICE, GROUP); @@ -186,7 +186,7 @@ public void testInstanceDeregister() { } @Test - public void testInstanceDeregistered() { + void testInstanceDeregistered() { ConcurrentMap registeredInstances = getInstanceRedoDataMap(); redoService.cacheInstanceForRedo(SERVICE, GROUP, new Instance()); redoService.instanceDeregistered(SERVICE, GROUP); @@ -196,7 +196,7 @@ public void testInstanceDeregistered() { } @Test - public void testRemoveInstanceForRedo() { + void testRemoveInstanceForRedo() { ConcurrentMap registeredInstances = getInstanceRedoDataMap(); assertTrue(registeredInstances.isEmpty()); redoService.cacheInstanceForRedo(SERVICE, GROUP, new Instance()); @@ -207,7 +207,7 @@ public void testRemoveInstanceForRedo() { } @Test - public void testFindInstanceRedoData() { + void testFindInstanceRedoData() { redoService.cacheInstanceForRedo(SERVICE, GROUP, new Instance()); assertFalse(redoService.findInstanceRedoData().isEmpty()); redoService.instanceRegistered(SERVICE, GROUP); @@ -222,7 +222,7 @@ private ConcurrentMap getInstanceRedoDataMap() { } @Test - public void testCacheSubscriberForRedo() { + void testCacheSubscriberForRedo() { ConcurrentMap subscribes = getSubscriberRedoDataMap(); assertTrue(subscribes.isEmpty()); redoService.cacheSubscriberForRedo(SERVICE, GROUP, CLUSTER); @@ -236,7 +236,7 @@ public void testCacheSubscriberForRedo() { } @Test - public void testSubscriberRegistered() { + void testSubscriberRegistered() { ConcurrentMap subscribes = getSubscriberRedoDataMap(); redoService.cacheSubscriberForRedo(SERVICE, GROUP, CLUSTER); redoService.subscriberRegistered(SERVICE, GROUP, CLUSTER); @@ -245,7 +245,7 @@ public void testSubscriberRegistered() { } @Test - public void testSubscriberDeregister() { + void testSubscriberDeregister() { ConcurrentMap subscribes = getSubscriberRedoDataMap(); redoService.cacheSubscriberForRedo(SERVICE, GROUP, CLUSTER); redoService.subscriberDeregister(SERVICE, GROUP, CLUSTER); @@ -254,7 +254,7 @@ public void testSubscriberDeregister() { } @Test - public void testIsSubscriberRegistered() { + void testIsSubscriberRegistered() { assertFalse(redoService.isSubscriberRegistered(SERVICE, GROUP, CLUSTER)); redoService.cacheSubscriberForRedo(SERVICE, GROUP, CLUSTER); redoService.subscriberRegistered(SERVICE, GROUP, CLUSTER); @@ -262,7 +262,7 @@ public void testIsSubscriberRegistered() { } @Test - public void testRemoveSubscriberForRedo() { + void testRemoveSubscriberForRedo() { ConcurrentMap subscribes = getSubscriberRedoDataMap(); assertTrue(subscribes.isEmpty()); redoService.cacheSubscriberForRedo(SERVICE, GROUP, CLUSTER); @@ -273,7 +273,7 @@ public void testRemoveSubscriberForRedo() { } @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..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 @@ -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"; @@ -56,15 +60,15 @@ public class RedoScheduledTaskTest { 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(); @@ -72,9 +76,9 @@ public void testRunRedoRegisterInstance() throws NacosException { } @Test - public void testRunRedoRegisterBatchInstance() throws NacosException { - BatchInstanceRedoData redoData = BatchInstanceRedoData - .build(SERVICE, GROUP, Collections.singletonList(INSTANCE)); + void testRunRedoRegisterBatchInstance() throws NacosException { + BatchInstanceRedoData redoData = BatchInstanceRedoData.build(SERVICE, GROUP, + Collections.singletonList(INSTANCE)); redoData.setRegistered(false); redoData.setUnregistering(false); redoData.setExpectedRegistered(true); @@ -86,7 +90,7 @@ public void testRunRedoRegisterBatchInstance() throws NacosException { } @Test - public void testRunRedoDeregisterInstance() throws NacosException { + void testRunRedoDeregisterInstance() throws NacosException { Set mockData = generateMockInstanceData(true, true, false); when(redoService.findInstanceRedoData()).thenReturn(mockData); redoTask.run(); @@ -94,7 +98,7 @@ public void testRunRedoDeregisterInstance() throws NacosException { } @Test - public void testRunRedoRemoveInstanceRedoData() throws NacosException { + void testRunRedoRemoveInstanceRedoData() throws NacosException { Set mockData = generateMockInstanceData(false, true, false); when(redoService.findInstanceRedoData()).thenReturn(mockData); redoTask.run(); @@ -102,7 +106,7 @@ public void testRunRedoRemoveInstanceRedoData() throws NacosException { } @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); @@ -111,7 +115,7 @@ public void testRunRedoRegisterInstanceWithClientDisabled() throws NacosExceptio } @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); @@ -120,7 +124,7 @@ public void testRunRedoDeregisterInstanceWithClientDisabled() throws NacosExcept } @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); @@ -129,7 +133,7 @@ public void testRunRedoRegisterInstanceWithNacosException() throws NacosExceptio } @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); @@ -149,7 +153,7 @@ private Set generateMockInstanceData(boolean registered, boole } @Test - public void testRunRedoRegisterSubscriber() throws NacosException { + void testRunRedoRegisterSubscriber() throws NacosException { Set mockData = generateMockSubscriberData(false, false, true); when(redoService.findSubscriberRedoData()).thenReturn(mockData); redoTask.run(); @@ -157,7 +161,7 @@ public void testRunRedoRegisterSubscriber() throws NacosException { } @Test - public void testRunRedoDeregisterSubscriber() throws NacosException { + void testRunRedoDeregisterSubscriber() throws NacosException { Set mockData = generateMockSubscriberData(true, true, false); when(redoService.findSubscriberRedoData()).thenReturn(mockData); redoTask.run(); @@ -165,7 +169,7 @@ public void testRunRedoDeregisterSubscriber() throws NacosException { } @Test - public void testRunRedoRemoveSubscriberRedoData() throws NacosException { + void testRunRedoRemoveSubscriberRedoData() throws NacosException { Set mockData = generateMockSubscriberData(false, true, false); when(redoService.findSubscriberRedoData()).thenReturn(mockData); redoTask.run(); @@ -173,7 +177,7 @@ public void testRunRedoRemoveSubscriberRedoData() throws NacosException { } @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); @@ -182,7 +186,7 @@ public void testRunRedoRegisterSubscriberWithClientDisabled() throws NacosExcept } @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); @@ -191,7 +195,7 @@ public void testRunRedoDeRegisterSubscriberWithClientDisabled() throws NacosExce } @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); @@ -211,7 +215,7 @@ private Set generateMockSubscriberData(boolean registered, b } @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..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 @@ -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; -public class BatchInstanceRedoDataTest { +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..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 @@ -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; -public class InstanceRedoDataTest { +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..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 @@ -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(); @@ -70,7 +70,7 @@ public void testShutdown() throws NoSuchFieldException, IllegalAccessException, } @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..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 @@ -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; @@ -80,33 +80,33 @@ public class NamingHttpClientProxyTest { 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(); @@ -128,81 +128,88 @@ public void testRegisterService() throws Exception { 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()); + 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); - throw ex; - } + 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()); + 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); - throw ex; - } + 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(); @@ -225,7 +232,7 @@ public void testDeregisterService() throws Exception { } @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); @@ -237,7 +244,7 @@ public void testDeregisterServiceForEphemeral() throws Exception { } @Test - public void testUpdateInstance() throws Exception { + void testUpdateInstance() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -259,17 +266,17 @@ public void testUpdateInstance() throws Exception { } @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(); @@ -287,14 +294,14 @@ public 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 - public void testCreateService() throws Exception { + void testCreateService() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -309,12 +316,12 @@ public 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 - public void testDeleteService() throws Exception { + void testDeleteService() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -331,12 +338,12 @@ public 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 - public void testUpdateService() throws Exception { + void testUpdateService() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -353,13 +360,13 @@ public 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 - public void testServerHealthy() throws Exception { + void testServerHealthy() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -374,16 +381,16 @@ public 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()); - Assert.assertTrue(serverHealthy); + verify(nacosRestTemplate, times(1)).exchangeForm(endsWith("/operator/metrics"), any(), any(), any(), + eq(HttpMethod.GET), any()); + 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")); + 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); @@ -391,7 +398,7 @@ public void testServerHealthyForException() throws Exception { } @Test - public void testGetServiceList() throws Exception { + void testGetServiceList() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -407,15 +414,15 @@ public 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 - public void testGetServiceListWithLabelSelector() throws Exception { + void testGetServiceListWithLabelSelector() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -431,25 +438,27 @@ public 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(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"; @@ -460,12 +469,12 @@ public void testUnsubscribe() throws Exception { } @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); @@ -491,7 +500,7 @@ public void testReqApi() throws Exception { } @Test - public void testReqApi2() throws Exception { + void testReqApi2() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); @@ -517,7 +526,7 @@ public void testReqApi2() throws Exception { } @Test - public void testReqApi3() throws Exception { + void testReqApi3() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); @@ -544,36 +553,38 @@ public void testReqApi3() throws Exception { } @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); @@ -600,7 +611,7 @@ public void testCallServerFail304() throws Exception { } @Test - public void testGetNamespaceId() { + void testGetNamespaceId() { String namespaceId = "aaa"; final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props); NamingHttpClientProxy clientProxy = new NamingHttpClientProxy(namespaceId, proxy, mgr, nacosClientProperties); @@ -609,7 +620,7 @@ public void testGetNamespaceId() { } @Test - public void testSetServerPort() { + void testSetServerPort() { clientProxy.setServerPort(1234); assertEquals(1234, ReflectUtils.getFieldValue(clientProxy, "serverPort")); System.setProperty(SystemPropertyKeyConst.NAMING_SERVER_PORT, "1111"); @@ -617,20 +628,23 @@ public void testSetServerPort() { 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/selector/DefaultNamingSelectorTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/selector/DefaultNamingSelectorTest.java new file mode 100644 index 00000000000..03fad8f3c16 --- /dev/null +++ b/client/src/test/java/com/alibaba/nacos/client/naming/selector/DefaultNamingSelectorTest.java @@ -0,0 +1,69 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.client.naming.selector; + +import com.alibaba.nacos.api.naming.pojo.Instance; +import com.alibaba.nacos.api.naming.selector.NamingContext; +import com.alibaba.nacos.api.naming.selector.NamingResult; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class DefaultNamingSelectorTest { + + @Test + public void testSelect() { + DefaultNamingSelector namingSelector = new DefaultNamingSelector(Instance::isHealthy); + Random random = new Random(); + int total = random.nextInt(32) + 1; + int health = random.nextInt(total); + + NamingContext namingContext = getMockNamingContext(total, health); + NamingResult result = namingSelector.select(namingContext); + + assertEquals(health, result.getResult().size()); + result.getResult().forEach(ins -> assertTrue(ins.isHealthy())); + } + + private NamingContext getMockNamingContext(int total, int health) { + NamingContext namingContext = mock(NamingContext.class); + when(namingContext.getInstances()).thenReturn(getInstance(total, health)); + return namingContext; + } + + private List getInstance(int total, int health) { + List list = new ArrayList<>(total); + for (int i = 0; i < total; i++) { + Instance instance = new Instance(); + instance.setHealthy(false); + list.add(instance); + } + + for (int i = 0; i < health; i++) { + list.get(i).setHealthy(true); + } + + return list; + } +} diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/selector/NamingListenerInvokerTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/selector/NamingListenerInvokerTest.java new file mode 100644 index 00000000000..8a62a1ea815 --- /dev/null +++ b/client/src/test/java/com/alibaba/nacos/client/naming/selector/NamingListenerInvokerTest.java @@ -0,0 +1,76 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.client.naming.selector; + +import com.alibaba.nacos.api.naming.listener.AbstractEventListener; +import com.alibaba.nacos.api.naming.listener.EventListener; +import com.alibaba.nacos.api.naming.listener.NamingEvent; +import com.alibaba.nacos.client.naming.event.InstancesDiff; +import com.alibaba.nacos.client.naming.listener.AbstractNamingChangeListener; +import com.alibaba.nacos.client.naming.listener.NamingChangeEvent; +import org.junit.jupiter.api.Test; + +import java.util.Collections; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + +public class NamingListenerInvokerTest { + + @Test + public void testEventListener() { + EventListener listener = mock(EventListener.class); + NamingListenerInvoker listenerInvoker = new NamingListenerInvoker(listener); + NamingEvent event = new NamingEvent("serviceName", Collections.emptyList()); + listenerInvoker.invoke(event); + verify(listener).onEvent(event); + } + + @Test + public void testAbstractEventListener() { + AbstractEventListener listener = mock(AbstractEventListener.class); + NamingListenerInvoker listenerInvoker = new NamingListenerInvoker(listener); + NamingEvent event = new NamingEvent("serviceName", Collections.emptyList()); + listenerInvoker.invoke(event); + verify(listener).getExecutor(); + } + + @Test + public void testAbstractNamingChaneEventListener() { + AbstractNamingChangeListener listener = spy(AbstractNamingChangeListener.class); + NamingListenerInvoker listenerInvoker = new NamingListenerInvoker(listener); + NamingChangeEvent event = new NamingChangeEvent("serviceName", Collections.emptyList(), new InstancesDiff()); + listenerInvoker.invoke(event); + verify(listener).onChange(event); + } + + @Test + public void testEquals() { + EventListener listener1 = mock(EventListener.class); + EventListener listener2 = mock(EventListener.class); + NamingListenerInvoker invoker1 = new NamingListenerInvoker(listener1); + NamingListenerInvoker invoker2 = new NamingListenerInvoker(listener1); + NamingListenerInvoker invoker3 = new NamingListenerInvoker(listener2); + assertEquals(invoker1.hashCode(), invoker2.hashCode()); + assertEquals(invoker1, invoker2); + assertNotEquals(invoker1.hashCode(), invoker3.hashCode()); + assertNotEquals(invoker1, invoker3); + } +} diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/selector/NamingSelectorFactoryTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/selector/NamingSelectorFactoryTest.java new file mode 100644 index 00000000000..3c3aa27ad95 --- /dev/null +++ b/client/src/test/java/com/alibaba/nacos/client/naming/selector/NamingSelectorFactoryTest.java @@ -0,0 +1,178 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.client.naming.selector; + +import com.alibaba.nacos.api.naming.pojo.Instance; +import com.alibaba.nacos.api.naming.selector.NamingContext; +import com.alibaba.nacos.api.naming.selector.NamingResult; +import com.alibaba.nacos.api.naming.selector.NamingSelector; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class NamingSelectorFactoryTest { + + @Test + public void testNewClusterSelector1() { + Instance ins1 = new Instance(); + ins1.setClusterName("a"); + Instance ins2 = new Instance(); + ins2.setClusterName("b"); + Instance ins3 = new Instance(); + ins3.setClusterName("c"); + + NamingContext namingContext = mock(NamingContext.class); + when(namingContext.getInstances()).thenReturn(Arrays.asList(ins1, ins2, ins3)); + + NamingSelector namingSelector1 = NamingSelectorFactory.newClusterSelector(Collections.singletonList("a")); + NamingResult result1 = namingSelector1.select(namingContext); + assertEquals("a", result1.getResult().get(0).getClusterName()); + + NamingSelector namingSelector2 = NamingSelectorFactory.newClusterSelector(Collections.emptyList()); + NamingResult result2 = namingSelector2.select(namingContext); + assertEquals(3, result2.getResult().size()); + } + + @Test + public void testNewClusterSelector2() { + NamingSelector namingSelector1 = NamingSelectorFactory.newClusterSelector(Arrays.asList("a", "b", "c")); + NamingSelector namingSelector2 = NamingSelectorFactory.newClusterSelector(Arrays.asList("c", "b", "a")); + NamingSelector namingSelector3 = NamingSelectorFactory.newClusterSelector(Arrays.asList("a", "b", "c", "c")); + NamingSelector namingSelector4 = NamingSelectorFactory.newClusterSelector(Arrays.asList("d", "e")); + + assertEquals(namingSelector1, namingSelector2); + assertEquals(namingSelector1, namingSelector3); + assertNotEquals(namingSelector1, namingSelector4); + } + + @Test + public void testNewIpSelector() { + Instance ins1 = new Instance(); + ins1.setIp("172.18.137.120"); + Instance ins2 = new Instance(); + ins2.setIp("172.18.137.121"); + Instance ins3 = new Instance(); + ins3.setIp("172.18.136.111"); + + NamingContext namingContext = mock(NamingContext.class); + when(namingContext.getInstances()).thenReturn(Arrays.asList(ins1, ins2, ins3)); + + NamingSelector ipSelector = NamingSelectorFactory.newIpSelector("^172\\.18\\.137.*"); + NamingResult result = ipSelector.select(namingContext); + List list = result.getResult(); + + assertEquals(2, list.size()); + assertEquals(ins1.getIp(), list.get(0).getIp()); + assertEquals(ins2.getIp(), list.get(1).getIp()); + } + + @Test + public void testNewMetadataSelector() { + Instance ins1 = new Instance(); + ins1.addMetadata("a", "1"); + ins1.addMetadata("b", "2"); + Instance ins2 = new Instance(); + ins2.addMetadata("a", "1"); + Instance ins3 = new Instance(); + ins3.addMetadata("b", "2"); + + NamingContext namingContext = mock(NamingContext.class); + when(namingContext.getInstances()).thenReturn(Arrays.asList(ins1, ins2, ins3)); + + NamingSelector metadataSelector = NamingSelectorFactory.newMetadataSelector(new HashMap() { + { + put("a", "1"); + put("b", "2"); + } + }); + List result = metadataSelector.select(namingContext).getResult(); + + assertEquals(1, result.size()); + assertEquals(ins1, result.get(0)); + } + + @Test + public void testNewMetadataSelector2() { + Instance ins1 = new Instance(); + ins1.addMetadata("a", "1"); + ins1.addMetadata("c", "3"); + Instance ins2 = new Instance(); + ins2.addMetadata("b", "2"); + Instance ins3 = new Instance(); + ins3.addMetadata("c", "3"); + + NamingContext namingContext = mock(NamingContext.class); + when(namingContext.getInstances()).thenReturn(Arrays.asList(ins1, ins2, ins3)); + + NamingSelector metadataSelector = NamingSelectorFactory.newMetadataSelector(new HashMap() { + { + put("a", "1"); + put("b", "2"); + } + }, true); + List result = metadataSelector.select(namingContext).getResult(); + + assertEquals(2, result.size()); + assertEquals(ins1, result.get(0)); + assertEquals(ins2, result.get(1)); + } + + @Test + public void testHealthSelector() { + Instance ins1 = new Instance(); + Instance ins2 = new Instance(); + Instance ins3 = new Instance(); + ins3.setHealthy(false); + + NamingContext namingContext = mock(NamingContext.class); + when(namingContext.getInstances()).thenReturn(Arrays.asList(ins1, ins2, ins3)); + + List result = NamingSelectorFactory.HEALTHY_SELECTOR.select(namingContext).getResult(); + + assertEquals(2, result.size()); + assertTrue(result.contains(ins1)); + assertTrue(result.contains(ins2)); + assertTrue(result.get(0).isHealthy()); + assertTrue(result.get(1).isHealthy()); + } + + @Test + public void testEmptySelector() { + Instance ins1 = new Instance(); + Instance ins2 = new Instance(); + Instance ins3 = new Instance(); + + NamingContext namingContext = mock(NamingContext.class); + when(namingContext.getInstances()).thenReturn(Arrays.asList(ins1, ins2, ins3)); + + List result = NamingSelectorFactory.EMPTY_SELECTOR.select(namingContext).getResult(); + + assertEquals(3, result.size()); + assertTrue(result.contains(ins1)); + assertTrue(result.contains(ins2)); + assertTrue(result.contains(ins3)); + } +} diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/selector/NamingSelectorWrapperTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/selector/NamingSelectorWrapperTest.java new file mode 100644 index 00000000000..2d941617ab9 --- /dev/null +++ b/client/src/test/java/com/alibaba/nacos/client/naming/selector/NamingSelectorWrapperTest.java @@ -0,0 +1,103 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.client.naming.selector; + +import com.alibaba.nacos.api.naming.listener.EventListener; +import com.alibaba.nacos.api.naming.pojo.Instance; +import com.alibaba.nacos.api.naming.selector.NamingSelector; +import com.alibaba.nacos.client.naming.event.InstancesChangeEvent; +import com.alibaba.nacos.client.naming.event.InstancesDiff; +import com.alibaba.nacos.client.naming.listener.NamingChangeEvent; +import org.junit.jupiter.api.Test; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; + +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.argThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +public class NamingSelectorWrapperTest { + + @Test + public void testEquals() { + EventListener listener = mock(EventListener.class); + NamingSelector selector1 = mock(NamingSelector.class); + NamingSelector selector2 = mock(NamingSelector.class); + NamingSelectorWrapper sw1 = new NamingSelectorWrapper(selector1, listener); + NamingSelectorWrapper sw2 = new NamingSelectorWrapper(selector2, listener); + NamingSelectorWrapper sw3 = new NamingSelectorWrapper(selector1, listener); + + assertNotEquals(sw1.hashCode(), sw2.hashCode()); + assertEquals(sw1.hashCode(), sw3.hashCode()); + assertNotEquals(sw1, sw2); + assertEquals(sw1, sw3); + + Set set = new HashSet<>(); + set.add(sw1); + assertFalse(set.contains(sw2)); + assertTrue(set.contains(sw3)); + assertTrue(set.add(sw2)); + assertFalse(set.add(sw3)); + assertTrue(set.remove(sw3)); + + assertEquals(sw1, new NamingSelectorWrapper("a", "b", "c", selector1, listener)); + } + + @Test + public void testSelectable() { + NamingSelectorWrapper selectorWrapper = new NamingSelectorWrapper(null, null); + assertFalse(selectorWrapper.isSelectable(null)); + InstancesChangeEvent event1 = new InstancesChangeEvent(null, null, null, null, null, null); + assertFalse(selectorWrapper.isSelectable(event1)); + InstancesChangeEvent event2 = new InstancesChangeEvent(null, null, null, null, null, new InstancesDiff()); + assertFalse(selectorWrapper.isSelectable(event2)); + InstancesChangeEvent event3 = new InstancesChangeEvent(null, null, null, null, Collections.emptyList(), null); + assertFalse(selectorWrapper.isSelectable(event3)); + InstancesChangeEvent event4 = new InstancesChangeEvent(null, null, null, null, Collections.emptyList(), + new InstancesDiff()); + assertTrue(selectorWrapper.isSelectable(event4)); + } + + @Test + public void testCallable() { + NamingSelectorWrapper selectorWrapper = new NamingSelectorWrapper(null, null); + InstancesDiff instancesDiff = new InstancesDiff(null, Collections.singletonList(new Instance()), null); + NamingChangeEvent changeEvent = new NamingChangeEvent("serviceName", Collections.emptyList(), instancesDiff); + assertTrue(selectorWrapper.isCallable(changeEvent)); + changeEvent.getRemovedInstances().clear(); + assertFalse(selectorWrapper.isCallable(changeEvent)); + } + + @Test + public void testNotifyListener() { + EventListener listener = mock(EventListener.class); + NamingSelectorWrapper selectorWrapper = new NamingSelectorWrapper( + new DefaultNamingSelector(Instance::isHealthy), listener); + InstancesDiff diff = new InstancesDiff(null, Collections.singletonList(new Instance()), null); + InstancesChangeEvent event = new InstancesChangeEvent(null, "serviceName", "groupName", "clusters", + Collections.emptyList(), diff); + selectorWrapper.notifyListener(event); + verify(listener).onEvent(argThat(Objects::nonNull)); + } +} 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..76eb3685494 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,28 +18,36 @@ 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 { +class CacheDirUtilTest { - @After - public void tearDown() throws Exception { + @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 testInitCacheDirWithDefaultRootAndWithoutCache2() { + NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); + properties.setProperty("user.home", "/home/test"); + String actual = CacheDirUtil.initCacheDir("test", properties); + assertEquals("/home/test/nacos/naming/test", actual); + } + + @Test + void testInitCacheDirWithDefaultRootAndWithCache() { System.setProperty("user.home", "/home/admin"); NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); properties.setProperty(PropertyKeyConst.NAMING_CACHE_REGISTRY_DIR, "custom"); @@ -48,18 +56,26 @@ public void testInitCacheDirWithDefaultRootAndWithCache() { } @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 testInitCacheDirWithJmSnapshotPathRootAndWithoutCache2() { + NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); + properties.setProperty("JM.SNAPSHOT.PATH", "/home/custom/snapshot"); + String actual = CacheDirUtil.initCacheDir("test", properties); + assertEquals("/home/custom/snapshot/nacos/naming/test", actual); + } + + @Test + void testInitCacheDirWithJmSnapshotPathRootAndWithCache() { System.setProperty("user.home", "/home/snapshot"); NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); properties.setProperty(PropertyKeyConst.NAMING_CACHE_REGISTRY_DIR, "custom"); String actual = CacheDirUtil.initCacheDir("test", properties); assertEquals("/home/snapshot/nacos/custom/naming/test", actual); } -} \ No newline at end of file +} 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..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 @@ -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,16 +25,17 @@ 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; -public class ChooserTest { +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); @@ -42,14 +43,14 @@ public void testChooser() { } @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); @@ -59,7 +60,7 @@ public void testChooserRandomForOneSizeList() { } @Test - public void testChooserRandom() { + void testChooserRandom() { List> list = new LinkedList<>(); list.add(new Pair<>("test", 1)); list.add(new Pair<>("test2", 1)); @@ -70,7 +71,7 @@ public void testChooserRandom() { } @Test - public void testOnlyOneInstanceWeightIsNotZero() { + void testOnlyOneInstanceWeightIsNotZero() { // If there is only one instance whose weight is not zero, it will be selected List hosts = getOneInstanceNotZeroList(); @@ -79,7 +80,7 @@ public void testOnlyOneInstanceWeightIsNotZero() { } @Test - public void testInstanceWeightAllZero() { + void testInstanceWeightAllZero() { // Throw an IllegalStateException when all instances have a weight of zero. List hosts = getInstanceWeightAllZero(); @@ -90,16 +91,18 @@ public void testInstanceWeightAllZero() { } } - @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()); @@ -112,43 +115,43 @@ public void testRefresh() { } @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..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 @@ -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() { - List subtract = (List) CollectionUtils - .subtract(Arrays.asList("a", "b"), Arrays.asList("b", "c")); - Assert.assertEquals(1, subtract.size()); - Assert.assertEquals("a", subtract.get(0)); + void testSubtract() { + List subtract = (List) CollectionUtils.subtract(Arrays.asList("a", "b"), + Arrays.asList("b", "c")); + 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"); + 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"); - 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)); + 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..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 @@ -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..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 @@ -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..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 @@ -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 { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class InitUtilsTest { - @After - public void tearDown() { + @AfterEach + void tearDown() { System.clearProperty(SystemPropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING); System.clearProperty(SystemPropertyKeyConst.ANS_NAMESPACE); System.clearProperty(PropertyKeyConst.NAMESPACE); @@ -42,125 +43,125 @@ public void tearDown() { * 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..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 @@ -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; -public class NamingHttpUtilTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +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..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 @@ -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; -public class PairTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +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..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 @@ -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}"); @@ -64,7 +69,7 @@ public void setUp() throws Exception { } @Test - public void testLoginClientAuthService() throws Exception { + void testLoginClientAuthService() throws Exception { Properties properties = new Properties(); properties.setProperty(PropertyKeyConst.USERNAME, "aaa"); properties.setProperty(PropertyKeyConst.PASSWORD, "123456"); @@ -73,7 +78,7 @@ public void testLoginClientAuthService() throws Exception { } @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/selector/SelectorManagerTest.java b/client/src/test/java/com/alibaba/nacos/client/selector/SelectorManagerTest.java new file mode 100644 index 00000000000..0d68977111a --- /dev/null +++ b/client/src/test/java/com/alibaba/nacos/client/selector/SelectorManagerTest.java @@ -0,0 +1,83 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.client.selector; + +import com.alibaba.nacos.client.naming.selector.NamingSelectorWrapper; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; + +public class SelectorManagerTest { + + @Test + public void testCurd() { + SelectorManager selectorManager = new SelectorManager<>(); + String subId = "subId"; + NamingSelectorWrapper sw = mock(NamingSelectorWrapper.class); + selectorManager.addSelectorWrapper(subId, sw); + assertTrue(selectorManager.getSelectorWrappers(subId).contains(sw)); + selectorManager.removeSelectorWrapper(subId, sw); + assertTrue(selectorManager.getSelectorWrappers(subId).isEmpty()); + } + + @Test + public void testSubInfo() { + SelectorManager selectorManager = new SelectorManager<>(); + List list = new ArrayList<>(); + for (int i = 0; i < 64; i++) { + list.add(generateRandomString(2, 32)); + } + + for (String subId : list) { + selectorManager.addSelectorWrapper(subId, mock(NamingSelectorWrapper.class)); + assertTrue(selectorManager.isSubscribed(subId)); + } + + Set subsSet = selectorManager.getSubscriptions(); + for (String subId : subsSet) { + assertTrue(list.contains(subId)); + } + + for (String subId : list) { + selectorManager.removeSubscription(subId); + assertFalse(selectorManager.isSubscribed(subId)); + } + } + + private static String generateRandomString(int minLength, int maxLength) { + String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + + Random random = new Random(); + int length = random.nextInt(maxLength - minLength + 1) + minLength; + StringBuilder sb = new StringBuilder(); + + for (int i = 0; i < length; i++) { + int index = random.nextInt(characters.length()); + char randomChar = characters.charAt(index); + sb.append(randomChar); + } + + return sb.toString(); + } +} 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..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 @@ -19,20 +19,20 @@ 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 { +class AppNameUtilsTest { - @Before - public void setUp() throws Exception { + @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"); @@ -40,34 +40,34 @@ public void tearDown() throws Exception { } @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..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 @@ -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..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 @@ -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..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 @@ -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..5f96fcb9734 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 @@ -20,19 +20,22 @@ import com.alibaba.nacos.api.PropertyKeyConst; import com.alibaba.nacos.client.env.NacosClientProperties; +import com.alibaba.nacos.client.env.SourceType; 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; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ParamUtilTest { +class ParamUtilTest { private String defaultAppKey; @@ -48,8 +51,8 @@ public class ParamUtilTest { private String defaultNodesPath; - @Before - public void before() { + @BeforeEach + void before() { defaultAppKey = ""; defaultAppName = "unknown"; defaultContextPath = "nacos"; @@ -59,8 +62,8 @@ public void before() { defaultNodesPath = "serverlist"; } - @After - public void after() { + @AfterEach + void after() { ParamUtil.setAppKey(defaultAppKey); ParamUtil.setAppName(defaultAppName); ParamUtil.setDefaultContextPath(defaultContextPath); @@ -74,7 +77,7 @@ public void after() { } @Test - public void testGetAppKey() { + void testGetAppKey() { String defaultVal = ParamUtil.getAppKey(); assertEquals(defaultAppKey, defaultVal); @@ -84,7 +87,7 @@ public void testGetAppKey() { } @Test - public void testGetAppName() { + void testGetAppName() { String defaultVal = ParamUtil.getAppName(); assertEquals(defaultAppName, defaultVal); @@ -94,7 +97,7 @@ public void testGetAppName() { } @Test - public void testGetDefaultContextPath() { + void testGetDefaultContextPath() { String defaultVal = ParamUtil.getDefaultContextPath(); assertEquals(defaultContextPath, defaultVal); @@ -104,7 +107,7 @@ public void testGetDefaultContextPath() { } @Test - public void testGetClientVersion() { + void testGetClientVersion() { String defaultVal = ParamUtil.getClientVersion(); assertEquals(defaultVersion, defaultVal); @@ -114,7 +117,7 @@ public void testGetClientVersion() { } @Test - public void testSetConnectTimeout() { + void testSetConnectTimeout() { int defaultVal = ParamUtil.getConnectTimeout(); assertEquals(defaultConnectTimeout, defaultVal); @@ -124,7 +127,7 @@ public void testSetConnectTimeout() { } @Test - public void testGetPerTaskConfigSize() { + void testGetPerTaskConfigSize() { double defaultVal = ParamUtil.getPerTaskConfigSize(); assertEquals(defaultPerTaskConfigSize, defaultVal, 0.01); @@ -134,13 +137,13 @@ public void testGetPerTaskConfigSize() { } @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); @@ -150,7 +153,7 @@ public void testGetDefaultNodesPath() { } @Test - public void testParseNamespace() { + void testParseNamespace() { String expect = "test"; Properties properties = new Properties(); properties.setProperty(PropertyKeyConst.NAMESPACE, expect); @@ -161,50 +164,54 @@ public void testParseNamespace() { } @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); @@ -215,8 +222,34 @@ public void testSimplyEnvNameIfOverLimit() { assertEquals(expect, actual); } - @Test public void testSimplyEnvNameNotOverLimit() { + @Test + void testSimplyEnvNameNotOverLimit() { String expect = "test"; assertEquals(expect, ParamUtil.simplyEnvNameIfOverLimit(expect)); } + + @Test + void testGetInputParametersWithFullMode() { + Properties properties = new Properties(); + properties.setProperty("testKey", "testValue"); + properties.setProperty(PropertyKeyConst.LOG_ALL_PROPERTIES, "true"); + NacosClientProperties clientProperties = NacosClientProperties.PROTOTYPE.derive(properties); + String actual = ParamUtil.getInputParameters(clientProperties.asProperties()); + assertTrue(actual.startsWith("Log nacos client init properties with Full mode, This mode is only used for debugging and troubleshooting.")); + assertTrue(actual.contains("\ttestKey=testValue\n")); + Properties envProperties = clientProperties.getProperties(SourceType.ENV); + String envCaseKey = envProperties.stringPropertyNames().iterator().next(); + String envCaseValue = envProperties.getProperty(envCaseKey); + assertTrue(actual.contains(String.format("\t%s=%s\n", envCaseKey, envCaseValue))); + } + + @Test + void testGetInputParameters() { + Properties properties = new Properties(); + properties.setProperty("testKey", "testValue"); + properties.setProperty(PropertyKeyConst.SERVER_ADDR, "localhost:8848"); + NacosClientProperties clientProperties = NacosClientProperties.PROTOTYPE.derive(properties); + String actual = ParamUtil.getInputParameters(clientProperties.asProperties()); + assertEquals("Nacos client key init properties: \n\tserverAddr=localhost:8848\n", actual); + } } \ No newline at end of file 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..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 @@ -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..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 @@ -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,15 +27,15 @@ 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; -public class StringUtilsTest { +class StringUtilsTest { @Test - public void testisNotBlank() { + void testisNotBlank() { assertTrue(isNotBlank("foo")); assertFalse(isNotBlank(" ")); @@ -43,20 +43,20 @@ public void testisNotBlank() { } @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")); @@ -65,7 +65,7 @@ public void testEquals() { } @Test - public void testSubstringBetween() { + void testSubstringBetween() { assertNull(substringBetween(null, null, null)); assertNull(substringBetween("", "foo", "")); assertNull(substringBetween("foo", "bar", "baz")); @@ -74,7 +74,7 @@ public void testSubstringBetween() { } @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..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 @@ -18,21 +18,21 @@ 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); @@ -40,7 +40,7 @@ public void testStringNotEmptyAndThenExecuteSuccess() { } @Test - public void testStringNotEmptyAndThenExecuteFail() { + void testStringNotEmptyAndThenExecuteFail() { String word = ""; Runnable task = Mockito.mock(Runnable.class); TemplateUtils.stringNotEmptyAndThenExecute(word, task); @@ -48,7 +48,7 @@ public void testStringNotEmptyAndThenExecuteFail() { } @Test - public void testStringNotEmptyAndThenExecuteException() { + void testStringNotEmptyAndThenExecuteException() { String word = "run"; Runnable task = Mockito.mock(Runnable.class); doThrow(new RuntimeException("test")).when(task).run(); @@ -58,22 +58,22 @@ public void testStringNotEmptyAndThenExecuteException() { } @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); @@ -81,22 +81,22 @@ public void testStringEmptyAndThenExecuteException() throws Exception { } @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..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 @@ -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 { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class TenantUtilTest { - @After - public void tearDown() { + @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..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 @@ -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"; @@ -40,39 +41,45 @@ public void testContextPathLegal() { 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(); - } + }); } } diff --git a/cmdb/pom.xml b/cmdb/pom.xml index 4aa45d2b099..3a0cda7cedf 100644 --- a/cmdb/pom.xml +++ b/cmdb/pom.xml @@ -52,11 +52,6 @@ org.springframework.boot spring-boot-starter-web - - org.springframework.boot - spring-boot-starter-test - test - diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/PersistentConsistencyService.java b/common/src/main/java/com/alibaba/nacos/common/constant/Symbols.java similarity index 50% rename from naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/PersistentConsistencyService.java rename to common/src/main/java/com/alibaba/nacos/common/constant/Symbols.java index 67a63370201..deee19685ba 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/PersistentConsistencyService.java +++ b/common/src/main/java/com/alibaba/nacos/common/constant/Symbols.java @@ -14,22 +14,18 @@ * limitations under the License. */ -package com.alibaba.nacos.naming.consistency.persistent; - -import com.alibaba.nacos.naming.consistency.ConsistencyService; +package com.alibaba.nacos.common.constant; /** - * A consistency service that guarantee CP consistency for the published data. - * - *

    CP consistency is hereby defined as follows: - * - *

    Once the writing operation returned client a success, the data within the operation is guaranteed to be - * successfully written to the cluster. And the data should be consistent between servers after some time without any - * outside interfere. + * Symbols. * - * @author nkorange - * @since 1.0.0 + * @author haiqi.wang + * @date 2024/08/13 */ -public interface PersistentConsistencyService extends ConsistencyService { +public final class Symbols { -} + /** + * Comma. + */ + public static final String COMMA = ","; +} \ No newline at end of file diff --git a/common/src/main/java/com/alibaba/nacos/common/paramcheck/DefaultParamChecker.java b/common/src/main/java/com/alibaba/nacos/common/paramcheck/DefaultParamChecker.java index 69ca16048b2..d720828558f 100644 --- a/common/src/main/java/com/alibaba/nacos/common/paramcheck/DefaultParamChecker.java +++ b/common/src/main/java/com/alibaba/nacos/common/paramcheck/DefaultParamChecker.java @@ -16,6 +16,8 @@ package com.alibaba.nacos.common.paramcheck; +import com.alibaba.nacos.common.utils.NumberUtils; +import com.alibaba.nacos.common.utils.PropertyUtils; import com.alibaba.nacos.common.utils.StringUtils; import java.util.List; @@ -45,6 +47,10 @@ public class DefaultParamChecker extends AbstractParamChecker { private static final String CHECKER_TYPE = "default"; + private static final String MAX_METADATA_LENGTH_PROP_NAME = "nacos.naming.service.metadata.length"; + + private static final String MAX_METADATA_LENGTH_ENV_NAME = "NACOS_NAMING_SERVICE_METADATA_LENGTH"; + @Override public String getCheckerType() { return CHECKER_TYPE; @@ -71,6 +77,7 @@ public ParamCheckResponse checkParamInfoList(List paramInfos) { public void initParamCheckRule() { this.paramCheckRule = new ParamCheckRule(); initFormatPattern(); + replaceParamCheckRuleByEnv(); } private void initFormatPattern() { @@ -83,6 +90,16 @@ private void initFormatPattern() { this.ipPattern = Pattern.compile(this.paramCheckRule.ipPatternString); } + /** + * if environment variables exists, it will be replaced. + */ + private void replaceParamCheckRuleByEnv() { + String maxMetadataLength = PropertyUtils.getProperty(MAX_METADATA_LENGTH_PROP_NAME, MAX_METADATA_LENGTH_ENV_NAME); + if (StringUtils.isNotBlank(maxMetadataLength)) { + this.paramCheckRule.maxMetadataLength = NumberUtils.toInt(maxMetadataLength); + } + } + /** * Check param info format. * @@ -207,8 +224,8 @@ public ParamCheckResponse checkDataIdFormat(String dataId) { } if (dataId.length() > paramCheckRule.maxDataIdLength) { paramCheckResponse.setSuccess(false); - paramCheckResponse.setMessage(String.format("Param 'dataId' is illegal, the param length should not exceed %d.", - paramCheckRule.maxDataIdLength)); + paramCheckResponse.setMessage( + String.format("Param 'dataId' is illegal, the param length should not exceed %d.", paramCheckRule.maxDataIdLength)); return paramCheckResponse; } if (!dataIdPattern.matcher(dataId).matches()) { @@ -234,8 +251,8 @@ public ParamCheckResponse checkServiceNameFormat(String serviceName) { } if (serviceName.length() > paramCheckRule.maxServiceNameLength) { paramCheckResponse.setSuccess(false); - paramCheckResponse.setMessage(String.format("Param 'serviceName' is illegal, the param length should not exceed %d.", - paramCheckRule.maxServiceNameLength)); + paramCheckResponse.setMessage( + String.format("Param 'serviceName' is illegal, the param length should not exceed %d.", paramCheckRule.maxServiceNameLength)); return paramCheckResponse; } if (!serviceNamePattern.matcher(serviceName).matches()) { @@ -261,8 +278,8 @@ public ParamCheckResponse checkGroupFormat(String group) { } if (group.length() > paramCheckRule.maxGroupLength) { paramCheckResponse.setSuccess(false); - paramCheckResponse.setMessage(String.format("Param 'group' is illegal, the param length should not exceed %d.", - paramCheckRule.maxGroupLength)); + paramCheckResponse.setMessage( + String.format("Param 'group' is illegal, the param length should not exceed %d.", paramCheckRule.maxGroupLength)); return paramCheckResponse; } if (!groupPattern.matcher(group).matches()) { @@ -312,8 +329,8 @@ public ParamCheckResponse checkSingleClusterFormat(String cluster) { if (cluster.length() > paramCheckRule.maxClusterLength) { paramCheckResponse.setSuccess(false); - paramCheckResponse.setMessage(String.format("Param 'cluster' is illegal, the param length should not exceed %d.", - paramCheckRule.maxClusterLength)); + paramCheckResponse.setMessage( + String.format("Param 'cluster' is illegal, the param length should not exceed %d.", paramCheckRule.maxClusterLength)); return paramCheckResponse; } if (!clusterPattern.matcher(cluster).matches()) { @@ -339,8 +356,7 @@ public ParamCheckResponse checkIpFormat(String ip) { } if (ip.length() > paramCheckRule.maxIpLength) { paramCheckResponse.setSuccess(false); - paramCheckResponse.setMessage(String.format("Param 'ip' is illegal, the param length should not exceed %d.", - paramCheckRule.maxIpLength)); + paramCheckResponse.setMessage(String.format("Param 'ip' is illegal, the param length should not exceed %d.", paramCheckRule.maxIpLength)); return paramCheckResponse; } if (!ipPattern.matcher(ip).matches()) { @@ -369,14 +385,14 @@ public ParamCheckResponse checkPortFormat(String port) { portInt = Integer.parseInt(port); } catch (Exception e) { paramCheckResponse.setSuccess(false); - paramCheckResponse.setMessage(String.format("Param 'port' is illegal, the value should be between %d and %d.", - paramCheckRule.minPort, paramCheckRule.maxPort)); + paramCheckResponse.setMessage( + String.format("Param 'port' is illegal, the value should be between %d and %d.", paramCheckRule.minPort, paramCheckRule.maxPort)); return paramCheckResponse; } if (portInt > paramCheckRule.maxPort || portInt < paramCheckRule.minPort) { paramCheckResponse.setSuccess(false); - paramCheckResponse.setMessage(String.format("Param 'port' is illegal, the value should be between %d and %d.", - paramCheckRule.minPort, paramCheckRule.maxPort)); + paramCheckResponse.setMessage( + String.format("Param 'port' is illegal, the value should be between %d and %d.", paramCheckRule.minPort, paramCheckRule.maxPort)); return paramCheckResponse; } paramCheckResponse.setSuccess(true); @@ -406,8 +422,8 @@ public ParamCheckResponse checkMetadataFormat(Map metadata) { } if (totalLength > paramCheckRule.maxMetadataLength) { paramCheckResponse.setSuccess(false); - paramCheckResponse.setMessage(String.format("Param 'Metadata' is illegal, the param length should not exceed %d.", - paramCheckRule.maxMetadataLength)); + paramCheckResponse.setMessage( + String.format("Param 'Metadata' is illegal, the param length should not exceed %d.", paramCheckRule.maxMetadataLength)); return paramCheckResponse; } paramCheckResponse.setSuccess(true); diff --git a/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClient.java b/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClient.java index 53e36174fe7..b9065ef5391 100644 --- a/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClient.java +++ b/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClient.java @@ -529,8 +529,9 @@ protected void reconnect(final ServerInfo recommendServerInfo, boolean onRequest lastException = null; - } catch (Exception e) { - lastException = e; + } catch (Throwable throwable) { + LoggerUtils.printIfErrorEnabled(LOGGER, "Fail to connect server, error = {}", throwable.getMessage()); + lastException = new Exception(throwable); } finally { recommendServer.set(null); } diff --git a/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClientFactory.java b/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClientFactory.java index dec351ba387..92f02ef3af5 100644 --- a/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClientFactory.java +++ b/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClientFactory.java @@ -121,30 +121,41 @@ public static RpcClient createClient(String clientName, ConnectionType connectio } /** - * create a rpc client. + * Creates an RPC client for cluster communication with default thread pool settings. * - * @param clientName client name. - * @param connectionType client type. - * @return rpc client. + * @param clientName The name of the client. + * @param connectionType The type of client connection. + * @param labels Additional labels for RPC-related attributes. + * @return An RPC client for cluster communication. */ public static RpcClient createClusterClient(String clientName, ConnectionType connectionType, Map labels) { return createClusterClient(clientName, connectionType, null, null, labels); } + /** + * Creates an RPC client for cluster communication with TLS configuration. + * + * @param clientName The name of the client. + * @param connectionType The type of client connection. + * @param labels Additional labels for RPC-related attributes. + * @param tlsConfig TLS configuration for secure communication. + * @return An RPC client for cluster communication with TLS configuration. + */ public static RpcClient createClusterClient(String clientName, ConnectionType connectionType, Map labels, RpcClientTlsConfig tlsConfig) { return createClusterClient(clientName, connectionType, null, null, labels, tlsConfig); } /** - * create a rpc client. + * Creates an RPC client for cluster communication with custom thread pool settings. * - * @param clientName client name. - * @param connectionType client type. - * @param threadPoolCoreSize grpc thread pool core size - * @param threadPoolMaxSize grpc thread pool max size - * @return rpc client. + * @param clientName The name of the client. + * @param connectionType The type of client connection. + * @param threadPoolCoreSize The core size of the gRPC thread pool. + * @param threadPoolMaxSize The maximum size of the gRPC thread pool. + * @param labels Additional labels for RPC-related attributes. + * @return An RPC client for cluster communication with custom thread pool settings. */ public static RpcClient createClusterClient(String clientName, ConnectionType connectionType, Integer threadPoolCoreSize, Integer threadPoolMaxSize, Map labels) { @@ -162,7 +173,6 @@ public static RpcClient createClusterClient(String clientName, ConnectionType co * @param tlsConfig tlsConfig. * @return */ - public static RpcClient createClusterClient(String clientName, ConnectionType connectionType, Integer threadPoolCoreSize, Integer threadPoolMaxSize, Map labels, RpcClientTlsConfig tlsConfig) { diff --git a/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClientTlsConfig.java b/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClientTlsConfig.java index 61b847e98ac..de5c2e5cdb2 100644 --- a/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClientTlsConfig.java +++ b/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClientTlsConfig.java @@ -18,68 +18,10 @@ import com.alibaba.nacos.common.remote.TlsConfig; -import java.util.Properties; - /** * gRPC config for sdk. * * @author githubcheng2978 */ public class RpcClientTlsConfig extends TlsConfig { - - /** - * get tls config from properties. - * @param properties Properties. - * @return tls of config. - */ - public static RpcClientTlsConfig properties(Properties properties) { - RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig(); - if (properties.containsKey(RpcConstants.RPC_CLIENT_TLS_ENABLE)) { - tlsConfig.setEnableTls(Boolean.parseBoolean( - properties.getProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE))); - } - - if (properties.containsKey(RpcConstants.RPC_CLIENT_TLS_PROVIDER)) { - tlsConfig.setSslProvider(properties.getProperty(RpcConstants.RPC_CLIENT_TLS_PROVIDER)); - } - - if (properties.containsKey(RpcConstants.RPC_CLIENT_MUTUAL_AUTH)) { - tlsConfig.setMutualAuthEnable(Boolean.parseBoolean( - properties.getProperty(RpcConstants.RPC_CLIENT_MUTUAL_AUTH))); - } - - if (properties.containsKey(RpcConstants.RPC_CLIENT_TLS_PROTOCOLS)) { - tlsConfig.setProtocols(properties.getProperty(RpcConstants.RPC_CLIENT_TLS_PROTOCOLS)); - } - - if (properties.containsKey(RpcConstants.RPC_CLIENT_TLS_CIPHERS)) { - tlsConfig.setCiphers(properties.getProperty(RpcConstants.RPC_CLIENT_TLS_CIPHERS)); - } - - if (properties.containsKey(RpcConstants.RPC_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH)) { - tlsConfig.setTrustCollectionCertFile(properties.getProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH)); - } - - if (properties.containsKey(RpcConstants.RPC_CLIENT_TLS_CERT_CHAIN_PATH)) { - tlsConfig.setCertChainFile(properties.getProperty(RpcConstants.RPC_CLIENT_TLS_CERT_CHAIN_PATH)); - } - - if (properties.containsKey(RpcConstants.RPC_CLIENT_TLS_CERT_KEY)) { - tlsConfig.setCertPrivateKey(properties.getProperty(RpcConstants.RPC_CLIENT_TLS_CERT_KEY)); - } - - if (properties.containsKey(RpcConstants.RPC_CLIENT_TLS_TRUST_ALL)) { - tlsConfig.setTrustAll(Boolean.parseBoolean(properties.getProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_ALL))); - } - - if (properties.containsKey(RpcConstants.RPC_CLIENT_TLS_TRUST_PWD)) { - tlsConfig.setCertPrivateKeyPassword(properties.getProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_PWD)); - } - - if (properties.containsKey(RpcConstants.RPC_CLIENT_TLS_PROVIDER)) { - tlsConfig.setSslProvider(properties.getProperty(RpcConstants.RPC_CLIENT_TLS_PROVIDER)); - } - return tlsConfig; - } - } diff --git a/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClientTlsConfigFactory.java b/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClientTlsConfigFactory.java new file mode 100644 index 00000000000..0c12d5e393d --- /dev/null +++ b/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcClientTlsConfigFactory.java @@ -0,0 +1,97 @@ +/* + * Copyright 1999-2020 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.common.remote.client; + +import java.util.Properties; + +import static com.alibaba.nacos.common.remote.client.RpcConstants.ClientSuffix.MUTUAL_AUTH; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ClientSuffix.TLS_CERT_CHAIN_PATH; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ClientSuffix.TLS_CERT_KEY; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ClientSuffix.TLS_CIPHERS; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ClientSuffix.TLS_ENABLE; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ClientSuffix.TLS_PROTOCOLS; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ClientSuffix.TLS_PROVIDER; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ClientSuffix.TLS_TRUST_ALL; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ClientSuffix.TLS_TRUST_COLLECTION_CHAIN_PATH; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ClientSuffix.TLS_TRUST_PWD; +import static com.alibaba.nacos.common.remote.client.RpcConstants.NACOS_CLIENT_RPC; +import static com.alibaba.nacos.common.remote.client.RpcConstants.NACOS_PEER_RPC; + +/** + * TlsConfigFactory. + * + * @author stone-98 + */ +public class RpcClientTlsConfigFactory implements RpcTlsConfigFactory { + + private static RpcClientTlsConfigFactory instance; + + private RpcClientTlsConfigFactory() { + } + + public static synchronized RpcClientTlsConfigFactory getInstance() { + if (instance == null) { + instance = new RpcClientTlsConfigFactory(); + } + return instance; + } + + /** + * Create SDK client TLS config. + * + * @param properties Properties containing TLS configuration + * @return RpcClientTlsConfig object representing the TLS configuration + */ + @Override + public RpcClientTlsConfig createSdkConfig(Properties properties) { + RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig(); + tlsConfig.setEnableTls(getBooleanProperty(properties, NACOS_CLIENT_RPC + TLS_ENABLE, false)); + tlsConfig.setMutualAuthEnable(getBooleanProperty(properties, NACOS_CLIENT_RPC + MUTUAL_AUTH, false)); + tlsConfig.setProtocols(properties.getProperty(NACOS_CLIENT_RPC + TLS_PROTOCOLS)); + tlsConfig.setCiphers(properties.getProperty(NACOS_CLIENT_RPC + TLS_CIPHERS)); + tlsConfig.setTrustCollectionCertFile(properties.getProperty(NACOS_CLIENT_RPC + TLS_TRUST_COLLECTION_CHAIN_PATH)); + tlsConfig.setCertChainFile(properties.getProperty(NACOS_CLIENT_RPC + TLS_CERT_CHAIN_PATH)); + tlsConfig.setCertPrivateKey(properties.getProperty(NACOS_CLIENT_RPC + TLS_CERT_KEY)); + tlsConfig.setTrustAll(getBooleanProperty(properties, NACOS_CLIENT_RPC + TLS_TRUST_ALL, true)); + tlsConfig.setCertPrivateKeyPassword(properties.getProperty(NACOS_CLIENT_RPC + TLS_TRUST_PWD)); + tlsConfig.setSslProvider(properties.getProperty(NACOS_CLIENT_RPC + TLS_PROVIDER)); + return tlsConfig; + } + + /** + * Create cluster client TLS config. + * + * @param properties Properties containing TLS configuration + * @return RpcClientTlsConfig object representing the TLS configuration + */ + @Override + public RpcClientTlsConfig createClusterConfig(Properties properties) { + RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig(); + tlsConfig.setEnableTls(getBooleanProperty(properties, NACOS_PEER_RPC + RpcConstants.ServerSuffix.TLS_ENABLE, false)); + tlsConfig.setMutualAuthEnable(getBooleanProperty(properties, NACOS_PEER_RPC + RpcConstants.ServerSuffix.MUTUAL_AUTH, false)); + tlsConfig.setProtocols(properties.getProperty(NACOS_PEER_RPC + RpcConstants.ServerSuffix.TLS_PROTOCOLS)); + tlsConfig.setCiphers(properties.getProperty(NACOS_PEER_RPC + RpcConstants.ServerSuffix.TLS_CIPHERS)); + tlsConfig.setTrustCollectionCertFile(properties.getProperty(NACOS_PEER_RPC + RpcConstants.ServerSuffix.TLS_TRUST_COLLECTION_CHAIN_PATH)); + tlsConfig.setCertChainFile(properties.getProperty(NACOS_PEER_RPC + RpcConstants.ServerSuffix.TLS_CERT_CHAIN_PATH)); + tlsConfig.setCertPrivateKey(properties.getProperty(NACOS_PEER_RPC + RpcConstants.ServerSuffix.TLS_CERT_KEY)); + tlsConfig.setTrustAll(getBooleanProperty(properties, NACOS_PEER_RPC + RpcConstants.ServerSuffix.TLS_TRUST_ALL, true)); + tlsConfig.setCertPrivateKeyPassword(properties.getProperty(NACOS_PEER_RPC + RpcConstants.ServerSuffix.TLS_TRUST_PWD)); + tlsConfig.setSslProvider(properties.getProperty(NACOS_PEER_RPC + RpcConstants.ServerSuffix.TLS_PROVIDER)); + return tlsConfig; + } + +} diff --git a/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcConstants.java b/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcConstants.java index 0b0f40762b6..92ee198bcc7 100644 --- a/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcConstants.java +++ b/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcConstants.java @@ -34,54 +34,51 @@ public class RpcConstants { public static final String NACOS_CLIENT_RPC = "nacos.remote.client.rpc"; - + + public static final String NACOS_SERVER_RPC = "nacos.remote.server.rpc.tls"; + + public static final String NACOS_PEER_RPC = "nacos.remote.peer.rpc.tls"; + @RpcConfigLabel - public static final String RPC_CLIENT_TLS_ENABLE = NACOS_CLIENT_RPC + ".tls.enable"; + public static final String RPC_CLIENT_TLS_ENABLE = NACOS_CLIENT_RPC + ClientSuffix.TLS_ENABLE; @RpcConfigLabel - public static final String RPC_CLIENT_TLS_PROVIDER = NACOS_CLIENT_RPC + ".tls.provider"; + public static final String RPC_CLIENT_TLS_PROVIDER = NACOS_CLIENT_RPC + ClientSuffix.TLS_PROVIDER; @RpcConfigLabel - public static final String RPC_CLIENT_MUTUAL_AUTH = NACOS_CLIENT_RPC + ".tls.mutualAuth"; + public static final String RPC_CLIENT_MUTUAL_AUTH = NACOS_CLIENT_RPC + ClientSuffix.MUTUAL_AUTH; @RpcConfigLabel - public static final String RPC_CLIENT_TLS_PROTOCOLS = NACOS_CLIENT_RPC + ".tls.protocols"; + public static final String RPC_CLIENT_TLS_PROTOCOLS = NACOS_CLIENT_RPC + ClientSuffix.TLS_PROTOCOLS; @RpcConfigLabel - public static final String RPC_CLIENT_TLS_CIPHERS = NACOS_CLIENT_RPC + ".tls.ciphers"; + public static final String RPC_CLIENT_TLS_CIPHERS = NACOS_CLIENT_RPC + ClientSuffix.TLS_CIPHERS; @RpcConfigLabel - public static final String RPC_CLIENT_TLS_CERT_CHAIN_PATH = NACOS_CLIENT_RPC + ".tls.certChainFile"; + public static final String RPC_CLIENT_TLS_CERT_CHAIN_PATH = NACOS_CLIENT_RPC + ClientSuffix.TLS_CERT_CHAIN_PATH; @RpcConfigLabel - public static final String RPC_CLIENT_TLS_CERT_KEY = NACOS_CLIENT_RPC + ".tls.certPrivateKey"; + public static final String RPC_CLIENT_TLS_CERT_KEY = NACOS_CLIENT_RPC + ClientSuffix.TLS_CERT_KEY; @RpcConfigLabel - public static final String RPC_CLIENT_TLS_TRUST_PWD = NACOS_CLIENT_RPC + ".tls.certPrivateKeyPassword"; + public static final String RPC_CLIENT_TLS_TRUST_PWD = NACOS_CLIENT_RPC + ClientSuffix.TLS_TRUST_PWD; @RpcConfigLabel public static final String RPC_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH = - NACOS_CLIENT_RPC + ".tls.trustCollectionChainPath"; + NACOS_CLIENT_RPC + ClientSuffix.TLS_TRUST_COLLECTION_CHAIN_PATH; @RpcConfigLabel - public static final String RPC_CLIENT_TLS_TRUST_ALL = NACOS_CLIENT_RPC + ".tls.trustAll"; + public static final String RPC_CLIENT_TLS_TRUST_ALL = NACOS_CLIENT_RPC + ClientSuffix.TLS_TRUST_ALL; private static final Set CONFIG_NAMES = new HashSet<>(); - @Documented - @Target(ElementType.FIELD) - @Retention(RetentionPolicy.RUNTIME) - protected @interface RpcConfigLabel { - - } - static { Class clazz = RpcConstants.class; Field[] declaredFields = clazz.getDeclaredFields(); for (Field declaredField : declaredFields) { declaredField.setAccessible(true); - if (declaredField.getType().equals(String.class) && null != declaredField - .getAnnotation(RpcConfigLabel.class)) { + if (declaredField.getType().equals(String.class) && null != declaredField.getAnnotation( + RpcConfigLabel.class)) { try { CONFIG_NAMES.add((String) declaredField.get(null)); } catch (IllegalAccessException ignored) { @@ -90,7 +87,139 @@ public class RpcConstants { } } + /** + * Enumeration of common suffixes for RPC configuration properties. Each enum constant represents a specific + * configuration attribute suffix. This allows for the construction of complete configuration property keys. + */ + public class ClientSuffix { + + /** + * Suffix for 'tls.enable' configuration property. + */ + public static final String TLS_ENABLE = ".tls.enable"; + + /** + * Suffix for 'tls.provider' configuration property. + */ + public static final String TLS_PROVIDER = ".tls.provider"; + + /** + * Suffix for 'tls.mutualAuth' configuration property. + */ + public static final String MUTUAL_AUTH = ".tls.mutualAuth"; + + /** + * Suffix for 'tls.protocols' configuration property. + */ + public static final String TLS_PROTOCOLS = ".tls.protocols"; + + /** + * Suffix for 'tls.ciphers' configuration property. + */ + public static final String TLS_CIPHERS = ".tls.ciphers"; + + /** + * Suffix for 'tls.certChainFile' configuration property. + */ + public static final String TLS_CERT_CHAIN_PATH = ".tls.certChainFile"; + + /** + * Suffix for 'tls.certPrivateKey' configuration property. + */ + public static final String TLS_CERT_KEY = ".tls.certPrivateKey"; + + /** + * Suffix for 'tls.certPrivateKeyPassword' configuration property. + */ + public static final String TLS_TRUST_PWD = ".tls.certPrivateKeyPassword"; + + /** + * Suffix for 'tls.trustCollectionChainPath' configuration property. + */ + public static final String TLS_TRUST_COLLECTION_CHAIN_PATH = ".tls.trustCollectionChainPath"; + + /** + * Suffix for 'tls.trustAll' configuration property. + */ + public static final String TLS_TRUST_ALL = ".tls.trustAll"; + } + + /** + * Enumeration of common suffixes for RPC configuration properties. Each enum constant represents a specific + * configuration attribute suffix. This allows for the construction of complete configuration property keys. + */ + public class ServerSuffix { + + /** + * Suffix for 'tls.enable' configuration property. + */ + public static final String TLS_ENABLE = ".enableTls"; + + /** + * Suffix for 'tls.provider' configuration property. + */ + public static final String TLS_PROVIDER = ".sslProvider"; + + /** + * Suffix for 'tls.mutualAuth' configuration property. + */ + public static final String MUTUAL_AUTH = ".mutualAuthEnable"; + + /** + * Suffix for 'tls.protocols' configuration property. + */ + public static final String TLS_PROTOCOLS = ".protocols"; + + /** + * Suffix for 'tls.ciphers' configuration property. + */ + public static final String TLS_CIPHERS = ".ciphers"; + + /** + * Suffix for 'tls.certChainFile' configuration property. + */ + public static final String TLS_CERT_CHAIN_PATH = ".certChainFile"; + + /** + * Suffix for 'tls.certPrivateKey' configuration property. + */ + public static final String TLS_CERT_KEY = ".certPrivateKey"; + + /** + * Suffix for 'tls.certPrivateKeyPassword' configuration property. + */ + public static final String TLS_TRUST_PWD = ".certPrivateKeyPassword"; + + /** + * Suffix for 'tls.trustCollectionChainPath' configuration property. + */ + public static final String TLS_TRUST_COLLECTION_CHAIN_PATH = ".trustCollectionCertFile"; + + /** + * Suffix for 'tls.trustAll' configuration property. + */ + public static final String TLS_TRUST_ALL = ".trustAll"; + + /** + * Suffix for '.sslContextRefresher' configuration property. + */ + public static final String SSL_CONTEXT_REFRESHER = ".sslContextRefresher"; + + /** + * Suffix for '.compatibility' configuration property. + */ + public static final String COMPATIBILITY = ".compatibility"; + } + + @Documented + @Target(ElementType.FIELD) + @Retention(RetentionPolicy.RUNTIME) + protected @interface RpcConfigLabel { + + } + public static Set getRpcParams() { return Collections.unmodifiableSet(CONFIG_NAMES); } + } diff --git a/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcTlsConfigFactory.java b/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcTlsConfigFactory.java new file mode 100644 index 00000000000..eded7fdd78b --- /dev/null +++ b/common/src/main/java/com/alibaba/nacos/common/remote/client/RpcTlsConfigFactory.java @@ -0,0 +1,62 @@ +/* + * Copyright 1999-2020 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.common.remote.client; + +import com.alibaba.nacos.common.remote.TlsConfig; + +import java.util.Properties; + +/** + * RpcTlsConfigFactory. + * + * @author stone-98 + * @date 2024/4/8 + */ +public interface RpcTlsConfigFactory { + + /** + * Create a TlsConfig for SDK connections based on the provided properties. + * + * @param properties Properties containing configuration + * @return TlsConfig instance for SDK connections + */ + TlsConfig createSdkConfig(Properties properties); + + /** + * Create a TlsConfig for cluster connections based on the provided properties. + * + * @param properties Properties containing configuration + * @return TlsConfig instance for cluster connections + */ + TlsConfig createClusterConfig(Properties properties); + + /** + * Get boolean property from properties. + * + * @param properties Properties containing configuration + * @param key Key of the property + * @param defaultValue Default value to return if the property is not found or is invalid + * @return Boolean value of the property, or the provided defaultValue if not found or invalid + */ + default Boolean getBooleanProperty(Properties properties, String key, Boolean defaultValue) { + String value = properties.getProperty(key); + if (value != null) { + return Boolean.parseBoolean(value); + } + return defaultValue; + } +} \ No newline at end of file diff --git a/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/DefaultGrpcClientConfig.java b/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/DefaultGrpcClientConfig.java index cf6ac4787e5..05fbb825b9d 100644 --- a/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/DefaultGrpcClientConfig.java +++ b/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/DefaultGrpcClientConfig.java @@ -16,7 +16,9 @@ package com.alibaba.nacos.common.remote.client.grpc; +import com.alibaba.nacos.common.remote.TlsConfig; import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig; +import com.alibaba.nacos.common.remote.client.RpcClientTlsConfigFactory; import com.alibaba.nacos.common.utils.ThreadUtils; import java.util.HashMap; @@ -32,37 +34,37 @@ */ public class DefaultGrpcClientConfig implements GrpcClientConfig { - private String name; + private final String name; - private int retryTimes; + private final int retryTimes; - private long timeOutMills; + private final long timeOutMills; - private long connectionKeepAlive; + private final long connectionKeepAlive; - private long channelKeepAliveTimeout; + private final long channelKeepAliveTimeout; - private long threadPoolKeepAlive; + private final long threadPoolKeepAlive; - private int threadPoolCoreSize; + private final int threadPoolCoreSize; - private int threadPoolMaxSize; + private final int threadPoolMaxSize; - private long serverCheckTimeOut; + private final long serverCheckTimeOut; - private int threadPoolQueueSize; + private final int threadPoolQueueSize; - private int maxInboundMessageSize; + private final int maxInboundMessageSize; - private int channelKeepAlive; + private final int channelKeepAlive; - private int healthCheckRetryTimes; + private final int healthCheckRetryTimes; - private long healthCheckTimeOut; + private final long healthCheckTimeOut; - private long capabilityNegotiationTimeout; + private final long capabilityNegotiationTimeout; - private Map labels; + private final Map labels; private RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig(); @@ -98,7 +100,7 @@ private DefaultGrpcClientConfig(Builder builder) { this.labels.put("tls.enable", "false"); if (Objects.nonNull(builder.tlsConfig)) { this.tlsConfig = builder.tlsConfig; - if (builder.tlsConfig.getEnableTls()) { + if (Objects.nonNull(builder.tlsConfig.getEnableTls()) && builder.tlsConfig.getEnableTls()) { this.labels.put("tls.enable", "true"); } } @@ -173,7 +175,7 @@ public long channelKeepAliveTimeout() { } @Override - public RpcClientTlsConfig tlsConfig() { + public TlsConfig tlsConfig() { return tlsConfig; } @@ -237,12 +239,22 @@ public static class Builder { private long capabilityNegotiationTimeout = 5000L; - private Map labels = new HashMap<>(); + private final Map labels = new HashMap<>(); private RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig(); private Builder() { } + + public Builder buildSdkFromProperties(Properties properties) { + RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createSdkConfig(properties); + return fromProperties(properties, tlsConfig); + } + + public Builder buildClusterFromProperties(Properties properties) { + RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createClusterConfig(properties); + return fromProperties(properties, tlsConfig); + } /** * Set config from properties. @@ -250,7 +262,7 @@ private Builder() { * @param properties properties * @return Builder */ - public Builder fromProperties(Properties properties) { + public Builder fromProperties(Properties properties, RpcClientTlsConfig tlsConfig) { if (properties.containsKey(GrpcConstants.GRPC_NAME)) { this.name = properties.getProperty(GrpcConstants.GRPC_NAME); } @@ -261,53 +273,53 @@ public Builder fromProperties(Properties properties) { this.timeOutMills = Long.parseLong(properties.getProperty(GrpcConstants.GRPC_TIMEOUT_MILLS)); } if (properties.containsKey(GrpcConstants.GRPC_CONNECT_KEEP_ALIVE_TIME)) { - this.connectionKeepAlive = Long - .parseLong(properties.getProperty(GrpcConstants.GRPC_CONNECT_KEEP_ALIVE_TIME)); + this.connectionKeepAlive = Long.parseLong( + properties.getProperty(GrpcConstants.GRPC_CONNECT_KEEP_ALIVE_TIME)); } if (properties.containsKey(GrpcConstants.GRPC_THREADPOOL_KEEPALIVETIME)) { - this.threadPoolKeepAlive = Long - .parseLong(properties.getProperty(GrpcConstants.GRPC_THREADPOOL_KEEPALIVETIME)); + this.threadPoolKeepAlive = Long.parseLong( + properties.getProperty(GrpcConstants.GRPC_THREADPOOL_KEEPALIVETIME)); } if (properties.containsKey(GrpcConstants.GRPC_THREADPOOL_CORE_SIZE)) { - this.threadPoolCoreSize = Integer - .parseInt(properties.getProperty(GrpcConstants.GRPC_THREADPOOL_CORE_SIZE)); + this.threadPoolCoreSize = Integer.parseInt( + properties.getProperty(GrpcConstants.GRPC_THREADPOOL_CORE_SIZE)); } if (properties.containsKey(GrpcConstants.GRPC_THREADPOOL_MAX_SIZE)) { - this.threadPoolMaxSize = Integer - .parseInt(properties.getProperty(GrpcConstants.GRPC_THREADPOOL_MAX_SIZE)); + this.threadPoolMaxSize = Integer.parseInt( + properties.getProperty(GrpcConstants.GRPC_THREADPOOL_MAX_SIZE)); } if (properties.containsKey(GrpcConstants.GRPC_SERVER_CHECK_TIMEOUT)) { - this.serverCheckTimeOut = Long - .parseLong(properties.getProperty(GrpcConstants.GRPC_SERVER_CHECK_TIMEOUT)); + this.serverCheckTimeOut = Long.parseLong( + properties.getProperty(GrpcConstants.GRPC_SERVER_CHECK_TIMEOUT)); } if (properties.containsKey(GrpcConstants.GRPC_QUEUESIZE)) { this.threadPoolQueueSize = Integer.parseInt(properties.getProperty(GrpcConstants.GRPC_QUEUESIZE)); } if (properties.containsKey(GrpcConstants.GRPC_MAX_INBOUND_MESSAGE_SIZE)) { - this.maxInboundMessageSize = Integer - .parseInt(properties.getProperty(GrpcConstants.GRPC_MAX_INBOUND_MESSAGE_SIZE)); + this.maxInboundMessageSize = Integer.parseInt( + properties.getProperty(GrpcConstants.GRPC_MAX_INBOUND_MESSAGE_SIZE)); } if (properties.containsKey(GrpcConstants.GRPC_CHANNEL_KEEP_ALIVE_TIME)) { - this.channelKeepAlive = Integer - .parseInt(properties.getProperty(GrpcConstants.GRPC_CHANNEL_KEEP_ALIVE_TIME)); + this.channelKeepAlive = Integer.parseInt( + properties.getProperty(GrpcConstants.GRPC_CHANNEL_KEEP_ALIVE_TIME)); } if (properties.containsKey(GrpcConstants.GRPC_CHANNEL_CAPABILITY_NEGOTIATION_TIMEOUT)) { - this.capabilityNegotiationTimeout = Integer - .parseInt(properties.getProperty(GrpcConstants.GRPC_CHANNEL_CAPABILITY_NEGOTIATION_TIMEOUT)); + this.capabilityNegotiationTimeout = Integer.parseInt( + properties.getProperty(GrpcConstants.GRPC_CHANNEL_CAPABILITY_NEGOTIATION_TIMEOUT)); } if (properties.containsKey(GrpcConstants.GRPC_HEALTHCHECK_RETRY_TIMES)) { - this.healthCheckRetryTimes = Integer - .parseInt(properties.getProperty(GrpcConstants.GRPC_HEALTHCHECK_RETRY_TIMES)); + this.healthCheckRetryTimes = Integer.parseInt( + properties.getProperty(GrpcConstants.GRPC_HEALTHCHECK_RETRY_TIMES)); } if (properties.containsKey(GrpcConstants.GRPC_HEALTHCHECK_TIMEOUT)) { - this.healthCheckTimeOut = Long - .parseLong(properties.getProperty(GrpcConstants.GRPC_HEALTHCHECK_TIMEOUT)); + this.healthCheckTimeOut = Long.parseLong( + properties.getProperty(GrpcConstants.GRPC_HEALTHCHECK_TIMEOUT)); } if (properties.containsKey(GrpcConstants.GRPC_CHANNEL_KEEP_ALIVE_TIMEOUT)) { - this.channelKeepAliveTimeout = Integer - .parseInt(properties.getProperty(GrpcConstants.GRPC_CHANNEL_KEEP_ALIVE_TIMEOUT)); + this.channelKeepAliveTimeout = Integer.parseInt( + properties.getProperty(GrpcConstants.GRPC_CHANNEL_KEEP_ALIVE_TIMEOUT)); } - this.tlsConfig = RpcClientTlsConfig.properties(properties); + this.tlsConfig = tlsConfig; return this; } diff --git a/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClient.java b/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClient.java index 25d213cb951..3cde9d830fa 100644 --- a/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClient.java +++ b/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClient.java @@ -33,6 +33,7 @@ import com.alibaba.nacos.common.ability.discover.NacosAbilityManagerHolder; import com.alibaba.nacos.common.packagescan.resource.Resource; import com.alibaba.nacos.common.remote.ConnectionType; +import com.alibaba.nacos.common.remote.TlsConfig; import com.alibaba.nacos.common.remote.client.Connection; import com.alibaba.nacos.common.remote.client.RpcClient; import com.alibaba.nacos.common.remote.client.RpcClientStatus; @@ -64,7 +65,6 @@ import java.util.HashMap; import java.util.Map; import java.util.Optional; -import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; @@ -109,15 +109,6 @@ public GrpcClient(String name) { this(DefaultGrpcClientConfig.newBuilder().setName(name).build()); } - /** - * constructor. - * - * @param properties . - */ - public GrpcClient(Properties properties) { - this(DefaultGrpcClientConfig.newBuilder().fromProperties(properties).build()); - } - /** * constructor. * @@ -209,8 +200,8 @@ protected RequestGrpc.RequestFutureStub createNewChannelStub(ManagedChannel mana private ManagedChannel createNewManagedChannel(String serverIp, int serverPort) { LOGGER.info("grpc client connection server:{} ip,serverPort:{},grpcTslConfig:{}", serverIp, serverPort, JacksonUtils.toJson(clientConfig.tlsConfig())); - ManagedChannelBuilder managedChannelBuilder = buildChannel(serverIp, serverPort, buildSslContext()) - .executor(grpcExecutor).compressorRegistry(CompressorRegistry.getDefaultInstance()) + ManagedChannelBuilder managedChannelBuilder = buildChannel(serverIp, serverPort, buildSslContext()).executor( + grpcExecutor).compressorRegistry(CompressorRegistry.getDefaultInstance()) .decompressorRegistry(DecompressorRegistry.getDefaultInstance()) .maxInboundMessageSize(clientConfig.maxInboundMessageSize()) .keepAliveTime(clientConfig.channelKeepAlive(), TimeUnit.MILLISECONDS) @@ -288,8 +279,8 @@ public void onNext(Payload payload) { } catch (Exception e) { LoggerUtils.printIfErrorEnabled(LOGGER, "[{}]Handle server request exception: {}", grpcConn.getConnectionId(), payload.toString(), e.getMessage()); - Response errResponse = ErrorResponse - .build(NacosException.CLIENT_ERROR, "Handle server request error"); + Response errResponse = ErrorResponse.build(NacosException.CLIENT_ERROR, + "Handle server request error"); errResponse.setRequestId(request.getRequestId()); sendResponse(errResponse); } @@ -374,8 +365,8 @@ public Connection connectToServer(ServerInfo serverInfo) { ServerCheckResponse serverCheckResponse = (ServerCheckResponse) response; connectionId = serverCheckResponse.getConnectionId(); - BiRequestStreamGrpc.BiRequestStreamStub biRequestStreamStub = BiRequestStreamGrpc - .newStub(newChannelStubTemp.getChannel()); + BiRequestStreamGrpc.BiRequestStreamStub biRequestStreamStub = BiRequestStreamGrpc.newStub( + newChannelStubTemp.getChannel()); GrpcConnection grpcConn = new GrpcConnection(serverInfo, grpcExecutor); grpcConn.setConnectionId(connectionId); // if not supported, it will be false @@ -398,8 +389,8 @@ public Connection connectToServer(ServerInfo serverInfo) { conSetupRequest.setClientVersion(VersionUtils.getFullClientVersion()); conSetupRequest.setLabels(super.getLabels()); // set ability table - conSetupRequest - .setAbilityTable(NacosAbilityManagerHolder.getInstance().getCurrentNodeAbilities(abilityMode())); + conSetupRequest.setAbilityTable( + NacosAbilityManagerHolder.getInstance().getCurrentNodeAbilities(abilityMode())); conSetupRequest.setTenant(super.getTenant()); grpcConn.sendRequest(conSetupRequest); // wait for response @@ -531,44 +522,9 @@ public boolean check(Connection connection) { } } - /** - * Setup response handler. - */ - class SetupRequestHandler implements ServerRequestHandler { - - private final RecAbilityContext abilityContext; - - public SetupRequestHandler(RecAbilityContext abilityContext) { - this.abilityContext = abilityContext; - } - - @Override - public Response requestReply(Request request, Connection connection) { - // if finish setup - if (request instanceof SetupAckRequest) { - SetupAckRequest setupAckRequest = (SetupAckRequest) request; - // remove and count down - recAbilityContext - .release(Optional.ofNullable(setupAckRequest.getAbilityTable()).orElse(new HashMap<>(0))); - return new SetupAckResponse(); - } - return null; - } - } - - private ManagedChannelBuilder buildChannel(String serverIp, int port, Optional sslContext) { - if (sslContext.isPresent()) { - return NettyChannelBuilder.forAddress(serverIp, port).negotiationType(NegotiationType.TLS) - .sslContext(sslContext.get()); - - } else { - return ManagedChannelBuilder.forAddress(serverIp, port).usePlaintext(); - } - } - private Optional buildSslContext() { - RpcClientTlsConfig tlsConfig = clientConfig.tlsConfig(); + TlsConfig tlsConfig = clientConfig.tlsConfig(); if (!tlsConfig.getEnableTls()) { return Optional.empty(); } @@ -595,8 +551,8 @@ private Optional buildSslContext() { } if (tlsConfig.getMutualAuthEnable()) { - if (StringUtils.isBlank(tlsConfig.getCertChainFile()) || StringUtils - .isBlank(tlsConfig.getCertPrivateKey())) { + if (StringUtils.isBlank(tlsConfig.getCertChainFile()) || StringUtils.isBlank( + tlsConfig.getCertPrivateKey())) { throw new IllegalArgumentException("client certChainFile or certPrivateKey must be not null"); } Resource certChainFile = resourceLoader.getResource(tlsConfig.getCertChainFile()); @@ -609,6 +565,41 @@ private Optional buildSslContext() { throw new RuntimeException("Unable to build SslContext", e); } } + + private ManagedChannelBuilder buildChannel(String serverIp, int port, Optional sslContext) { + if (sslContext.isPresent()) { + return NettyChannelBuilder.forAddress(serverIp, port).negotiationType(NegotiationType.TLS) + .sslContext(sslContext.get()); + + } else { + return ManagedChannelBuilder.forAddress(serverIp, port).usePlaintext(); + } + } + + /** + * Setup response handler. + */ + class SetupRequestHandler implements ServerRequestHandler { + + private final RecAbilityContext abilityContext; + + public SetupRequestHandler(RecAbilityContext abilityContext) { + this.abilityContext = abilityContext; + } + + @Override + public Response requestReply(Request request, Connection connection) { + // if finish setup + if (request instanceof SetupAckRequest) { + SetupAckRequest setupAckRequest = (SetupAckRequest) request; + // remove and count down + recAbilityContext.release( + Optional.ofNullable(setupAckRequest.getAbilityTable()).orElse(new HashMap<>(0))); + return new SetupAckResponse(); + } + return null; + } + } } diff --git a/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClientConfig.java b/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClientConfig.java index 1c1b4003bad..d16ebcc9dc9 100644 --- a/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClientConfig.java +++ b/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClientConfig.java @@ -16,6 +16,7 @@ package com.alibaba.nacos.common.remote.client.grpc; +import com.alibaba.nacos.common.remote.TlsConfig; import com.alibaba.nacos.common.remote.client.RpcClientConfig; import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig; @@ -81,26 +82,26 @@ public interface GrpcClientConfig extends RpcClientConfig { * @return channelKeepAliveTimeout. */ long channelKeepAliveTimeout(); - + /** - * getTlsConfig. + * getTlsConfig. * * @return TlsConfig. */ - RpcClientTlsConfig tlsConfig(); - + TlsConfig tlsConfig(); + /** - *Set TlsConfig. + * Set TlsConfig. * * @param tlsConfig tlsConfig of client. */ void setTlsConfig(RpcClientTlsConfig tlsConfig); - + /** * get timeout of connection setup(TimeUnit.MILLISECONDS). * * @return timeout of connection setup */ long capabilityNegotiationTimeout(); - + } diff --git a/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClusterClient.java b/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClusterClient.java index 7749f69b6f6..69530afd833 100644 --- a/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClusterClient.java +++ b/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClusterClient.java @@ -21,7 +21,6 @@ import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig; import java.util.Map; -import java.util.Properties; /** * gRPC client for cluster. @@ -48,16 +47,7 @@ public GrpcClusterClient(String name) { public GrpcClusterClient(GrpcClientConfig config) { super(config); } - - /** - * Constructor. - * - * @param properties . - */ - public GrpcClusterClient(Properties properties) { - super(properties); - } - + /** * Constructor. * @@ -67,20 +57,20 @@ public GrpcClusterClient(Properties properties) { * @param labels . */ public GrpcClusterClient(String name, Integer threadPoolCoreSize, Integer threadPoolMaxSize, - Map labels) { + Map labels) { this(name, threadPoolCoreSize, threadPoolMaxSize, labels, null); } - + public GrpcClusterClient(String name, Integer threadPoolCoreSize, Integer threadPoolMaxSize, - Map labels, RpcClientTlsConfig tlsConfig) { + Map labels, RpcClientTlsConfig tlsConfig) { super(name, threadPoolCoreSize, threadPoolMaxSize, labels, tlsConfig); } - + @Override protected AbilityMode abilityMode() { return AbilityMode.CLUSTER_CLIENT; } - + @Override public int rpcPortOffset() { return Integer.parseInt(System.getProperty(GrpcConstants.NACOS_SERVER_GRPC_PORT_OFFSET_KEY, diff --git a/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcSdkClient.java b/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcSdkClient.java index 0ede2af6de6..cf973416cca 100644 --- a/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcSdkClient.java +++ b/common/src/main/java/com/alibaba/nacos/common/remote/client/grpc/GrpcSdkClient.java @@ -21,7 +21,6 @@ import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig; import java.util.Map; -import java.util.Properties; /** * gRPC client for sdk. @@ -40,15 +39,6 @@ public GrpcSdkClient(String name) { super(name); } - /** - * Constructor. - * - * @param properties . - */ - public GrpcSdkClient(Properties properties) { - super(properties); - } - /** * Constructor. * @@ -57,20 +47,21 @@ public GrpcSdkClient(Properties properties) { * @param threadPoolMaxSize . * @param labels . */ - public GrpcSdkClient(String name, Integer threadPoolCoreSize, Integer threadPoolMaxSize, Map labels) { + public GrpcSdkClient(String name, Integer threadPoolCoreSize, Integer threadPoolMaxSize, + Map labels) { this(name, threadPoolCoreSize, threadPoolMaxSize, labels, null); } - + public GrpcSdkClient(String name, Integer threadPoolCoreSize, Integer threadPoolMaxSize, Map labels, - RpcClientTlsConfig tlsConfig) { + RpcClientTlsConfig tlsConfig) { super(name, threadPoolCoreSize, threadPoolMaxSize, labels, tlsConfig); } - + @Override protected AbilityMode abilityMode() { return AbilityMode.SDK_CLIENT; } - + /** * constructor. * @@ -86,4 +77,4 @@ public int rpcPortOffset() { String.valueOf(Constants.SDK_GRPC_PORT_DEFAULT_OFFSET))); } -} \ No newline at end of file +} diff --git a/common/src/test/java/ClassUtilsTestMockClass.java b/common/src/test/java/ClassUtilsTestMockClass.java index 5183078632f..f031c6d4493 100644 --- a/common/src/test/java/ClassUtilsTestMockClass.java +++ b/common/src/test/java/ClassUtilsTestMockClass.java @@ -15,4 +15,5 @@ */ public class ClassUtilsTestMockClass { + } diff --git a/common/src/test/java/com/alibaba/nacos/common/AppTest.java b/common/src/test/java/com/alibaba/nacos/common/AppTest.java index 75cfed5b962..3e2b245a855 100644 --- a/common/src/test/java/com/alibaba/nacos/common/AppTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/AppTest.java @@ -16,21 +16,14 @@ package com.alibaba.nacos.common; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; +import org.junit.jupiter.api.Test; -public class AppTest extends TestCase { - - public AppTest(String testName) { - super(testName); - } - - public static Test suite() { - return new TestSuite(AppTest.class); - } +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class AppTest { - public void testApp() { + @Test + void testApp() { assertTrue(true); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/ability/AbstractAbilityControlManagerTest.java b/common/src/test/java/com/alibaba/nacos/common/ability/AbstractAbilityControlManagerTest.java index 7da46bfc53e..a25df5c6061 100644 --- a/common/src/test/java/com/alibaba/nacos/common/ability/AbstractAbilityControlManagerTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/ability/AbstractAbilityControlManagerTest.java @@ -22,19 +22,20 @@ import com.alibaba.nacos.common.notify.Event; import com.alibaba.nacos.common.notify.NotifyCenter; import com.alibaba.nacos.common.notify.listener.Subscriber; -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.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; -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; -public class AbstractAbilityControlManagerTest { +class AbstractAbilityControlManagerTest { private AbstractAbilityControlManager abilityControlManager; @@ -46,8 +47,8 @@ public class AbstractAbilityControlManagerTest { private boolean notified = false; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { mockSubscriber = new Subscriber() { @Override public void onEvent(AbstractAbilityControlManager.AbilityUpdateEvent event) { @@ -71,15 +72,15 @@ public Class subscribeType() { NotifyCenter.registerSubscriber(mockSubscriber); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { NotifyCenter.deregisterSubscriber(mockSubscriber); assertionError = null; notified = false; } @Test - public void testEnableCurrentNodeAbility() throws InterruptedException { + void testEnableCurrentNodeAbility() throws InterruptedException { isOn = true; abilityControlManager.enableCurrentNodeAbility(AbilityKey.SERVER_TEST_1); TimeUnit.MILLISECONDS.sleep(1100); @@ -90,7 +91,7 @@ public void testEnableCurrentNodeAbility() throws InterruptedException { } @Test - public void testDisableCurrentNodeAbility() throws InterruptedException { + void testDisableCurrentNodeAbility() throws InterruptedException { isOn = false; abilityControlManager.disableCurrentNodeAbility(AbilityKey.SERVER_TEST_1); TimeUnit.MILLISECONDS.sleep(1100); @@ -101,17 +102,14 @@ public void testDisableCurrentNodeAbility() throws InterruptedException { } @Test - public void testIsCurrentNodeAbilityRunning() { - assertEquals(AbilityStatus.SUPPORTED, - abilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_1)); - assertEquals(AbilityStatus.NOT_SUPPORTED, - abilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_2)); - assertEquals(AbilityStatus.UNKNOWN, - abilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SDK_CLIENT_TEST_1)); + void testIsCurrentNodeAbilityRunning() { + assertEquals(AbilityStatus.SUPPORTED, abilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_1)); + assertEquals(AbilityStatus.NOT_SUPPORTED, abilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_2)); + assertEquals(AbilityStatus.UNKNOWN, abilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SDK_CLIENT_TEST_1)); } @Test - public void testGetCurrentNodeAbilities() { + void testGetCurrentNodeAbilities() { Map actual = abilityControlManager.getCurrentNodeAbilities(AbilityMode.SERVER); assertEquals(2, actual.size()); assertTrue(actual.containsKey(AbilityKey.SERVER_TEST_1.getName())); @@ -121,24 +119,26 @@ public void testGetCurrentNodeAbilities() { } @Test - public void testGetPriority() { + void testGetPriority() { assertEquals(Integer.MIN_VALUE, abilityControlManager.getPriority()); } - @Test(expected = IllegalStateException.class) - public void testInitFailed() { - abilityControlManager = new AbstractAbilityControlManager() { - @Override - protected Map> initCurrentNodeAbilities() { - Map abilities = Collections.singletonMap(AbilityKey.SDK_CLIENT_TEST_1, true); - return Collections.singletonMap(AbilityMode.SERVER, abilities); - } - - @Override - public int getPriority() { - return 0; - } - }; + @Test + void testInitFailed() { + assertThrows(IllegalStateException.class, () -> { + abilityControlManager = new AbstractAbilityControlManager() { + @Override + protected Map> initCurrentNodeAbilities() { + Map abilities = Collections.singletonMap(AbilityKey.SDK_CLIENT_TEST_1, true); + return Collections.singletonMap(AbilityMode.SERVER, abilities); + } + + @Override + public int getPriority() { + return 0; + } + }; + }); } private static final class MockAbilityControlManager extends AbstractAbilityControlManager { diff --git a/common/src/test/java/com/alibaba/nacos/common/ability/discover/NacosAbilityManagerHolderTest.java b/common/src/test/java/com/alibaba/nacos/common/ability/discover/NacosAbilityManagerHolderTest.java index 6cf8dce7f9d..768ccf1878d 100644 --- a/common/src/test/java/com/alibaba/nacos/common/ability/discover/NacosAbilityManagerHolderTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/ability/discover/NacosAbilityManagerHolderTest.java @@ -16,44 +16,46 @@ package com.alibaba.nacos.common.ability.discover; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +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.junit.jupiter.MockitoExtension; import java.lang.reflect.Field; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; -@RunWith(MockitoJUnitRunner.class) -public class NacosAbilityManagerHolderTest { +@ExtendWith(MockitoExtension.class) +class NacosAbilityManagerHolderTest { - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { NacosAbilityManagerHolder.getInstance(); } - @After - public void tearDown() throws Exception { - Field abilityControlManagerField = NacosAbilityManagerHolder.class - .getDeclaredField("abstractAbilityControlManager"); + @AfterEach + void tearDown() throws Exception { + Field abilityControlManagerField = NacosAbilityManagerHolder.class.getDeclaredField("abstractAbilityControlManager"); abilityControlManagerField.setAccessible(true); abilityControlManagerField.set(null, null); } @Test - public void testGetInstance() { + void testGetInstance() { assertNotNull(NacosAbilityManagerHolder.getInstance()); } @Test - public void testGetInstanceByType() { + void testGetInstanceByType() { assertNotNull(NacosAbilityManagerHolder.getInstance(HigherMockAbilityManager.class)); } - @Test(expected = ClassCastException.class) - public void testGetInstanceByWrongType() { - assertNotNull(NacosAbilityManagerHolder.getInstance(LowerMockAbilityManager.class)); + @Test + void testGetInstanceByWrongType() { + assertThrows(ClassCastException.class, () -> { + assertNotNull(NacosAbilityManagerHolder.getInstance(LowerMockAbilityManager.class)); + }); } } \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/cache/builder/CacheBuilderTest.java b/common/src/test/java/com/alibaba/nacos/common/cache/builder/CacheBuilderTest.java index ad7f31c80d3..0a7ea25196d 100644 --- a/common/src/test/java/com/alibaba/nacos/common/cache/builder/CacheBuilderTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/cache/builder/CacheBuilderTest.java @@ -16,43 +16,45 @@ package com.alibaba.nacos.common.cache.builder; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; -public class CacheBuilderTest { - - @Rule - public ExpectedException exception = ExpectedException.none(); +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class CacheBuilderTest { @Test - public void testNegativeDuration() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("duration cannot be negative"); - CacheBuilder.builder().expireNanos(-1, TimeUnit.MINUTES).build(); + void testNegativeDuration() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + CacheBuilder.builder().expireNanos(-1, TimeUnit.MINUTES).build(); + }); + assertTrue(exception.getMessage().contains("duration cannot be negative")); } @Test - public void testNullTimeUnit() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("unit cannot be null"); - CacheBuilder.builder().expireNanos(500, null).build(); + void testNullTimeUnit() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + CacheBuilder.builder().expireNanos(500, null).build(); + }); + assertTrue(exception.getMessage().contains("unit cannot be null")); } @Test - public void testNegativeMaximumSize() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("size cannot be negative"); - CacheBuilder.builder().maximumSize(-1).build(); + void testNegativeMaximumSize() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + CacheBuilder.builder().maximumSize(-1).build(); + }); + assertTrue(exception.getMessage().contains("size cannot be negative")); } @Test - public void testNegativeInitializeCapacity() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("initializeCapacity cannot be negative"); - CacheBuilder.builder().initializeCapacity(-1).build(); + void testNegativeInitializeCapacity() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + CacheBuilder.builder().initializeCapacity(-1).build(); + }); + assertTrue(exception.getMessage().contains("initializeCapacity cannot be negative")); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/cache/decorators/AutoExpireCacheTest.java b/common/src/test/java/com/alibaba/nacos/common/cache/decorators/AutoExpireCacheTest.java index a75b70c98c1..92d9118cdee 100644 --- a/common/src/test/java/com/alibaba/nacos/common/cache/decorators/AutoExpireCacheTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/cache/decorators/AutoExpireCacheTest.java @@ -18,47 +18,51 @@ import com.alibaba.nacos.common.cache.Cache; import com.alibaba.nacos.common.cache.builder.CacheBuilder; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + /** * auto expire cache test. + * * @author zzq * @date 2021/8/1 */ -public class AutoExpireCacheTest { +class AutoExpireCacheTest { @Test - public void testBasic() throws Exception { + void testBasic() throws Exception { Cache cache = CacheBuilder.builder().expireNanos(10, TimeUnit.MINUTES).build(); IntStream.range(0, 100).forEach(item -> cache.put(item, item)); - Assert.assertEquals(100, cache.getSize()); - Assert.assertEquals(99, cache.get(99)); - Assert.assertEquals(99, cache.get(99, () -> 100)); + assertEquals(100, cache.getSize()); + assertEquals(99, cache.get(99)); + assertEquals(99, cache.get(99, () -> 100)); Object removed = cache.remove(99); - Assert.assertEquals(99, removed); - Assert.assertEquals(99, cache.getSize()); - Assert.assertEquals(100, cache.get(99, () -> 100)); + assertEquals(99, removed); + assertEquals(99, cache.getSize()); + assertEquals(100, cache.get(99, () -> 100)); cache.clear(); - Assert.assertEquals(0, cache.getSize()); + assertEquals(0, cache.getSize()); } - + @Test - public void testExpire() throws Exception { + void testExpire() throws Exception { Cache cache = CacheBuilder.builder().expireNanos(1, TimeUnit.SECONDS).build(); - cache.put("a", "a"); + cache.put("a", "a"); TimeUnit.SECONDS.sleep(2); - Assert.assertNull(cache.get("a")); + assertNull(cache.get("a")); } - + @Test - public void testGetCache() { + void testGetCache() { Cache cache = CacheBuilder.builder().expireNanos(1, TimeUnit.MINUTES).build(); cache.put("test", "test"); - Assert.assertNotNull(cache.get("test")); - Assert.assertNull(cache.get("test2")); + assertNotNull(cache.get("test")); + assertNull(cache.get("test2")); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/cache/decorators/LruCacheTest.java b/common/src/test/java/com/alibaba/nacos/common/cache/decorators/LruCacheTest.java index bda3b3bbe10..4dbc82cfc05 100644 --- a/common/src/test/java/com/alibaba/nacos/common/cache/decorators/LruCacheTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/cache/decorators/LruCacheTest.java @@ -18,39 +18,42 @@ import com.alibaba.nacos.common.cache.Cache; import com.alibaba.nacos.common.cache.builder.CacheBuilder; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.stream.IntStream; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + /** * lru test . + * * @author zzq * @date 2021/7/30 */ -public class LruCacheTest { - +class LruCacheTest { + @Test - public void testBasic() throws Exception { + void testBasic() throws Exception { int capacity = 10; int start = 0; int end = 99; Cache cache = CacheBuilder.builder().maximumSize(capacity).lru(true).build(); IntStream.range(start, end).forEach(item -> cache.put(item, item)); - Assert.assertEquals(capacity, cache.getSize()); - Assert.assertNull(cache.get(start)); - Assert.assertEquals(89, cache.get(89)); - Assert.assertEquals(94, cache.get(94)); - Assert.assertEquals(94, cache.get(94, () -> 100)); + assertEquals(capacity, cache.getSize()); + assertNull(cache.get(start)); + assertEquals(89, cache.get(89)); + assertEquals(94, cache.get(94)); + assertEquals(94, cache.get(94, () -> 100)); Object removed = cache.remove(98); - Assert.assertEquals(98, removed); - Assert.assertEquals(9, cache.getSize()); + assertEquals(98, removed); + assertEquals(9, cache.getSize()); cache.clear(); - Assert.assertEquals(0, cache.getSize()); + assertEquals(0, cache.getSize()); } - + @Test - public void testLru() { + void testLru() { int capacity = 10; int start = 0; int end = 10; @@ -58,7 +61,7 @@ public void testLru() { IntStream.range(start, end).forEach(item -> cache.put(item, item)); IntStream.range(start, 2).forEach(item -> cache.get(0)); cache.put(100, 100); - Assert.assertEquals(start, cache.get(0)); - Assert.assertNull(cache.get(1)); + assertEquals(start, cache.get(0)); + assertNull(cache.get(1)); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/cache/decorators/SynchronizedCacheTest.java b/common/src/test/java/com/alibaba/nacos/common/cache/decorators/SynchronizedCacheTest.java index c5a4fee35d6..d082d91b6b4 100644 --- a/common/src/test/java/com/alibaba/nacos/common/cache/decorators/SynchronizedCacheTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/cache/decorators/SynchronizedCacheTest.java @@ -18,26 +18,27 @@ import com.alibaba.nacos.common.cache.Cache; import com.alibaba.nacos.common.cache.builder.CacheBuilder; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.stream.IntStream; -public class SynchronizedCacheTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SynchronizedCacheTest { @Test - public void testSync() throws Exception { + void testSync() throws Exception { Cache cache = CacheBuilder.builder().sync(true).build(); IntStream.range(0, 100).forEach(item -> cache.put(item, item)); - Assert.assertEquals(100, cache.getSize()); - Assert.assertEquals(99, cache.get(99)); - Assert.assertEquals(99, cache.get(99, () -> 100)); + assertEquals(100, cache.getSize()); + assertEquals(99, cache.get(99)); + assertEquals(99, cache.get(99, () -> 100)); Object removed = cache.remove(99); - Assert.assertEquals(99, removed); - Assert.assertEquals(99, cache.getSize()); - Assert.assertEquals(100, cache.get(99, () -> 100)); + assertEquals(99, removed); + assertEquals(99, cache.getSize()); + assertEquals(100, cache.get(99, () -> 100)); cache.clear(); - Assert.assertEquals(0, cache.getSize()); + assertEquals(0, cache.getSize()); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/cache/impl/SimpleCacheTest.java b/common/src/test/java/com/alibaba/nacos/common/cache/impl/SimpleCacheTest.java index 396bb9a9edf..53634a6bb8c 100644 --- a/common/src/test/java/com/alibaba/nacos/common/cache/impl/SimpleCacheTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/cache/impl/SimpleCacheTest.java @@ -18,27 +18,29 @@ import com.alibaba.nacos.common.cache.Cache; import com.alibaba.nacos.common.cache.builder.CacheBuilder; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.stream.IntStream; -public class SimpleCacheTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +class SimpleCacheTest { + @Test - public void test() throws Exception { + void test() throws Exception { Cache cache = CacheBuilder.builder().initializeCapacity(100).build(); IntStream.range(0, 100).forEach(item -> cache.put(item, item)); - Assert.assertEquals(100, cache.getSize()); + assertEquals(100, cache.getSize()); Object item = cache.remove(89); - Assert.assertEquals(89, item); - Assert.assertEquals(99, cache.getSize()); - Assert.assertEquals(null, cache.get(89)); - Assert.assertEquals(99, cache.get(99)); - Assert.assertEquals(99, cache.get(99, () -> 99999)); - Assert.assertEquals(87, cache.get(111, () -> 87)); + assertEquals(89, item); + assertEquals(99, cache.getSize()); + assertNull(cache.get(89)); + assertEquals(99, cache.get(99)); + assertEquals(99, cache.get(99, () -> 99999)); + assertEquals(87, cache.get(111, () -> 87)); cache.clear(); - Assert.assertEquals(0, cache.getSize()); + assertEquals(0, cache.getSize()); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/codec/Base64Test.java b/common/src/test/java/com/alibaba/nacos/common/codec/Base64Test.java index accdd7fe4cd..fbe92dd8aaf 100644 --- a/common/src/test/java/com/alibaba/nacos/common/codec/Base64Test.java +++ b/common/src/test/java/com/alibaba/nacos/common/codec/Base64Test.java @@ -16,81 +16,86 @@ package com.alibaba.nacos.common.codec; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.nio.charset.StandardCharsets; -public class Base64Test { +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 Base64Test { @Test - public void test() { + void test() { String origin = "nacos"; String encoded = "bmFjb3M="; byte[] encodeBase64 = Base64.encodeBase64(origin.getBytes(StandardCharsets.UTF_8)); - Assert.assertEquals(encoded, new String(encodeBase64)); + assertEquals(encoded, new String(encodeBase64)); byte[] decodeBase64 = Base64.decodeBase64(encoded.getBytes(StandardCharsets.UTF_8)); - Assert.assertEquals(origin, new String(decodeBase64)); + assertEquals(origin, new String(decodeBase64)); } @Test - public void testEncodeNullOrEmpty() { + void testEncodeNullOrEmpty() { byte[] b1 = Base64.encodeBase64(null); - Assert.assertNull(b1); + assertNull(b1); byte[] b2 = Base64.encodeBase64(new byte[] {}); - Assert.assertEquals(0, b2.length); + assertEquals(0, b2.length); } @Test - public void testDecodeNullOrEmpty() { + void testDecodeNullOrEmpty() { byte[] b1 = Base64.decodeBase64(null); - Assert.assertNull(b1); + assertNull(b1); byte[] b2 = Base64.decodeBase64(new byte[] {}); - Assert.assertEquals(0, b2.length); + assertEquals(0, b2.length); } @Test - public void testChunk() { + void testChunk() { String a = "very large characters to test chunk encoding and see if the result is expected or not"; byte[] b1 = Base64.encodeBase64(a.getBytes(StandardCharsets.UTF_8), false, false, Integer.MAX_VALUE); byte[] b2 = Base64.encodeBase64(a.getBytes(StandardCharsets.UTF_8), true, false, Integer.MAX_VALUE); String s1 = new String(b1); String s2 = new String(b2); - Assert.assertEquals(s1, "dmVyeSBsYXJnZSBjaGFyYWN0ZXJzIHRvIHRlc3QgY2h1bmsgZW5jb2RpbmcgYW5kIHNlZSBpZiB0" + assertEquals(s1, "dmVyeSBsYXJnZSBjaGFyYWN0ZXJzIHRvIHRlc3QgY2h1bmsgZW5jb2RpbmcgYW5kIHNlZSBpZiB0" + "aGUgcmVzdWx0IGlzIGV4cGVjdGVkIG9yIG5vdA=="); - Assert.assertEquals(s2, "dmVyeSBsYXJnZSBjaGFyYWN0ZXJzIHRvIHRlc3QgY2h1bmsgZW5jb2RpbmcgYW5kIHNlZSBpZiB0" + "\r\n" + assertEquals(s2, "dmVyeSBsYXJnZSBjaGFyYWN0ZXJzIHRvIHRlc3QgY2h1bmsgZW5jb2RpbmcgYW5kIHNlZSBpZiB0" + "\r\n" + "aGUgcmVzdWx0IGlzIGV4cGVjdGVkIG9yIG5vdA==" + "\r\n"); - + byte[] c1 = Base64.decodeBase64(b1); byte[] c2 = Base64.decodeBase64(b2); String s3 = new String(c1); String s4 = new String(c2); - Assert.assertEquals(a, s3); - Assert.assertEquals(a, s4); + assertEquals(a, s3); + assertEquals(a, s4); } @Test - public void testUrlSafe() { + void testUrlSafe() { String a = "aa~aa?"; byte[] b1 = Base64.encodeBase64(a.getBytes(StandardCharsets.UTF_8), false, false, Integer.MAX_VALUE); byte[] b2 = Base64.encodeBase64(a.getBytes(StandardCharsets.UTF_8), false, true, Integer.MAX_VALUE); String s1 = new String(b1); String s2 = new String(b2); - Assert.assertEquals("YWF+YWE/", s1); - Assert.assertEquals("YWF-YWE_", s2); + assertEquals("YWF+YWE/", s1); + assertEquals("YWF-YWE_", s2); byte[] c1 = Base64.decodeBase64(b1); byte[] c2 = Base64.decodeBase64(b2); String s3 = new String(c1); String s4 = new String(c2); - Assert.assertEquals("aa~aa?", s3); - Assert.assertEquals("aa~aa?", s4); + assertEquals("aa~aa?", s3); + assertEquals("aa~aa?", s4); } - @Test(expected = IllegalArgumentException.class) - public void testEncodeOverMaxLength() { - String a = "very large characters to test chunk encoding and see if the result is expected or not"; - Base64.encodeBase64(a.getBytes(StandardCharsets.UTF_8), false, false, 10); + @Test + void testEncodeOverMaxLength() { + assertThrows(IllegalArgumentException.class, () -> { + String a = "very large characters to test chunk encoding and see if the result is expected or not"; + Base64.encodeBase64(a.getBytes(StandardCharsets.UTF_8), false, false, 10); + }); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/event/ServerConfigChangeEventTest.java b/common/src/test/java/com/alibaba/nacos/common/event/ServerConfigChangeEventTest.java index e3d8ee681cc..11925b0efe2 100644 --- a/common/src/test/java/com/alibaba/nacos/common/event/ServerConfigChangeEventTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/event/ServerConfigChangeEventTest.java @@ -17,14 +17,15 @@ package com.alibaba.nacos.common.event; import com.alibaba.nacos.common.notify.Event; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ServerConfigChangeEventTest { +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ServerConfigChangeEventTest { @Test - public void test() { + void test() { Event event = ServerConfigChangeEvent.newEvent(); - Assert.assertTrue(event instanceof ServerConfigChangeEvent); + assertTrue(event instanceof ServerConfigChangeEvent); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/executor/ExecutorFactoryTest.java b/common/src/test/java/com/alibaba/nacos/common/executor/ExecutorFactoryTest.java index c8ee903cbfc..5d2fb47d5b1 100644 --- a/common/src/test/java/com/alibaba/nacos/common/executor/ExecutorFactoryTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/executor/ExecutorFactoryTest.java @@ -16,8 +16,7 @@ package com.alibaba.nacos.common.executor; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Map; import java.util.Set; @@ -25,67 +24,71 @@ import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor; -public class ExecutorFactoryTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ExecutorFactoryTest { private final NameThreadFactory threadFactory = new NameThreadFactory("test"); @Test - public void test() { + void test() { ExecutorService executorService; ThreadPoolExecutor threadPoolExecutor; executorService = ExecutorFactory.newSingleExecutorService(); - Assert.assertTrue(executorService instanceof ThreadPoolExecutor); + assertTrue(executorService instanceof ThreadPoolExecutor); threadPoolExecutor = (ThreadPoolExecutor) executorService; - Assert.assertEquals(1, threadPoolExecutor.getCorePoolSize()); - Assert.assertEquals(1, threadPoolExecutor.getMaximumPoolSize()); - Assert.assertNotEquals(threadFactory, threadPoolExecutor.getThreadFactory()); + assertEquals(1, threadPoolExecutor.getCorePoolSize()); + assertEquals(1, threadPoolExecutor.getMaximumPoolSize()); + assertNotEquals(threadFactory, threadPoolExecutor.getThreadFactory()); executorService = ExecutorFactory.newFixedExecutorService(10); - Assert.assertTrue(executorService instanceof ThreadPoolExecutor); + assertTrue(executorService instanceof ThreadPoolExecutor); threadPoolExecutor = (ThreadPoolExecutor) executorService; - Assert.assertEquals(10, threadPoolExecutor.getCorePoolSize()); - Assert.assertEquals(10, threadPoolExecutor.getMaximumPoolSize()); - Assert.assertNotEquals(threadFactory, threadPoolExecutor.getThreadFactory()); + assertEquals(10, threadPoolExecutor.getCorePoolSize()); + assertEquals(10, threadPoolExecutor.getMaximumPoolSize()); + assertNotEquals(threadFactory, threadPoolExecutor.getThreadFactory()); executorService = ExecutorFactory.newSingleExecutorService(threadFactory); - Assert.assertTrue(executorService instanceof ThreadPoolExecutor); + assertTrue(executorService instanceof ThreadPoolExecutor); threadPoolExecutor = (ThreadPoolExecutor) executorService; - Assert.assertEquals(1, threadPoolExecutor.getCorePoolSize()); - Assert.assertEquals(1, threadPoolExecutor.getMaximumPoolSize()); - Assert.assertEquals(threadFactory, threadPoolExecutor.getThreadFactory()); + assertEquals(1, threadPoolExecutor.getCorePoolSize()); + assertEquals(1, threadPoolExecutor.getMaximumPoolSize()); + assertEquals(threadFactory, threadPoolExecutor.getThreadFactory()); executorService = ExecutorFactory.newFixedExecutorService(10, threadFactory); - Assert.assertTrue(executorService instanceof ThreadPoolExecutor); + assertTrue(executorService instanceof ThreadPoolExecutor); threadPoolExecutor = (ThreadPoolExecutor) executorService; - Assert.assertEquals(10, threadPoolExecutor.getCorePoolSize()); - Assert.assertEquals(10, threadPoolExecutor.getMaximumPoolSize()); - Assert.assertEquals(threadFactory, threadPoolExecutor.getThreadFactory()); - + assertEquals(10, threadPoolExecutor.getCorePoolSize()); + assertEquals(10, threadPoolExecutor.getMaximumPoolSize()); + assertEquals(threadFactory, threadPoolExecutor.getThreadFactory()); + ScheduledThreadPoolExecutor scheduledThreadPoolExecutor; executorService = ExecutorFactory.newSingleScheduledExecutorService(threadFactory); - Assert.assertTrue(executorService instanceof ScheduledThreadPoolExecutor); + assertTrue(executorService instanceof ScheduledThreadPoolExecutor); scheduledThreadPoolExecutor = (ScheduledThreadPoolExecutor) executorService; - Assert.assertEquals(1, scheduledThreadPoolExecutor.getCorePoolSize()); - Assert.assertEquals(Integer.MAX_VALUE, scheduledThreadPoolExecutor.getMaximumPoolSize()); - Assert.assertEquals(threadFactory, threadPoolExecutor.getThreadFactory()); + assertEquals(1, scheduledThreadPoolExecutor.getCorePoolSize()); + assertEquals(Integer.MAX_VALUE, scheduledThreadPoolExecutor.getMaximumPoolSize()); + assertEquals(threadFactory, threadPoolExecutor.getThreadFactory()); executorService = ExecutorFactory.newScheduledExecutorService(10, threadFactory); - Assert.assertTrue(executorService instanceof ScheduledThreadPoolExecutor); + assertTrue(executorService instanceof ScheduledThreadPoolExecutor); scheduledThreadPoolExecutor = (ScheduledThreadPoolExecutor) executorService; - Assert.assertEquals(10, scheduledThreadPoolExecutor.getCorePoolSize()); - Assert.assertEquals(Integer.MAX_VALUE, scheduledThreadPoolExecutor.getMaximumPoolSize()); - Assert.assertEquals(threadFactory, threadPoolExecutor.getThreadFactory()); + assertEquals(10, scheduledThreadPoolExecutor.getCorePoolSize()); + assertEquals(Integer.MAX_VALUE, scheduledThreadPoolExecutor.getMaximumPoolSize()); + assertEquals(threadFactory, threadPoolExecutor.getThreadFactory()); threadPoolExecutor = ExecutorFactory.newCustomerThreadExecutor(10, 20, 1000, threadFactory); - Assert.assertEquals(10, threadPoolExecutor.getCorePoolSize()); - Assert.assertEquals(20, threadPoolExecutor.getMaximumPoolSize()); - Assert.assertEquals(threadFactory, threadPoolExecutor.getThreadFactory()); + assertEquals(10, threadPoolExecutor.getCorePoolSize()); + assertEquals(20, threadPoolExecutor.getMaximumPoolSize()); + assertEquals(threadFactory, threadPoolExecutor.getThreadFactory()); } @Test - public void testManaged() { + void testManaged() { String testGroup = "test"; ExecutorService executorService; ThreadPoolExecutor threadPoolExecutor; @@ -93,59 +96,59 @@ public void testManaged() { final Map>> resourcesManager = manager.getResourcesManager(); executorService = ExecutorFactory.Managed.newSingleExecutorService(testGroup); - Assert.assertTrue(executorService instanceof ThreadPoolExecutor); + assertTrue(executorService instanceof ThreadPoolExecutor); threadPoolExecutor = (ThreadPoolExecutor) executorService; - Assert.assertEquals(1, threadPoolExecutor.getCorePoolSize()); - Assert.assertEquals(1, threadPoolExecutor.getMaximumPoolSize()); - Assert.assertNotEquals(threadFactory, threadPoolExecutor.getThreadFactory()); - Assert.assertEquals(1, resourcesManager.get("nacos").get(testGroup).size()); + assertEquals(1, threadPoolExecutor.getCorePoolSize()); + assertEquals(1, threadPoolExecutor.getMaximumPoolSize()); + assertNotEquals(threadFactory, threadPoolExecutor.getThreadFactory()); + assertEquals(1, resourcesManager.get("nacos").get(testGroup).size()); executorService = ExecutorFactory.Managed.newFixedExecutorService(testGroup, 10); - Assert.assertTrue(executorService instanceof ThreadPoolExecutor); + assertTrue(executorService instanceof ThreadPoolExecutor); threadPoolExecutor = (ThreadPoolExecutor) executorService; - Assert.assertEquals(10, threadPoolExecutor.getCorePoolSize()); - Assert.assertEquals(10, threadPoolExecutor.getMaximumPoolSize()); - Assert.assertNotEquals(threadFactory, threadPoolExecutor.getThreadFactory()); - Assert.assertEquals(2, resourcesManager.get("nacos").get(testGroup).size()); + assertEquals(10, threadPoolExecutor.getCorePoolSize()); + assertEquals(10, threadPoolExecutor.getMaximumPoolSize()); + assertNotEquals(threadFactory, threadPoolExecutor.getThreadFactory()); + assertEquals(2, resourcesManager.get("nacos").get(testGroup).size()); executorService = ExecutorFactory.Managed.newSingleExecutorService(testGroup, threadFactory); - Assert.assertTrue(executorService instanceof ThreadPoolExecutor); + assertTrue(executorService instanceof ThreadPoolExecutor); threadPoolExecutor = (ThreadPoolExecutor) executorService; - Assert.assertEquals(1, threadPoolExecutor.getCorePoolSize()); - Assert.assertEquals(1, threadPoolExecutor.getMaximumPoolSize()); - Assert.assertEquals(threadFactory, threadPoolExecutor.getThreadFactory()); - Assert.assertEquals(3, resourcesManager.get("nacos").get(testGroup).size()); + assertEquals(1, threadPoolExecutor.getCorePoolSize()); + assertEquals(1, threadPoolExecutor.getMaximumPoolSize()); + assertEquals(threadFactory, threadPoolExecutor.getThreadFactory()); + assertEquals(3, resourcesManager.get("nacos").get(testGroup).size()); executorService = ExecutorFactory.Managed.newFixedExecutorService(testGroup, 10, threadFactory); - Assert.assertTrue(executorService instanceof ThreadPoolExecutor); + assertTrue(executorService instanceof ThreadPoolExecutor); threadPoolExecutor = (ThreadPoolExecutor) executorService; - Assert.assertEquals(10, threadPoolExecutor.getCorePoolSize()); - Assert.assertEquals(10, threadPoolExecutor.getMaximumPoolSize()); - Assert.assertEquals(threadFactory, threadPoolExecutor.getThreadFactory()); - Assert.assertEquals(4, resourcesManager.get("nacos").get(testGroup).size()); - + assertEquals(10, threadPoolExecutor.getCorePoolSize()); + assertEquals(10, threadPoolExecutor.getMaximumPoolSize()); + assertEquals(threadFactory, threadPoolExecutor.getThreadFactory()); + assertEquals(4, resourcesManager.get("nacos").get(testGroup).size()); + ScheduledThreadPoolExecutor scheduledThreadPoolExecutor; executorService = ExecutorFactory.Managed.newSingleScheduledExecutorService(testGroup, threadFactory); - Assert.assertTrue(executorService instanceof ScheduledThreadPoolExecutor); + assertTrue(executorService instanceof ScheduledThreadPoolExecutor); scheduledThreadPoolExecutor = (ScheduledThreadPoolExecutor) executorService; - Assert.assertEquals(1, scheduledThreadPoolExecutor.getCorePoolSize()); - Assert.assertEquals(Integer.MAX_VALUE, scheduledThreadPoolExecutor.getMaximumPoolSize()); - Assert.assertEquals(threadFactory, threadPoolExecutor.getThreadFactory()); - Assert.assertEquals(5, resourcesManager.get("nacos").get(testGroup).size()); + assertEquals(1, scheduledThreadPoolExecutor.getCorePoolSize()); + assertEquals(Integer.MAX_VALUE, scheduledThreadPoolExecutor.getMaximumPoolSize()); + assertEquals(threadFactory, threadPoolExecutor.getThreadFactory()); + assertEquals(5, resourcesManager.get("nacos").get(testGroup).size()); executorService = ExecutorFactory.Managed.newScheduledExecutorService(testGroup, 10, threadFactory); - Assert.assertTrue(executorService instanceof ScheduledThreadPoolExecutor); + assertTrue(executorService instanceof ScheduledThreadPoolExecutor); scheduledThreadPoolExecutor = (ScheduledThreadPoolExecutor) executorService; - Assert.assertEquals(10, scheduledThreadPoolExecutor.getCorePoolSize()); - Assert.assertEquals(Integer.MAX_VALUE, scheduledThreadPoolExecutor.getMaximumPoolSize()); - Assert.assertEquals(threadFactory, threadPoolExecutor.getThreadFactory()); - Assert.assertEquals(6, resourcesManager.get("nacos").get(testGroup).size()); + assertEquals(10, scheduledThreadPoolExecutor.getCorePoolSize()); + assertEquals(Integer.MAX_VALUE, scheduledThreadPoolExecutor.getMaximumPoolSize()); + assertEquals(threadFactory, threadPoolExecutor.getThreadFactory()); + assertEquals(6, resourcesManager.get("nacos").get(testGroup).size()); threadPoolExecutor = ExecutorFactory.Managed.newCustomerThreadExecutor(testGroup, 10, 20, 1000, threadFactory); - Assert.assertEquals(10, threadPoolExecutor.getCorePoolSize()); - Assert.assertEquals(20, threadPoolExecutor.getMaximumPoolSize()); - Assert.assertEquals(threadFactory, threadPoolExecutor.getThreadFactory()); - Assert.assertEquals(7, resourcesManager.get("nacos").get(testGroup).size()); + assertEquals(10, threadPoolExecutor.getCorePoolSize()); + assertEquals(20, threadPoolExecutor.getMaximumPoolSize()); + assertEquals(threadFactory, threadPoolExecutor.getThreadFactory()); + assertEquals(7, resourcesManager.get("nacos").get(testGroup).size()); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/executor/NameThreadFactoryTest.java b/common/src/test/java/com/alibaba/nacos/common/executor/NameThreadFactoryTest.java index 82a1b80fa3d..de7e6e28be6 100644 --- a/common/src/test/java/com/alibaba/nacos/common/executor/NameThreadFactoryTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/executor/NameThreadFactoryTest.java @@ -16,13 +16,14 @@ package com.alibaba.nacos.common.executor; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class NameThreadFactoryTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class NameThreadFactoryTest { @Test - public void test() { + void test() { NameThreadFactory threadFactory = new NameThreadFactory("test"); Thread t1 = threadFactory.newThread(() -> { @@ -31,8 +32,8 @@ public void test() { }); - Assert.assertEquals(t1.getName(), "test.0"); - Assert.assertEquals(t2.getName(), "test.1"); + assertEquals("test.0", t1.getName()); + assertEquals("test.1", t2.getName()); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/executor/ThreadPoolManagerTest.java b/common/src/test/java/com/alibaba/nacos/common/executor/ThreadPoolManagerTest.java index dbdbf6d37b7..b9ab6baa0ea 100644 --- a/common/src/test/java/com/alibaba/nacos/common/executor/ThreadPoolManagerTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/executor/ThreadPoolManagerTest.java @@ -16,17 +16,18 @@ package com.alibaba.nacos.common.executor; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.ExecutorService; -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 ThreadPoolManagerTest { +class ThreadPoolManagerTest { @Test - public void test() { + void test() { ThreadPoolManager manager = ThreadPoolManager.getInstance(); ExecutorService executor = ExecutorFactory.newSingleExecutorService(); String namespace = "test"; @@ -34,41 +35,41 @@ public void test() { manager.register(namespace, group, executor); assertTrue(manager.getResourcesManager().containsKey(namespace)); - Assert.assertEquals(1, manager.getResourcesManager().get(namespace).get(group).size()); + assertEquals(1, manager.getResourcesManager().get(namespace).get(group).size()); manager.register(namespace, group, ExecutorFactory.newSingleExecutorService()); - Assert.assertEquals(2, manager.getResourcesManager().get(namespace).get(group).size()); + assertEquals(2, manager.getResourcesManager().get(namespace).get(group).size()); manager.destroy(namespace, group); - Assert.assertFalse(manager.getResourcesManager().get(namespace).containsKey(group)); + assertFalse(manager.getResourcesManager().get(namespace).containsKey(group)); manager.register(namespace, group, executor); manager.destroy(namespace); - Assert.assertFalse(manager.getResourcesManager().containsKey(namespace)); + assertFalse(manager.getResourcesManager().containsKey(namespace)); manager.register(namespace, group, executor); manager.deregister(namespace, group, ExecutorFactory.newSingleExecutorService()); - Assert.assertEquals(1, manager.getResourcesManager().get(namespace).get(group).size()); + assertEquals(1, manager.getResourcesManager().get(namespace).get(group).size()); manager.deregister(namespace, group, executor); - Assert.assertEquals(0, manager.getResourcesManager().get(namespace).get(group).size()); + assertEquals(0, manager.getResourcesManager().get(namespace).get(group).size()); manager.register(namespace, group, executor); manager.deregister(namespace, group); - Assert.assertFalse(manager.getResourcesManager().get(namespace).containsKey(group)); + assertFalse(manager.getResourcesManager().get(namespace).containsKey(group)); manager.register(namespace, group, executor); manager.register(namespace, group, ExecutorFactory.newSingleExecutorService()); ThreadPoolManager.shutdown(); - Assert.assertFalse(manager.getResourcesManager().containsKey(namespace)); + assertFalse(manager.getResourcesManager().containsKey(namespace)); manager.destroy(namespace); manager.destroy(namespace, group); - Assert.assertFalse(manager.getResourcesManager().containsKey(namespace)); + assertFalse(manager.getResourcesManager().containsKey(namespace)); } @Test - public void testDestroyWithNull() { + void testDestroyWithNull() { ThreadPoolManager.getInstance().register("t", "g", ExecutorFactory.newFixedExecutorService(1)); try { ThreadPoolManager.getInstance().destroy("null"); diff --git a/common/src/test/java/com/alibaba/nacos/common/http/AbstractApacheHttpClientFactoryTest.java b/common/src/test/java/com/alibaba/nacos/common/http/AbstractApacheHttpClientFactoryTest.java index 97d0cbea3fd..3ba7f83117c 100644 --- a/common/src/test/java/com/alibaba/nacos/common/http/AbstractApacheHttpClientFactoryTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/http/AbstractApacheHttpClientFactoryTest.java @@ -19,35 +19,35 @@ import com.alibaba.nacos.common.http.client.NacosRestTemplate; import com.alibaba.nacos.common.http.client.request.DefaultHttpClientRequest; import com.alibaba.nacos.common.http.client.request.HttpClientRequest; -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 org.slf4j.Logger; import java.lang.reflect.Field; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -@RunWith(MockitoJUnitRunner.class) -public class AbstractApacheHttpClientFactoryTest { +@ExtendWith(MockitoExtension.class) +class AbstractApacheHttpClientFactoryTest { @Mock private Logger logger; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { } @Test - public void testCreateNacosRestTemplate() throws NoSuchFieldException, IllegalAccessException { + void testCreateNacosRestTemplate() throws NoSuchFieldException, IllegalAccessException { HttpClientFactory factory = new AbstractApacheHttpClientFactory() { @Override protected HttpClientConfig buildHttpClientConfig() { diff --git a/common/src/test/java/com/alibaba/nacos/common/http/AbstractHttpClientFactoryTest.java b/common/src/test/java/com/alibaba/nacos/common/http/AbstractHttpClientFactoryTest.java index a934241d055..0cdefebac71 100644 --- a/common/src/test/java/com/alibaba/nacos/common/http/AbstractHttpClientFactoryTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/http/AbstractHttpClientFactoryTest.java @@ -19,28 +19,28 @@ import com.alibaba.nacos.common.http.client.NacosAsyncRestTemplate; import com.alibaba.nacos.common.http.client.NacosRestTemplate; import com.alibaba.nacos.common.tls.TlsSystemConfig; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +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.slf4j.Logger; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; -@RunWith(MockitoJUnitRunner.class) -public class AbstractHttpClientFactoryTest { +@ExtendWith(MockitoExtension.class) +class AbstractHttpClientFactoryTest { @Mock private Logger logger; - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { TlsSystemConfig.tlsEnable = false; } @Test - public void testCreateNacosRestTemplateWithSsl() throws Exception { + void testCreateNacosRestTemplateWithSsl() throws Exception { TlsSystemConfig.tlsEnable = true; HttpClientFactory httpClientFactory = new DefaultHttpClientFactory(logger); NacosRestTemplate nacosRestTemplate = httpClientFactory.createNacosRestTemplate(); @@ -48,7 +48,7 @@ public void testCreateNacosRestTemplateWithSsl() throws Exception { } @Test - public void testCreateNacosAsyncRestTemplate() { + void testCreateNacosAsyncRestTemplate() { HttpClientFactory httpClientFactory = new AbstractHttpClientFactory() { @Override protected HttpClientConfig buildHttpClientConfig() { diff --git a/common/src/test/java/com/alibaba/nacos/common/http/BaseHttpMethodTest.java b/common/src/test/java/com/alibaba/nacos/common/http/BaseHttpMethodTest.java index 612b561b1dc..df7204fd852 100644 --- a/common/src/test/java/com/alibaba/nacos/common/http/BaseHttpMethodTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/http/BaseHttpMethodTest.java @@ -17,89 +17,93 @@ package com.alibaba.nacos.common.http; import org.apache.http.client.methods.HttpRequestBase; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class BaseHttpMethodTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class BaseHttpMethodTest { @Test - public void testHttpGet() { + void testHttpGet() { BaseHttpMethod method = BaseHttpMethod.GET; HttpRequestBase request = method.init("http://example.com"); - Assert.assertEquals("GET", request.getMethod()); + assertEquals("GET", request.getMethod()); } @Test - public void testHttpGetLarge() { + void testHttpGetLarge() { BaseHttpMethod method = BaseHttpMethod.GET_LARGE; HttpRequestBase request = method.init("http://example.com"); - Assert.assertEquals("GET", request.getMethod()); + assertEquals("GET", request.getMethod()); } @Test - public void testHttpPost() { + void testHttpPost() { BaseHttpMethod method = BaseHttpMethod.POST; HttpRequestBase request = method.init("http://example.com"); - Assert.assertEquals("POST", request.getMethod()); + assertEquals("POST", request.getMethod()); } @Test - public void testHttpPut() { + void testHttpPut() { BaseHttpMethod method = BaseHttpMethod.PUT; HttpRequestBase request = method.init("http://example.com"); - Assert.assertEquals("PUT", request.getMethod()); + assertEquals("PUT", request.getMethod()); } @Test - public void testHttpDelete() { + void testHttpDelete() { BaseHttpMethod method = BaseHttpMethod.DELETE; HttpRequestBase request = method.init("http://example.com"); - Assert.assertEquals("DELETE", request.getMethod()); + assertEquals("DELETE", request.getMethod()); } @Test - public void testHttpDeleteLarge() { + void testHttpDeleteLarge() { BaseHttpMethod method = BaseHttpMethod.DELETE_LARGE; HttpRequestBase request = method.init("http://example.com"); - Assert.assertEquals("DELETE", request.getMethod()); + assertEquals("DELETE", request.getMethod()); } @Test - public void testHttpHead() { + void testHttpHead() { BaseHttpMethod method = BaseHttpMethod.HEAD; HttpRequestBase request = method.init("http://example.com"); - Assert.assertEquals("HEAD", request.getMethod()); + assertEquals("HEAD", request.getMethod()); } @Test - public void testHttpTrace() { + void testHttpTrace() { BaseHttpMethod method = BaseHttpMethod.TRACE; HttpRequestBase request = method.init("http://example.com"); - Assert.assertEquals("TRACE", request.getMethod()); + assertEquals("TRACE", request.getMethod()); } @Test - public void testHttpPatch() { + void testHttpPatch() { BaseHttpMethod method = BaseHttpMethod.PATCH; HttpRequestBase request = method.init("http://example.com"); - Assert.assertEquals("PATCH", request.getMethod()); + assertEquals("PATCH", request.getMethod()); } @Test - public void testHttpOptions() { + void testHttpOptions() { BaseHttpMethod method = BaseHttpMethod.OPTIONS; HttpRequestBase request = method.init("http://example.com"); - Assert.assertEquals("TRACE", request.getMethod()); + assertEquals("TRACE", request.getMethod()); } @Test - public void testSourceOf() { + void testSourceOf() { BaseHttpMethod method = BaseHttpMethod.sourceOf("GET"); - Assert.assertEquals(BaseHttpMethod.GET, method); + assertEquals(BaseHttpMethod.GET, method); } - @Test(expected = IllegalArgumentException.class) - public void testSourceOfNotFound() { - BaseHttpMethod.sourceOf("Not Found"); + @Test + void testSourceOfNotFound() { + assertThrows(IllegalArgumentException.class, () -> { + BaseHttpMethod.sourceOf("Not Found"); + }); } } \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/http/HttpClientBeanHolderTest.java b/common/src/test/java/com/alibaba/nacos/common/http/HttpClientBeanHolderTest.java index 18323a229a6..80172a70c48 100644 --- a/common/src/test/java/com/alibaba/nacos/common/http/HttpClientBeanHolderTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/http/HttpClientBeanHolderTest.java @@ -18,24 +18,29 @@ import com.alibaba.nacos.common.http.client.NacosAsyncRestTemplate; import com.alibaba.nacos.common.http.client.NacosRestTemplate; -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 org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.slf4j.Logger; import java.lang.reflect.Field; import java.util.HashMap; 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.when; -@RunWith(MockitoJUnitRunner.class) -public class HttpClientBeanHolderTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class HttpClientBeanHolderTest { private Map cachedRestTemplateMap; @@ -54,8 +59,8 @@ public class HttpClientBeanHolderTest { @Mock private HttpClientFactory mockFactory; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { cachedRestTemplateMap = new HashMap<>(); cachedAsyncRestTemplateMap = new HashMap<>(); restMap = (Map) getCachedMap("SINGLETON_REST"); @@ -68,8 +73,8 @@ public void setUp() throws Exception { when(mockFactory.createNacosAsyncRestTemplate()).thenReturn(mockAsyncRestTemplate); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { restMap.putAll(cachedRestTemplateMap); restAsyncMap.putAll(cachedAsyncRestTemplateMap); cachedRestTemplateMap.clear(); @@ -83,7 +88,7 @@ private Object getCachedMap(String mapName) throws NoSuchFieldException, Illegal } @Test - public void testGetNacosRestTemplateWithDefault() { + void testGetNacosRestTemplateWithDefault() { assertTrue(restMap.isEmpty()); NacosRestTemplate actual = HttpClientBeanHolder.getNacosRestTemplate((Logger) null); assertEquals(1, restMap.size()); @@ -92,13 +97,15 @@ public void testGetNacosRestTemplateWithDefault() { assertEquals(actual, duplicateGet); } - @Test(expected = NullPointerException.class) - public void testGetNacosRestTemplateForNullFactory() { - HttpClientBeanHolder.getNacosRestTemplate((HttpClientFactory) null); + @Test + void testGetNacosRestTemplateForNullFactory() { + assertThrows(NullPointerException.class, () -> { + HttpClientBeanHolder.getNacosRestTemplate((HttpClientFactory) null); + }); } @Test - public void testGetNacosRestTemplateWithCustomFactory() { + void testGetNacosRestTemplateWithCustomFactory() { assertTrue(restMap.isEmpty()); HttpClientBeanHolder.getNacosRestTemplate((Logger) null); assertEquals(1, restMap.size()); @@ -108,7 +115,7 @@ public void testGetNacosRestTemplateWithCustomFactory() { } @Test - public void testGetNacosAsyncRestTemplateWithDefault() { + void testGetNacosAsyncRestTemplateWithDefault() { assertTrue(restAsyncMap.isEmpty()); NacosAsyncRestTemplate actual = HttpClientBeanHolder.getNacosAsyncRestTemplate((Logger) null); assertEquals(1, restAsyncMap.size()); @@ -117,13 +124,15 @@ public void testGetNacosAsyncRestTemplateWithDefault() { assertEquals(actual, duplicateGet); } - @Test(expected = NullPointerException.class) - public void testGetNacosAsyncRestTemplateForNullFactory() { - HttpClientBeanHolder.getNacosAsyncRestTemplate((HttpClientFactory) null); + @Test + void testGetNacosAsyncRestTemplateForNullFactory() { + assertThrows(NullPointerException.class, () -> { + HttpClientBeanHolder.getNacosAsyncRestTemplate((HttpClientFactory) null); + }); } @Test - public void testGetNacosAsyncRestTemplateWithCustomFactory() { + void testGetNacosAsyncRestTemplateWithCustomFactory() { assertTrue(restAsyncMap.isEmpty()); HttpClientBeanHolder.getNacosAsyncRestTemplate((Logger) null); assertEquals(1, restAsyncMap.size()); @@ -133,7 +142,7 @@ public void testGetNacosAsyncRestTemplateWithCustomFactory() { } @Test - public void shutdown() throws Exception { + void shutdown() throws Exception { HttpClientBeanHolder.getNacosRestTemplate((Logger) null); HttpClientBeanHolder.getNacosAsyncRestTemplate((Logger) null); assertEquals(1, restMap.size()); diff --git a/common/src/test/java/com/alibaba/nacos/common/http/HttpClientConfigTest.java b/common/src/test/java/com/alibaba/nacos/common/http/HttpClientConfigTest.java index eaa44f3ab96..e94458d6cc2 100644 --- a/common/src/test/java/com/alibaba/nacos/common/http/HttpClientConfigTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/http/HttpClientConfigTest.java @@ -16,78 +16,77 @@ package com.alibaba.nacos.common.http; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; -public class HttpClientConfigTest { +class HttpClientConfigTest { @Test - public void testGetConTimeOutMillis() { + void testGetConTimeOutMillis() { HttpClientConfig config = HttpClientConfig.builder().setConTimeOutMillis(1000).build(); assertEquals(1000, config.getConTimeOutMillis()); } @Test - public void testGetReadTimeOutMillis() { + void testGetReadTimeOutMillis() { HttpClientConfig config = HttpClientConfig.builder().setReadTimeOutMillis(2000).build(); assertEquals(2000, config.getReadTimeOutMillis()); } @Test - public void testGetConnTimeToLive() { - HttpClientConfig config = HttpClientConfig.builder().setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS) - .build(); + void testGetConnTimeToLive() { + HttpClientConfig config = HttpClientConfig.builder().setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS).build(); assertEquals(3000, config.getConnTimeToLive()); } @Test - public void testGetConnTimeToLiveTimeUnit() { + void testGetConnTimeToLiveTimeUnit() { HttpClientConfig config = HttpClientConfig.builder().setConnectionTimeToLive(4000, TimeUnit.SECONDS).build(); assertEquals(TimeUnit.SECONDS, config.getConnTimeToLiveTimeUnit()); } @Test - public void testGetConnectionRequestTimeout() { + void testGetConnectionRequestTimeout() { HttpClientConfig config = HttpClientConfig.builder().setConnectionRequestTimeout(5000).build(); assertEquals(5000, config.getConnectionRequestTimeout()); } @Test - public void testGetMaxRedirects() { + void testGetMaxRedirects() { HttpClientConfig config = HttpClientConfig.builder().setMaxRedirects(60).build(); assertEquals(60, config.getMaxRedirects()); } @Test - public void testGetMaxConnTotal() { + void testGetMaxConnTotal() { HttpClientConfig config = HttpClientConfig.builder().setMaxConnTotal(70).build(); assertEquals(70, config.getMaxConnTotal()); } @Test - public void testGetMaxConnPerRoute() { + void testGetMaxConnPerRoute() { HttpClientConfig config = HttpClientConfig.builder().setMaxConnPerRoute(80).build(); assertEquals(80, config.getMaxConnPerRoute()); } @Test - public void testGetContentCompressionEnabled() { + void testGetContentCompressionEnabled() { HttpClientConfig config = HttpClientConfig.builder().setContentCompressionEnabled(false).build(); assertFalse(config.getContentCompressionEnabled()); } @Test - public void testGetIoThreadCount() { + void testGetIoThreadCount() { HttpClientConfig config = HttpClientConfig.builder().setIoThreadCount(90).build(); assertEquals(90, config.getIoThreadCount()); } @Test - public void testGetUserAgent() { + void testGetUserAgent() { HttpClientConfig config = HttpClientConfig.builder().setUserAgent("testUserAgent").build(); assertEquals("testUserAgent", config.getUserAgent()); } diff --git a/common/src/test/java/com/alibaba/nacos/common/http/HttpRestResultTest.java b/common/src/test/java/com/alibaba/nacos/common/http/HttpRestResultTest.java index 2d702dd7eb5..62bc6daca53 100644 --- a/common/src/test/java/com/alibaba/nacos/common/http/HttpRestResultTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/http/HttpRestResultTest.java @@ -17,14 +17,14 @@ package com.alibaba.nacos.common.http; import com.alibaba.nacos.common.http.param.Header; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class HttpRestResultTest { +class HttpRestResultTest { @Test - public void testSetHeader() { + void testSetHeader() { HttpRestResult result = new HttpRestResult<>(); result.setData("test data"); Header header = Header.newInstance(); @@ -34,7 +34,7 @@ public void testSetHeader() { } @Test - public void testFullConstructor() { + void testFullConstructor() { Header header = Header.newInstance(); HttpRestResult result = new HttpRestResult<>(header, 200, "test data", "message"); assertEquals(header, result.getHeader()); diff --git a/common/src/test/java/com/alibaba/nacos/common/http/HttpUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/http/HttpUtilsTest.java index 5a6250bee83..8dfdb4aec68 100644 --- a/common/src/test/java/com/alibaba/nacos/common/http/HttpUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/http/HttpUtilsTest.java @@ -25,10 +25,9 @@ import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.conn.ConnectTimeoutException; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.InputStream; import java.io.UnsupportedEncodingException; @@ -43,53 +42,60 @@ import java.util.Map; import java.util.concurrent.TimeoutException; -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.assertArrayEquals; +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; -@RunWith(MockitoJUnitRunner.class) -public class HttpUtilsTest { +@ExtendWith(MockitoExtension.class) +class HttpUtilsTest { String exceptUrl = "http://127.0.0.1:8080/v1/api/test"; @Test - public void testBuildHttpUrl1() { + void testBuildHttpUrl1() { String targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1/api/test"); - Assert.assertEquals(exceptUrl, targetUrl); + assertEquals(exceptUrl, targetUrl); targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "v1/api/test"); - Assert.assertEquals(exceptUrl, targetUrl); + assertEquals(exceptUrl, targetUrl); targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1", "/api/test"); - Assert.assertEquals(exceptUrl, targetUrl); + assertEquals(exceptUrl, targetUrl); targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1", "/api", "/test"); - Assert.assertEquals(exceptUrl, targetUrl); + assertEquals(exceptUrl, targetUrl); targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1", "/api/", "/test"); - Assert.assertEquals(exceptUrl, targetUrl); + assertEquals(exceptUrl, targetUrl); targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1", "", "/api/", "/test"); - Assert.assertEquals(exceptUrl, targetUrl); + assertEquals(exceptUrl, targetUrl); targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1", "", null, "/api/", "/test"); - Assert.assertEquals(exceptUrl, targetUrl); + assertEquals(exceptUrl, targetUrl); targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1", "/api/", "test"); - Assert.assertEquals(exceptUrl, targetUrl); + assertEquals(exceptUrl, targetUrl); targetUrl = HttpUtils.buildUrl(true, "127.0.0.1:8080", "/v1", "", null, "/api/", "/test"); - Assert.assertEquals("https://127.0.0.1:8080/v1/api/test", targetUrl); + assertEquals("https://127.0.0.1:8080/v1/api/test", targetUrl); } - @Test(expected = IllegalArgumentException.class) - public void testBuildHttpUrl2() { - String targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "//v1/api/test"); - Assert.assertNotEquals(exceptUrl, targetUrl); + @Test + void testBuildHttpUrl2() { + assertThrows(IllegalArgumentException.class, () -> { + String targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "//v1/api/test"); + assertNotEquals(exceptUrl, targetUrl); + }); } - @Test(expected = IllegalArgumentException.class) - public void testBuildHttpUrl3() { - String targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1", "/api//", "test"); - Assert.assertNotEquals(exceptUrl, targetUrl); + @Test + void testBuildHttpUrl3() { + assertThrows(IllegalArgumentException.class, () -> { + String targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1", "/api//", "test"); + assertNotEquals(exceptUrl, targetUrl); + }); } @Test - public void testInitRequestHeader() { + void testInitRequestHeader() { BaseHttpMethod.HttpGetWithEntity httpRequest = new BaseHttpMethod.HttpGetWithEntity(""); Header header = Header.newInstance(); header.addParam("k", "v"); @@ -97,13 +103,13 @@ public void testInitRequestHeader() { HttpUtils.initRequestHeader(httpRequest, header); org.apache.http.Header[] headers = httpRequest.getHeaders("k"); - Assert.assertEquals(1, headers.length); - Assert.assertEquals("k", headers[0].getName()); - Assert.assertEquals("v", headers[0].getValue()); + assertEquals(1, headers.length); + assertEquals("k", headers[0].getName()); + assertEquals("v", headers[0].getValue()); } @Test - public void testInitRequestEntity1() throws Exception { + void testInitRequestEntity1() throws Exception { BaseHttpMethod.HttpGetWithEntity httpRequest = new BaseHttpMethod.HttpGetWithEntity(""); Header header = Header.newInstance(); header.addParam(HttpHeaderConsts.CONTENT_TYPE, "text/html"); @@ -114,13 +120,13 @@ public void testInitRequestEntity1() throws Exception { InputStream contentStream = entity.getContent(); byte[] bytes = new byte[contentStream.available()]; contentStream.read(bytes); - Assert.assertArrayEquals(new byte[] {0, 1, 0, 1}, bytes); - Assert.assertEquals(HttpHeaderConsts.CONTENT_TYPE, entity.getContentType().getName()); - Assert.assertEquals("text/html; charset=UTF-8", entity.getContentType().getValue()); + assertArrayEquals(new byte[] {0, 1, 0, 1}, bytes); + assertEquals(HttpHeaderConsts.CONTENT_TYPE, entity.getContentType().getName()); + assertEquals("text/html; charset=UTF-8", entity.getContentType().getValue()); } @Test - public void testInitRequestEntity2() throws Exception { + void testInitRequestEntity2() throws Exception { BaseHttpMethod.HttpGetWithEntity httpRequest = new BaseHttpMethod.HttpGetWithEntity(""); Header header = Header.newInstance(); header.addParam(HttpHeaderConsts.CONTENT_TYPE, "text/html"); @@ -131,13 +137,13 @@ public void testInitRequestEntity2() throws Exception { InputStream contentStream = entity.getContent(); byte[] bytes = new byte[contentStream.available()]; contentStream.read(bytes); - Assert.assertEquals("{\"k\":\"v\"}", new String(bytes, Constants.ENCODE)); - Assert.assertEquals(HttpHeaderConsts.CONTENT_TYPE, entity.getContentType().getName()); - Assert.assertEquals("text/html; charset=UTF-8", entity.getContentType().getValue()); + assertEquals("{\"k\":\"v\"}", new String(bytes, Constants.ENCODE)); + assertEquals(HttpHeaderConsts.CONTENT_TYPE, entity.getContentType().getName()); + assertEquals("text/html; charset=UTF-8", entity.getContentType().getValue()); } @Test - public void testInitRequestEntity3() throws Exception { + void testInitRequestEntity3() throws Exception { BaseHttpMethod.HttpGetWithEntity httpRequest = new BaseHttpMethod.HttpGetWithEntity(""); Header header = Header.newInstance(); header.addParam(HttpHeaderConsts.CONTENT_TYPE, "text/html"); @@ -148,35 +154,35 @@ public void testInitRequestEntity3() throws Exception { InputStream contentStream = entity.getContent(); byte[] bytes = new byte[contentStream.available()]; contentStream.read(bytes); - Assert.assertEquals("common text", new String(bytes, Constants.ENCODE)); - Assert.assertEquals(HttpHeaderConsts.CONTENT_TYPE, entity.getContentType().getName()); - Assert.assertEquals("text/html; charset=UTF-8", entity.getContentType().getValue()); + assertEquals("common text", new String(bytes, Constants.ENCODE)); + assertEquals(HttpHeaderConsts.CONTENT_TYPE, entity.getContentType().getName()); + assertEquals("text/html; charset=UTF-8", entity.getContentType().getValue()); } @Test - public void testInitRequestEntity4() throws Exception { + void testInitRequestEntity4() throws Exception { BaseHttpMethod.HttpGetWithEntity httpRequest = new BaseHttpMethod.HttpGetWithEntity(""); HttpUtils.initRequestEntity(httpRequest, null, null); // nothing change - Assert.assertEquals(new BaseHttpMethod.HttpGetWithEntity("").getEntity(), httpRequest.getEntity()); - Assert.assertArrayEquals(new BaseHttpMethod.HttpGetWithEntity("").getAllHeaders(), httpRequest.getAllHeaders()); + assertEquals(new BaseHttpMethod.HttpGetWithEntity("").getEntity(), httpRequest.getEntity()); + assertArrayEquals(new BaseHttpMethod.HttpGetWithEntity("").getAllHeaders(), httpRequest.getAllHeaders()); } @Test - public void testInitRequestEntity5() throws Exception { + void testInitRequestEntity5() throws Exception { HttpDelete httpDelete = new HttpDelete(""); HttpUtils.initRequestEntity(httpDelete, null, null); // nothing change - Assert.assertEquals(new HttpDelete("").getMethod(), httpDelete.getMethod()); - Assert.assertArrayEquals(new HttpDelete("").getAllHeaders(), httpDelete.getAllHeaders()); + assertEquals(new HttpDelete("").getMethod(), httpDelete.getMethod()); + assertArrayEquals(new HttpDelete("").getAllHeaders(), httpDelete.getAllHeaders()); } @Test - public void testInitRequestFromEntity1() throws Exception { + void testInitRequestFromEntity1() throws Exception { BaseHttpMethod.HttpGetWithEntity httpRequest = new BaseHttpMethod.HttpGetWithEntity(""); HttpUtils.initRequestFromEntity(httpRequest, Collections.singletonMap("k", "v"), "UTF-8"); @@ -185,72 +191,72 @@ public void testInitRequestFromEntity1() throws Exception { InputStream contentStream = entity.getContent(); byte[] bytes = new byte[contentStream.available()]; contentStream.read(bytes); - Assert.assertEquals("k=v", new String(bytes, StandardCharsets.UTF_8)); + assertEquals("k=v", new String(bytes, StandardCharsets.UTF_8)); } @Test - public void testInitRequestFromEntity2() throws Exception { + void testInitRequestFromEntity2() throws Exception { BaseHttpMethod.HttpGetWithEntity httpRequest = new BaseHttpMethod.HttpGetWithEntity(""); HttpUtils.initRequestFromEntity(httpRequest, null, "UTF-8"); // nothing change - Assert.assertEquals(new BaseHttpMethod.HttpGetWithEntity("").getEntity(), httpRequest.getEntity()); + assertEquals(new BaseHttpMethod.HttpGetWithEntity("").getEntity(), httpRequest.getEntity()); } @Test - public void testInitRequestFromEntity3() throws Exception { + void testInitRequestFromEntity3() throws Exception { BaseHttpMethod.HttpGetWithEntity httpRequest = new BaseHttpMethod.HttpGetWithEntity(""); HttpUtils.initRequestFromEntity(httpRequest, Collections.emptyMap(), "UTF-8"); // nothing change - Assert.assertEquals(new BaseHttpMethod.HttpGetWithEntity("").getEntity(), httpRequest.getEntity()); + assertEquals(new BaseHttpMethod.HttpGetWithEntity("").getEntity(), httpRequest.getEntity()); } @Test - public void testInitRequestFromEntity4() throws Exception { + void testInitRequestFromEntity4() throws Exception { BaseHttpMethod.HttpGetWithEntity httpRequest = new BaseHttpMethod.HttpGetWithEntity(""); HttpUtils.initRequestFromEntity(mock(HttpRequestBase.class), Collections.emptyMap(), "UTF-8"); // nothing change - Assert.assertEquals(new BaseHttpMethod.HttpGetWithEntity("").getEntity(), httpRequest.getEntity()); + assertEquals(new BaseHttpMethod.HttpGetWithEntity("").getEntity(), httpRequest.getEntity()); } @Test - public void testInitRequestFromEntity5() throws Exception { + void testInitRequestFromEntity5() throws Exception { HttpDelete httpDelete = new HttpDelete(""); HttpUtils.initRequestFromEntity(httpDelete, Collections.singletonMap("k", "v"), "UTF-8"); // nothing change - Assert.assertEquals(new HttpDelete("").getMethod(), httpDelete.getMethod()); - Assert.assertArrayEquals(new HttpDelete("").getAllHeaders(), httpDelete.getAllHeaders()); + assertEquals(new HttpDelete("").getMethod(), httpDelete.getMethod()); + assertArrayEquals(new HttpDelete("").getAllHeaders(), httpDelete.getAllHeaders()); } @Test - public void testTranslateParameterMap() throws Exception { + void testTranslateParameterMap() throws Exception { Map map = Collections.singletonMap("K", new String[] {"V1", "V2"}); Map resultMap = HttpUtils.translateParameterMap(map); - Assert.assertEquals(Collections.singletonMap("K", "V1"), resultMap); + assertEquals(Collections.singletonMap("K", "V1"), resultMap); } @Test - public void testDecode() throws UnsupportedEncodingException { + void testDecode() throws UnsupportedEncodingException { // % - %25, { - %7B, } - %7D - Assert.assertEquals("{k,v}", HttpUtils.decode("%7Bk,v%7D", "UTF-8")); - Assert.assertEquals("{k,v}", HttpUtils.decode("%257Bk,v%257D", "UTF-8")); + assertEquals("{k,v}", HttpUtils.decode("%7Bk,v%7D", "UTF-8")); + assertEquals("{k,v}", HttpUtils.decode("%257Bk,v%257D", "UTF-8")); } @Test - public void testEncodingParamsMapWithNullOrEmpty() throws UnsupportedEncodingException { + void testEncodingParamsMapWithNullOrEmpty() throws UnsupportedEncodingException { assertNull(HttpUtils.encodingParams((Map) null, "UTF-8")); assertNull(HttpUtils.encodingParams(Collections.emptyMap(), "UTF-8")); } @Test - public void testEncodingParamsMap() throws UnsupportedEncodingException { + void testEncodingParamsMap() throws UnsupportedEncodingException { Map params = new LinkedHashMap<>(); params.put("a", ""); params.put("b", "x"); @@ -260,12 +266,12 @@ public void testEncodingParamsMap() throws UnsupportedEncodingException { } @Test - public void testEncodingParamsListWithNull() throws UnsupportedEncodingException { + void testEncodingParamsListWithNull() throws UnsupportedEncodingException { assertNull(HttpUtils.encodingParams((List) null, "UTF-8")); } @Test - public void testEncodingParamsList() throws UnsupportedEncodingException { + void testEncodingParamsList() throws UnsupportedEncodingException { List params = new LinkedList<>(); params.add("a"); params.add(""); @@ -279,7 +285,7 @@ public void testEncodingParamsList() throws UnsupportedEncodingException { } @Test - public void testBuildUriForEmptyQuery() throws URISyntaxException { + void testBuildUriForEmptyQuery() throws URISyntaxException { URI actual = HttpUtils.buildUri("www.aliyun.com", null); assertEquals("www.aliyun.com", actual.toString()); actual = HttpUtils.buildUri("www.aliyun.com", new Query()); @@ -287,7 +293,7 @@ public void testBuildUriForEmptyQuery() throws URISyntaxException { } @Test - public void testBuildUri() throws URISyntaxException { + void testBuildUri() throws URISyntaxException { Query query = new Query(); query.addParam("a", ""); query.addParam("b", "x"); @@ -298,7 +304,7 @@ public void testBuildUri() throws URISyntaxException { } @Test - public void testIsTimeoutException() { + void testIsTimeoutException() { assertFalse(HttpUtils.isTimeoutException(new NacosRuntimeException(0))); assertTrue(HttpUtils.isTimeoutException(new TimeoutException())); assertTrue(HttpUtils.isTimeoutException(new SocketTimeoutException())); diff --git a/common/src/test/java/com/alibaba/nacos/common/http/client/AbstractNacosRestTemplateTest.java b/common/src/test/java/com/alibaba/nacos/common/http/client/AbstractNacosRestTemplateTest.java index 5aa209f330a..3972f1f2039 100644 --- a/common/src/test/java/com/alibaba/nacos/common/http/client/AbstractNacosRestTemplateTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/http/client/AbstractNacosRestTemplateTest.java @@ -21,50 +21,49 @@ import com.alibaba.nacos.common.http.client.handler.RestResultResponseHandler; import com.alibaba.nacos.common.http.client.handler.StringResponseHandler; import com.alibaba.nacos.common.model.RestResult; -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.slf4j.Logger; import java.lang.reflect.Type; -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; -@RunWith(MockitoJUnitRunner.class) -public class AbstractNacosRestTemplateTest { +@ExtendWith(MockitoExtension.class) +class AbstractNacosRestTemplateTest { + + MockNacosRestTemplate restTemplate; @Mock private ResponseHandler mockResponseHandler; - MockNacosRestTemplate restTemplate; - - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { restTemplate = new MockNacosRestTemplate(null); restTemplate.registerResponseHandler(MockNacosRestTemplate.class.getName(), mockResponseHandler); } @Test - public void testSelectResponseHandlerForNull() { + void testSelectResponseHandlerForNull() { assertTrue(restTemplate.testFindResponseHandler(null) instanceof StringResponseHandler); } @Test - public void testSelectResponseHandlerForRestResult() { + void testSelectResponseHandlerForRestResult() { assertTrue(restTemplate.testFindResponseHandler(RestResult.class) instanceof RestResultResponseHandler); } @Test - public void testSelectResponseHandlerForDefault() { - assertTrue(restTemplate - .testFindResponseHandler(AbstractNacosRestTemplateTest.class) instanceof BeanResponseHandler); + void testSelectResponseHandlerForDefault() { + assertTrue(restTemplate.testFindResponseHandler(AbstractNacosRestTemplateTest.class) instanceof BeanResponseHandler); } @Test - public void testSelectResponseHandlerForCustom() { + void testSelectResponseHandlerForCustom() { assertEquals(mockResponseHandler, restTemplate.testFindResponseHandler(MockNacosRestTemplate.class)); } diff --git a/common/src/test/java/com/alibaba/nacos/common/http/client/InterceptingHttpClientRequestTest.java b/common/src/test/java/com/alibaba/nacos/common/http/client/InterceptingHttpClientRequestTest.java index e27941b5858..41aa961aea9 100644 --- a/common/src/test/java/com/alibaba/nacos/common/http/client/InterceptingHttpClientRequestTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/http/client/InterceptingHttpClientRequestTest.java @@ -21,23 +21,29 @@ import com.alibaba.nacos.common.http.param.Header; import com.alibaba.nacos.common.http.param.Query; import com.alibaba.nacos.common.model.RequestHttpEntity; -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 org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import java.net.URI; import java.util.LinkedList; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class InterceptingHttpClientRequestTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class InterceptingHttpClientRequestTest { + + InterceptingHttpClientRequest clientRequest; @Mock private HttpClientRequest httpClientRequest; @@ -51,10 +57,8 @@ public class InterceptingHttpClientRequestTest { @Mock private HttpClientResponse httpClientResponse; - InterceptingHttpClientRequest clientRequest; - - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { List interceptorList = new LinkedList<>(); interceptorList.add(interceptor); clientRequest = new InterceptingHttpClientRequest(httpClientRequest, interceptorList.listIterator()); @@ -62,23 +66,23 @@ public void setUp() throws Exception { when(httpClientRequest.execute(any(), any(), any())).thenReturn(httpClientResponse); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { clientRequest.close(); } @Test - public void testExecuteIntercepted() throws Exception { + void testExecuteIntercepted() throws Exception { when(interceptor.isIntercept(any(), any(), any())).thenReturn(true); - HttpClientResponse response = clientRequest - .execute(URI.create("http://example.com"), "GET", new RequestHttpEntity(Header.EMPTY, Query.EMPTY)); + HttpClientResponse response = clientRequest.execute(URI.create("http://example.com"), "GET", + new RequestHttpEntity(Header.EMPTY, Query.EMPTY)); assertEquals(interceptorResponse, response); } @Test - public void testExecuteNotIntercepted() throws Exception { - HttpClientResponse response = clientRequest - .execute(URI.create("http://example.com"), "GET", new RequestHttpEntity(Header.EMPTY, Query.EMPTY)); + void testExecuteNotIntercepted() throws Exception { + HttpClientResponse response = clientRequest.execute(URI.create("http://example.com"), "GET", + new RequestHttpEntity(Header.EMPTY, Query.EMPTY)); assertEquals(httpClientResponse, response); } } \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/http/client/NacosAsyncRestTemplateTest.java b/common/src/test/java/com/alibaba/nacos/common/http/client/NacosAsyncRestTemplateTest.java index a3749a8e694..ecb2bc7016b 100644 --- a/common/src/test/java/com/alibaba/nacos/common/http/client/NacosAsyncRestTemplateTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/http/client/NacosAsyncRestTemplateTest.java @@ -22,25 +22,25 @@ import com.alibaba.nacos.common.http.param.Header; import com.alibaba.nacos.common.http.param.MediaType; import com.alibaba.nacos.common.http.param.Query; -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 org.slf4j.Logger; import java.util.HashMap; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class NacosAsyncRestTemplateTest { +@ExtendWith(MockitoExtension.class) +class NacosAsyncRestTemplateTest { private static final String TEST_URL = "http://127.0.0.1:8848/nacos/test"; @@ -55,25 +55,25 @@ public class NacosAsyncRestTemplateTest { private NacosAsyncRestTemplate restTemplate; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { restTemplate = new NacosAsyncRestTemplate(logger, requestClient); when(logger.isDebugEnabled()).thenReturn(true); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { restTemplate.close(); } @Test - public void testGet() throws Exception { + void testGet() throws Exception { restTemplate.get(TEST_URL, Header.EMPTY, Query.EMPTY, String.class, mockCallback); verify(requestClient).execute(any(), eq("GET"), any(), any(), eq(mockCallback)); } @Test - public void testGetWithException() throws Exception { + void testGetWithException() throws Exception { doThrow(new RuntimeException("test")).when(requestClient).execute(any(), any(), any(), any(), any()); restTemplate.get(TEST_URL, Header.EMPTY, Query.EMPTY, String.class, mockCallback); verify(requestClient).execute(any(), eq("GET"), any(), any(), eq(mockCallback)); @@ -81,31 +81,31 @@ public void testGetWithException() throws Exception { } @Test - public void testGetLarge() throws Exception { + void testGetLarge() throws Exception { restTemplate.getLarge(TEST_URL, Header.EMPTY, Query.EMPTY, new Object(), String.class, mockCallback); verify(requestClient).execute(any(), eq("GET-LARGE"), any(), any(), eq(mockCallback)); } @Test - public void testDeleteWithBody() throws Exception { + void testDeleteWithBody() throws Exception { restTemplate.delete(TEST_URL, Header.EMPTY, Query.EMPTY, String.class, mockCallback); verify(requestClient).execute(any(), eq("DELETE"), any(), any(), eq(mockCallback)); } @Test - public void testDeleteLarge() throws Exception { + void testDeleteLarge() throws Exception { restTemplate.delete(TEST_URL, Header.EMPTY, "body", String.class, mockCallback); verify(requestClient).execute(any(), eq("DELETE_LARGE"), any(), any(), eq(mockCallback)); } @Test - public void testPut() throws Exception { + void testPut() throws Exception { restTemplate.put(TEST_URL, Header.EMPTY, Query.EMPTY, "body", String.class, mockCallback); verify(requestClient).execute(any(), eq("PUT"), any(), any(), eq(mockCallback)); } @Test - public void testPutJson() throws Exception { + void testPutJson() throws Exception { Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML); restTemplate.putJson(TEST_URL, header, "body", String.class, mockCallback); verify(requestClient).execute(any(), eq("PUT"), any(), any(), eq(mockCallback)); @@ -113,7 +113,7 @@ public void testPutJson() throws Exception { } @Test - public void testPutJsonWithQuery() throws Exception { + void testPutJsonWithQuery() throws Exception { Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML); restTemplate.putJson(TEST_URL, header, Query.EMPTY, "body", String.class, mockCallback); verify(requestClient).execute(any(), eq("PUT"), any(), any(), eq(mockCallback)); @@ -121,7 +121,7 @@ public void testPutJsonWithQuery() throws Exception { } @Test - public void testPutForm() throws Exception { + void testPutForm() throws Exception { Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML); restTemplate.putForm(TEST_URL, header, new HashMap<>(), String.class, mockCallback); verify(requestClient).execute(any(), eq("PUT"), any(), any(), eq(mockCallback)); @@ -129,7 +129,7 @@ public void testPutForm() throws Exception { } @Test - public void testPutFormWithQuery() throws Exception { + void testPutFormWithQuery() throws Exception { Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML); restTemplate.putForm(TEST_URL, header, Query.EMPTY, new HashMap<>(), String.class, mockCallback); verify(requestClient).execute(any(), eq("PUT"), any(), any(), eq(mockCallback)); @@ -137,13 +137,13 @@ public void testPutFormWithQuery() throws Exception { } @Test - public void testPost() throws Exception { + void testPost() throws Exception { restTemplate.post(TEST_URL, Header.EMPTY, Query.EMPTY, "body", String.class, mockCallback); verify(requestClient).execute(any(), eq("POST"), any(), any(), eq(mockCallback)); } @Test - public void testPostJson() throws Exception { + void testPostJson() throws Exception { Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML); restTemplate.postJson(TEST_URL, header, "body", String.class, mockCallback); verify(requestClient).execute(any(), eq("POST"), any(), any(), eq(mockCallback)); @@ -151,7 +151,7 @@ public void testPostJson() throws Exception { } @Test - public void testPostJsonWithQuery() throws Exception { + void testPostJsonWithQuery() throws Exception { Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML); restTemplate.postJson(TEST_URL, header, Query.EMPTY, "body", String.class, mockCallback); verify(requestClient).execute(any(), eq("POST"), any(), any(), eq(mockCallback)); @@ -159,7 +159,7 @@ public void testPostJsonWithQuery() throws Exception { } @Test - public void testPostForm() throws Exception { + void testPostForm() throws Exception { Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML); restTemplate.postForm(TEST_URL, header, new HashMap<>(), String.class, mockCallback); verify(requestClient).execute(any(), eq("POST"), any(), any(), eq(mockCallback)); @@ -167,7 +167,7 @@ public void testPostForm() throws Exception { } @Test - public void testPostFormWithQuery() throws Exception { + void testPostFormWithQuery() throws Exception { Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML); restTemplate.postForm(TEST_URL, header, Query.EMPTY, new HashMap<>(), String.class, mockCallback); verify(requestClient).execute(any(), eq("POST"), any(), any(), eq(mockCallback)); diff --git a/common/src/test/java/com/alibaba/nacos/common/http/client/NacosRestTemplateTest.java b/common/src/test/java/com/alibaba/nacos/common/http/client/NacosRestTemplateTest.java index 4682b680370..b4979a45465 100644 --- a/common/src/test/java/com/alibaba/nacos/common/http/client/NacosRestTemplateTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/http/client/NacosRestTemplateTest.java @@ -24,27 +24,32 @@ import com.alibaba.nacos.common.http.param.Header; import com.alibaba.nacos.common.http.param.MediaType; import com.alibaba.nacos.common.http.param.Query; -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 org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.slf4j.Logger; import java.io.ByteArrayInputStream; import java.util.Collections; import java.util.HashMap; -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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class NacosRestTemplateTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class NacosRestTemplateTest { @Mock private HttpClientRequest requestClient; @@ -60,8 +65,8 @@ public class NacosRestTemplateTest { private NacosRestTemplate restTemplate; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { restTemplate = new NacosRestTemplate(logger, requestClient); when(logger.isDebugEnabled()).thenReturn(true); when(mockResponse.getHeaders()).thenReturn(Header.EMPTY); @@ -69,111 +74,112 @@ public void setUp() throws Exception { when(interceptor.intercept()).thenReturn(mockResponse); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { restTemplate.close(); } @Test - public void testGetWithDefaultConfig() throws Exception { + void testGetWithDefaultConfig() throws Exception { when(requestClient.execute(any(), eq("GET"), any())).thenReturn(mockResponse); when(mockResponse.getStatusCode()).thenReturn(200); when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes())); - HttpRestResult result = restTemplate - .get("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, String.class); + HttpRestResult result = restTemplate.get("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, + String.class); assertTrue(result.ok()); assertEquals(Header.EMPTY, result.getHeader()); assertEquals("test", result.getData()); } @Test - public void testGetWithCustomConfig() throws Exception { + void testGetWithCustomConfig() throws Exception { when(requestClient.execute(any(), eq("GET"), any())).thenReturn(mockResponse); when(mockResponse.getStatusCode()).thenReturn(200); when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes())); HttpClientConfig config = HttpClientConfig.builder().setConTimeOutMillis(1000).build(); - HttpRestResult result = restTemplate - .get("http://127.0.0.1:8848/nacos/test", config, Header.EMPTY, Query.EMPTY, String.class); + HttpRestResult result = restTemplate.get("http://127.0.0.1:8848/nacos/test", config, Header.EMPTY, Query.EMPTY, + String.class); assertTrue(result.ok()); assertEquals(Header.EMPTY, result.getHeader()); assertEquals("test", result.getData()); } @Test - public void testGetWithInterceptor() throws Exception { + void testGetWithInterceptor() throws Exception { when(mockResponse.getStatusCode()).thenReturn(300); when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test interceptor".getBytes())); restTemplate.setInterceptors(Collections.singletonList(interceptor)); - HttpRestResult result = restTemplate - .get("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, String.class); + HttpRestResult result = restTemplate.get("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, + String.class); assertFalse(result.ok()); assertEquals(Header.EMPTY, result.getHeader()); assertEquals("test interceptor", result.getMessage()); } - @Test(expected = RuntimeException.class) - public void testGetWithException() throws Exception { - when(requestClient.execute(any(), eq("GET"), any())).thenThrow(new RuntimeException("test")); - restTemplate.get("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, String.class); + @Test + void testGetWithException() throws Exception { + assertThrows(RuntimeException.class, () -> { + when(requestClient.execute(any(), eq("GET"), any())).thenThrow(new RuntimeException("test")); + restTemplate.get("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, String.class); + }); } @Test - public void testGetLarge() throws Exception { + void testGetLarge() throws Exception { when(requestClient.execute(any(), eq("GET-LARGE"), any())).thenReturn(mockResponse); when(mockResponse.getStatusCode()).thenReturn(200); when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes())); - HttpRestResult result = restTemplate - .getLarge("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, new Object(), String.class); + HttpRestResult result = restTemplate.getLarge("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, + new Object(), String.class); assertTrue(result.ok()); assertEquals(Header.EMPTY, result.getHeader()); assertEquals("test", result.getData()); } @Test - public void testDeleteWithDefaultConfig() throws Exception { + void testDeleteWithDefaultConfig() throws Exception { when(requestClient.execute(any(), eq("DELETE"), any())).thenReturn(mockResponse); when(mockResponse.getStatusCode()).thenReturn(200); when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes())); - HttpRestResult result = restTemplate - .delete("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, String.class); + HttpRestResult result = restTemplate.delete("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, + String.class); assertTrue(result.ok()); assertEquals(Header.EMPTY, result.getHeader()); assertEquals("test", result.getData()); } @Test - public void testDeleteWithCustomConfig() throws Exception { + void testDeleteWithCustomConfig() throws Exception { when(requestClient.execute(any(), eq("DELETE"), any())).thenReturn(mockResponse); when(mockResponse.getStatusCode()).thenReturn(200); when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes())); HttpClientConfig config = HttpClientConfig.builder().setConTimeOutMillis(1000).build(); - HttpRestResult result = restTemplate - .delete("http://127.0.0.1:8848/nacos/test", config, Header.EMPTY, Query.EMPTY, String.class); + HttpRestResult result = restTemplate.delete("http://127.0.0.1:8848/nacos/test", config, Header.EMPTY, Query.EMPTY, + String.class); assertTrue(result.ok()); assertEquals(Header.EMPTY, result.getHeader()); assertEquals("test", result.getData()); } @Test - public void testPut() throws Exception { + void testPut() throws Exception { when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse); when(mockResponse.getStatusCode()).thenReturn(200); when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes())); - HttpRestResult result = restTemplate - .put("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, new Object(), String.class); + HttpRestResult result = restTemplate.put("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, + new Object(), String.class); assertTrue(result.ok()); assertEquals(Header.EMPTY, result.getHeader()); assertEquals("test", result.getData()); } @Test - public void testPutJson() throws Exception { + void testPutJson() throws Exception { when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse); when(mockResponse.getStatusCode()).thenReturn(200); when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes())); Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML); - HttpRestResult result = restTemplate - .putJson("http://127.0.0.1:8848/nacos/test", header, "body", String.class); + HttpRestResult result = restTemplate.putJson("http://127.0.0.1:8848/nacos/test", header, "body", String.class); assertTrue(result.ok()); assertEquals(Header.EMPTY, result.getHeader()); assertEquals("test", result.getData()); @@ -181,13 +187,13 @@ public void testPutJson() throws Exception { } @Test - public void testPutJsonWithQuery() throws Exception { + void testPutJsonWithQuery() throws Exception { when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse); when(mockResponse.getStatusCode()).thenReturn(200); when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes())); Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML); - HttpRestResult result = restTemplate - .putJson("http://127.0.0.1:8848/nacos/test", header, Query.EMPTY, "body", String.class); + HttpRestResult result = restTemplate.putJson("http://127.0.0.1:8848/nacos/test", header, Query.EMPTY, "body", + String.class); assertTrue(result.ok()); assertEquals(Header.EMPTY, result.getHeader()); assertEquals("test", result.getData()); @@ -195,13 +201,13 @@ public void testPutJsonWithQuery() throws Exception { } @Test - public void testPutForm() throws Exception { + void testPutForm() throws Exception { when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse); when(mockResponse.getStatusCode()).thenReturn(200); when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes())); Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML); - HttpRestResult result = restTemplate - .putForm("http://127.0.0.1:8848/nacos/test", header, new HashMap<>(), String.class); + HttpRestResult result = restTemplate.putForm("http://127.0.0.1:8848/nacos/test", header, new HashMap<>(), + String.class); assertTrue(result.ok()); assertEquals(Header.EMPTY, result.getHeader()); assertEquals("test", result.getData()); @@ -209,13 +215,13 @@ public void testPutForm() throws Exception { } @Test - public void testPutFormWithQuery() throws Exception { + void testPutFormWithQuery() throws Exception { when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse); when(mockResponse.getStatusCode()).thenReturn(200); when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes())); Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML); - HttpRestResult result = restTemplate - .putForm("http://127.0.0.1:8848/nacos/test", header, Query.EMPTY, new HashMap<>(), String.class); + HttpRestResult result = restTemplate.putForm("http://127.0.0.1:8848/nacos/test", header, Query.EMPTY, + new HashMap<>(), String.class); assertTrue(result.ok()); assertEquals(Header.EMPTY, result.getHeader()); assertEquals("test", result.getData()); @@ -223,14 +229,14 @@ public void testPutFormWithQuery() throws Exception { } @Test - public void testPutFormWithConfig() throws Exception { + void testPutFormWithConfig() throws Exception { when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse); when(mockResponse.getStatusCode()).thenReturn(200); when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes())); HttpClientConfig config = HttpClientConfig.builder().setConTimeOutMillis(1000).build(); Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML); - HttpRestResult result = restTemplate - .putForm("http://127.0.0.1:8848/nacos/test", config, header, new HashMap<>(), String.class); + HttpRestResult result = restTemplate.putForm("http://127.0.0.1:8848/nacos/test", config, header, new HashMap<>(), + String.class); assertTrue(result.ok()); assertEquals(Header.EMPTY, result.getHeader()); assertEquals("test", result.getData()); @@ -238,25 +244,24 @@ public void testPutFormWithConfig() throws Exception { } @Test - public void testPost() throws Exception { + void testPost() throws Exception { when(requestClient.execute(any(), eq("POST"), any())).thenReturn(mockResponse); when(mockResponse.getStatusCode()).thenReturn(200); when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes())); - HttpRestResult result = restTemplate - .post("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, new Object(), String.class); + HttpRestResult result = restTemplate.post("http://127.0.0.1:8848/nacos/test", Header.EMPTY, Query.EMPTY, + new Object(), String.class); assertTrue(result.ok()); assertEquals(Header.EMPTY, result.getHeader()); assertEquals("test", result.getData()); } @Test - public void testPostJson() throws Exception { + void testPostJson() throws Exception { when(requestClient.execute(any(), eq("POST"), any())).thenReturn(mockResponse); when(mockResponse.getStatusCode()).thenReturn(200); when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes())); Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML); - HttpRestResult result = restTemplate - .postJson("http://127.0.0.1:8848/nacos/test", header, "body", String.class); + HttpRestResult result = restTemplate.postJson("http://127.0.0.1:8848/nacos/test", header, "body", String.class); assertTrue(result.ok()); assertEquals(Header.EMPTY, result.getHeader()); assertEquals("test", result.getData()); @@ -264,13 +269,13 @@ public void testPostJson() throws Exception { } @Test - public void testPostJsonWithQuery() throws Exception { + void testPostJsonWithQuery() throws Exception { when(requestClient.execute(any(), eq("POST"), any())).thenReturn(mockResponse); when(mockResponse.getStatusCode()).thenReturn(200); when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes())); Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML); - HttpRestResult result = restTemplate - .postJson("http://127.0.0.1:8848/nacos/test", header, Query.EMPTY, "body", String.class); + HttpRestResult result = restTemplate.postJson("http://127.0.0.1:8848/nacos/test", header, Query.EMPTY, "body", + String.class); assertTrue(result.ok()); assertEquals(Header.EMPTY, result.getHeader()); assertEquals("test", result.getData()); @@ -278,13 +283,13 @@ public void testPostJsonWithQuery() throws Exception { } @Test - public void testPostForm() throws Exception { + void testPostForm() throws Exception { when(requestClient.execute(any(), eq("POST"), any())).thenReturn(mockResponse); when(mockResponse.getStatusCode()).thenReturn(200); when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes())); Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML); - HttpRestResult result = restTemplate - .postForm("http://127.0.0.1:8848/nacos/test", header, new HashMap<>(), String.class); + HttpRestResult result = restTemplate.postForm("http://127.0.0.1:8848/nacos/test", header, new HashMap<>(), + String.class); assertTrue(result.ok()); assertEquals(Header.EMPTY, result.getHeader()); assertEquals("test", result.getData()); @@ -292,13 +297,13 @@ public void testPostForm() throws Exception { } @Test - public void testPostFormWithQuery() throws Exception { + void testPostFormWithQuery() throws Exception { when(requestClient.execute(any(), eq("POST"), any())).thenReturn(mockResponse); when(mockResponse.getStatusCode()).thenReturn(200); when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes())); Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML); - HttpRestResult result = restTemplate - .postForm("http://127.0.0.1:8848/nacos/test", header, Query.EMPTY, new HashMap<>(), String.class); + HttpRestResult result = restTemplate.postForm("http://127.0.0.1:8848/nacos/test", header, Query.EMPTY, + new HashMap<>(), String.class); assertTrue(result.ok()); assertEquals(Header.EMPTY, result.getHeader()); assertEquals("test", result.getData()); @@ -306,14 +311,14 @@ public void testPostFormWithQuery() throws Exception { } @Test - public void testPostFormWithConfig() throws Exception { + void testPostFormWithConfig() throws Exception { when(requestClient.execute(any(), eq("POST"), any())).thenReturn(mockResponse); when(mockResponse.getStatusCode()).thenReturn(200); when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes())); HttpClientConfig config = HttpClientConfig.builder().setConTimeOutMillis(1000).build(); Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML); - HttpRestResult result = restTemplate - .postForm("http://127.0.0.1:8848/nacos/test", config, header, new HashMap<>(), String.class); + HttpRestResult result = restTemplate.postForm("http://127.0.0.1:8848/nacos/test", config, header, new HashMap<>(), + String.class); assertTrue(result.ok()); assertEquals(Header.EMPTY, result.getHeader()); assertEquals("test", result.getData()); @@ -321,14 +326,13 @@ public void testPostFormWithConfig() throws Exception { } @Test - public void testExchangeForm() throws Exception { + void testExchangeForm() throws Exception { when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse); when(mockResponse.getStatusCode()).thenReturn(200); when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes())); Header header = Header.newInstance().setContentType(MediaType.APPLICATION_XML); - HttpRestResult result = restTemplate - .exchangeForm("http://127.0.0.1:8848/nacos/test", header, Query.EMPTY, new HashMap<>(), "PUT", - String.class); + HttpRestResult result = restTemplate.exchangeForm("http://127.0.0.1:8848/nacos/test", header, Query.EMPTY, + new HashMap<>(), "PUT", String.class); assertTrue(result.ok()); assertEquals(Header.EMPTY, result.getHeader()); assertEquals("test", result.getData()); @@ -336,21 +340,20 @@ public void testExchangeForm() throws Exception { } @Test - public void testExchange() throws Exception { + void testExchange() throws Exception { when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse); when(mockResponse.getStatusCode()).thenReturn(200); when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes())); HttpClientConfig config = HttpClientConfig.builder().setConTimeOutMillis(1000).build(); - HttpRestResult result = restTemplate - .exchange("http://127.0.0.1:8848/nacos/test", config, Header.EMPTY, Query.EMPTY, new Object(), "PUT", - String.class); + HttpRestResult result = restTemplate.exchange("http://127.0.0.1:8848/nacos/test", config, Header.EMPTY, + Query.EMPTY, new Object(), "PUT", String.class); assertTrue(result.ok()); assertEquals(Header.EMPTY, result.getHeader()); assertEquals("test", result.getData()); } @Test - public void testGetInterceptors() { + void testGetInterceptors() { assertTrue(restTemplate.getInterceptors().isEmpty()); restTemplate.setInterceptors(Collections.singletonList(interceptor)); assertEquals(1, restTemplate.getInterceptors().size()); diff --git a/common/src/test/java/com/alibaba/nacos/common/http/client/handler/BeanResponseHandlerTest.java b/common/src/test/java/com/alibaba/nacos/common/http/client/handler/BeanResponseHandlerTest.java index 7d6fe48ce62..2c33f80244e 100644 --- a/common/src/test/java/com/alibaba/nacos/common/http/client/handler/BeanResponseHandlerTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/http/client/handler/BeanResponseHandlerTest.java @@ -20,22 +20,22 @@ 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.Test; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.LinkedList; 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; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class BeanResponseHandlerTest { +class BeanResponseHandlerTest { @Test - public void testConvertResult() throws Exception { + void testConvertResult() throws Exception { List testCase = new LinkedList<>(); for (int i = 0; i < 10; i++) { testCase.add(i); diff --git a/common/src/test/java/com/alibaba/nacos/common/http/client/handler/RestResultResponseHandlerTest.java b/common/src/test/java/com/alibaba/nacos/common/http/client/handler/RestResultResponseHandlerTest.java index 19e85fc4065..35a940b7af7 100644 --- a/common/src/test/java/com/alibaba/nacos/common/http/client/handler/RestResultResponseHandlerTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/http/client/handler/RestResultResponseHandlerTest.java @@ -21,19 +21,19 @@ import com.alibaba.nacos.common.http.param.Header; import com.alibaba.nacos.common.model.RestResult; import com.alibaba.nacos.common.utils.JacksonUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.InputStream; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class RestResultResponseHandlerTest { +class RestResultResponseHandlerTest { @Test - public void testConvertResult() throws Exception { + void testConvertResult() throws Exception { RestResult testCase = RestResult.builder().withCode(200).withData("ok").withMsg("msg").build(); InputStream inputStream = new ByteArrayInputStream(JacksonUtils.toJsonBytes(testCase)); HttpClientResponse response = mock(HttpClientResponse.class); diff --git a/common/src/test/java/com/alibaba/nacos/common/http/client/request/DefaultAsyncHttpClientRequestTest.java b/common/src/test/java/com/alibaba/nacos/common/http/client/request/DefaultAsyncHttpClientRequestTest.java index 9d1df552c94..31028b8caf4 100644 --- a/common/src/test/java/com/alibaba/nacos/common/http/client/request/DefaultAsyncHttpClientRequestTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/http/client/request/DefaultAsyncHttpClientRequestTest.java @@ -28,12 +28,12 @@ import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; import org.apache.http.impl.nio.reactor.ExceptionEvent; -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.net.URI; import java.util.Collections; @@ -41,14 +41,16 @@ import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; 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 DefaultAsyncHttpClientRequestTest { +@ExtendWith(MockitoExtension.class) +class DefaultAsyncHttpClientRequestTest { + + DefaultAsyncHttpClientRequest httpClientRequest; @Mock private CloseableHttpAsyncClient client; @@ -64,24 +66,22 @@ public class DefaultAsyncHttpClientRequestTest { private RequestConfig defaultConfig; - DefaultAsyncHttpClientRequest httpClientRequest; - private URI uri; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { defaultConfig = RequestConfig.DEFAULT; httpClientRequest = new DefaultAsyncHttpClientRequest(client, ioReactor, defaultConfig); uri = URI.create("http://127.0.0.1:8080"); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { httpClientRequest.close(); } @Test - public void testExecuteOnFail() throws Exception { + void testExecuteOnFail() throws Exception { Header header = Header.newInstance(); Map body = new HashMap<>(); body.put("test", "test"); @@ -96,7 +96,7 @@ public void testExecuteOnFail() throws Exception { } @Test - public void testExecuteOnCancel() throws Exception { + void testExecuteOnCancel() throws Exception { Header header = Header.newInstance(); Map body = new HashMap<>(); body.put("test", "test"); @@ -110,7 +110,7 @@ public void testExecuteOnCancel() throws Exception { } @Test - public void testExecuteOnComplete() throws Exception { + void testExecuteOnComplete() throws Exception { Header header = Header.newInstance(); Map body = new HashMap<>(); body.put("test", "test"); @@ -127,7 +127,7 @@ public void testExecuteOnComplete() throws Exception { } @Test - public void testExecuteOnCompleteWithException() throws Exception { + void testExecuteOnCompleteWithException() throws Exception { Header header = Header.newInstance(); Map body = new HashMap<>(); body.put("test", "test"); @@ -144,7 +144,7 @@ public void testExecuteOnCompleteWithException() throws Exception { } @Test - public void testExecuteException() throws Exception { + void testExecuteException() throws Exception { Header header = Header.newInstance(); Map body = new HashMap<>(); body.put("test", "test"); diff --git a/common/src/test/java/com/alibaba/nacos/common/http/client/request/DefaultHttpClientRequestTest.java b/common/src/test/java/com/alibaba/nacos/common/http/client/request/DefaultHttpClientRequestTest.java index 8fdcf2a084c..4af22b43a21 100644 --- a/common/src/test/java/com/alibaba/nacos/common/http/client/request/DefaultHttpClientRequestTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/http/client/request/DefaultHttpClientRequestTest.java @@ -29,24 +29,26 @@ import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.impl.client.CloseableHttpClient; -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.net.URI; import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class DefaultHttpClientRequestTest { +@ExtendWith(MockitoExtension.class) +class DefaultHttpClientRequestTest { + + DefaultHttpClientRequest httpClientRequest; @Mock private CloseableHttpClient client; @@ -56,16 +58,14 @@ public class DefaultHttpClientRequestTest { private RequestConfig defaultConfig; - DefaultHttpClientRequest httpClientRequest; - private boolean isForm; private boolean withConfig; private URI uri; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { defaultConfig = RequestConfig.DEFAULT; httpClientRequest = new DefaultHttpClientRequest(client, defaultConfig); when(client.execute(argThat(httpUriRequest -> { @@ -81,18 +81,17 @@ public void setUp() throws Exception { } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { isForm = false; withConfig = false; httpClientRequest.close(); } @Test - public void testExecuteForFormWithoutConfig() throws Exception { + void testExecuteForFormWithoutConfig() throws Exception { isForm = true; - Header header = Header.newInstance() - .addParam(HttpHeaderConsts.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED); + Header header = Header.newInstance().addParam(HttpHeaderConsts.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED); Map body = new HashMap<>(); body.put("test", "test"); RequestHttpEntity httpEntity = new RequestHttpEntity(header, Query.EMPTY, body); @@ -101,21 +100,19 @@ public void testExecuteForFormWithoutConfig() throws Exception { } @Test - public void testExecuteForFormWithConfig() throws Exception { + void testExecuteForFormWithConfig() throws Exception { isForm = true; withConfig = true; - Header header = Header.newInstance() - .addParam(HttpHeaderConsts.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED); + Header header = Header.newInstance().addParam(HttpHeaderConsts.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED); Map body = new HashMap<>(); body.put("test", "test"); - RequestHttpEntity httpEntity = new RequestHttpEntity(HttpClientConfig.builder().build(), header, Query.EMPTY, - body); + RequestHttpEntity httpEntity = new RequestHttpEntity(HttpClientConfig.builder().build(), header, Query.EMPTY, body); HttpClientResponse actual = httpClientRequest.execute(uri, "PUT", httpEntity); assertEquals(response, getActualResponse(actual)); } @Test - public void testExecuteForOther() throws Exception { + void testExecuteForOther() throws Exception { Header header = Header.newInstance(); RequestHttpEntity httpEntity = new RequestHttpEntity(header, Query.EMPTY, "body"); HttpClientResponse actual = httpClientRequest.execute(uri, "PUT", httpEntity); diff --git a/common/src/test/java/com/alibaba/nacos/common/http/client/request/JdkHttpClientRequestTest.java b/common/src/test/java/com/alibaba/nacos/common/http/client/request/JdkHttpClientRequestTest.java index 674ec69565e..1208fe89414 100644 --- a/common/src/test/java/com/alibaba/nacos/common/http/client/request/JdkHttpClientRequestTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/http/client/request/JdkHttpClientRequestTest.java @@ -23,12 +23,14 @@ import com.alibaba.nacos.common.http.param.MediaType; import com.alibaba.nacos.common.http.param.Query; import com.alibaba.nacos.common.model.RequestHttpEntity; -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 org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import java.io.OutputStream; import java.lang.reflect.Field; @@ -39,7 +41,7 @@ import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; @@ -47,8 +49,12 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class JdkHttpClientRequestTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class JdkHttpClientRequestTest { + + JdkHttpClientRequest httpClientRequest; @Mock private HttpURLConnection connection; @@ -62,12 +68,10 @@ public class JdkHttpClientRequestTest { @Mock private OutputStream outputStream; - JdkHttpClientRequest httpClientRequest; - private HttpClientConfig httpClientConfig; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { when(uri.toURL()).thenReturn(url); when(url.openConnection()).thenReturn(connection); when(connection.getOutputStream()).thenReturn(outputStream); @@ -75,13 +79,13 @@ public void setUp() throws Exception { httpClientRequest = new JdkHttpClientRequest(httpClientConfig); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { httpClientRequest.close(); } @Test - public void testExecuteNormal() throws Exception { + void testExecuteNormal() throws Exception { Header header = Header.newInstance(); HttpClientConfig config = HttpClientConfig.builder().build(); RequestHttpEntity httpEntity = new RequestHttpEntity(config, header, Query.EMPTY, "a=bo&dy"); @@ -92,7 +96,7 @@ public void testExecuteNormal() throws Exception { } @Test - public void testExecuteForm() throws Exception { + void testExecuteForm() throws Exception { Header header = Header.newInstance(); header.setContentType(MediaType.APPLICATION_FORM_URLENCODED); HttpClientConfig config = HttpClientConfig.builder().build(); @@ -100,14 +104,13 @@ public void testExecuteForm() throws Exception { body.put("a", "bo&dy"); RequestHttpEntity httpEntity = new RequestHttpEntity(config, header, Query.EMPTY, body); HttpClientResponse response = httpClientRequest.execute(uri, "GET", httpEntity); - byte[] writeBytes = HttpUtils.encodingParams(body, StandardCharsets.UTF_8.name()) - .getBytes(StandardCharsets.UTF_8); + byte[] writeBytes = HttpUtils.encodingParams(body, StandardCharsets.UTF_8.name()).getBytes(StandardCharsets.UTF_8); verify(outputStream).write(writeBytes, 0, writeBytes.length); assertEquals(connection, getActualConnection(response)); } @Test - public void testExecuteEmptyBody() throws Exception { + void testExecuteEmptyBody() throws Exception { Header header = Header.newInstance(); RequestHttpEntity httpEntity = new RequestHttpEntity(header, Query.EMPTY); HttpClientResponse response = httpClientRequest.execute(uri, "GET", httpEntity); @@ -116,8 +119,7 @@ public void testExecuteEmptyBody() throws Exception { } - private HttpURLConnection getActualConnection(HttpClientResponse actual) - throws IllegalAccessException, NoSuchFieldException { + private HttpURLConnection getActualConnection(HttpClientResponse actual) throws IllegalAccessException, NoSuchFieldException { Field field = actual.getClass().getDeclaredField("conn"); field.setAccessible(true); return (HttpURLConnection) field.get(actual); diff --git a/common/src/test/java/com/alibaba/nacos/common/http/client/response/DefaultClientHttpResponseTest.java b/common/src/test/java/com/alibaba/nacos/common/http/client/response/DefaultClientHttpResponseTest.java index 7c10f841a41..463b9204ff2 100644 --- a/common/src/test/java/com/alibaba/nacos/common/http/client/response/DefaultClientHttpResponseTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/http/client/response/DefaultClientHttpResponseTest.java @@ -20,21 +20,27 @@ import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; -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 org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import java.io.IOException; import java.io.InputStream; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class DefaultClientHttpResponseTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class DefaultClientHttpResponseTest { + + DefaultClientHttpResponse clientHttpResponse; @Mock private HttpResponse response; @@ -51,10 +57,8 @@ public class DefaultClientHttpResponseTest { @Mock private Header header; - DefaultClientHttpResponse clientHttpResponse; - - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { when(httpEntity.getContent()).thenReturn(inputStream); when(response.getEntity()).thenReturn(httpEntity); when(response.getStatusLine()).thenReturn(statusLine); @@ -64,36 +68,36 @@ public void setUp() throws Exception { clientHttpResponse = new DefaultClientHttpResponse(response); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { clientHttpResponse.close(); } @Test - public void testGetStatusCode() { + void testGetStatusCode() { when(statusLine.getStatusCode()).thenReturn(200); assertEquals(200, clientHttpResponse.getStatusCode()); } @Test - public void testGetStatusText() { + void testGetStatusText() { when(statusLine.getReasonPhrase()).thenReturn("test"); assertEquals("test", clientHttpResponse.getStatusText()); } @Test - public void testGetHeaders() { + void testGetHeaders() { assertEquals(3, clientHttpResponse.getHeaders().getHeader().size()); assertEquals("testValue", clientHttpResponse.getHeaders().getValue("testName")); } @Test - public void testGetBody() throws IOException { + void testGetBody() throws IOException { assertEquals(inputStream, clientHttpResponse.getBody()); } @Test - public void testCloseResponseWithException() { + void testCloseResponseWithException() { when(response.getEntity()).thenThrow(new RuntimeException("test")); clientHttpResponse.close(); } diff --git a/common/src/test/java/com/alibaba/nacos/common/http/client/response/JdkClientHttpResponseTest.java b/common/src/test/java/com/alibaba/nacos/common/http/client/response/JdkClientHttpResponseTest.java index 438f783b5ef..f25c9835a08 100644 --- a/common/src/test/java/com/alibaba/nacos/common/http/client/response/JdkClientHttpResponseTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/http/client/response/JdkClientHttpResponseTest.java @@ -18,12 +18,14 @@ import com.alibaba.nacos.common.constant.HttpHeaderConsts; import com.alibaba.nacos.common.utils.IoUtils; -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 org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -35,11 +37,15 @@ import java.util.List; import java.util.Map; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class JdkClientHttpResponseTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class JdkClientHttpResponseTest { + + JdkHttpClientResponse clientHttpResponse; @Mock private HttpURLConnection connection; @@ -49,47 +55,45 @@ public class JdkClientHttpResponseTest { private Map> headers; - JdkHttpClientResponse clientHttpResponse; - - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { headers = new HashMap<>(); headers.put("testName", Collections.singletonList("testValue")); when(connection.getHeaderFields()).thenReturn(headers); clientHttpResponse = new JdkHttpClientResponse(connection); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { clientHttpResponse.close(); } @Test - public void testGetStatusCode() throws IOException { + void testGetStatusCode() throws IOException { when(connection.getResponseCode()).thenReturn(200); assertEquals(200, clientHttpResponse.getStatusCode()); } @Test - public void testGetStatusText() throws IOException { + void testGetStatusText() throws IOException { when(connection.getResponseMessage()).thenReturn("test"); assertEquals("test", clientHttpResponse.getStatusText()); } @Test - public void testGetHeaders() { + void testGetHeaders() { assertEquals(3, clientHttpResponse.getHeaders().getHeader().size()); assertEquals("testValue", clientHttpResponse.getHeaders().getValue("testName")); } @Test - public void testGetBody() throws IOException { + void testGetBody() throws IOException { when(connection.getInputStream()).thenReturn(inputStream); assertEquals(inputStream, clientHttpResponse.getBody()); } @Test - public void testGetBodyWithGzip() throws IOException { + void testGetBodyWithGzip() throws IOException { byte[] testCase = IoUtils.tryCompress("test", StandardCharsets.UTF_8.name()); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(testCase); when(connection.getInputStream()).thenReturn(byteArrayInputStream); diff --git a/common/src/test/java/com/alibaba/nacos/common/http/param/HeaderTest.java b/common/src/test/java/com/alibaba/nacos/common/http/param/HeaderTest.java index 9205c0045bb..02ffef1df26 100644 --- a/common/src/test/java/com/alibaba/nacos/common/http/param/HeaderTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/http/param/HeaderTest.java @@ -17,7 +17,7 @@ package com.alibaba.nacos.common.http.param; import com.alibaba.nacos.common.constant.HttpHeaderConsts; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collections; @@ -25,13 +25,14 @@ 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; -public class HeaderTest { +class HeaderTest { @Test - public void testSetContentType() { + void testSetContentType() { Header header = Header.newInstance(); header.setContentType(null); assertEquals(MediaType.APPLICATION_JSON, header.getValue(HttpHeaderConsts.CONTENT_TYPE)); @@ -40,14 +41,14 @@ public void testSetContentType() { } @Test - public void testHeaderKyeIgnoreCase() { + void testHeaderKyeIgnoreCase() { Header header = Header.newInstance(); header.addParam("Content-Encoding", "gzip"); assertEquals("gzip", header.getValue("content-encoding")); } @Test - public void testToList() { + void testToList() { Header header = Header.newInstance(); List list = header.toList(); assertTrue(list.contains(HttpHeaderConsts.CONTENT_TYPE)); @@ -59,7 +60,7 @@ public void testToList() { } @Test - public void testAddAllForMap() { + void testAddAllForMap() { Map map = new HashMap<>(); map.put("test1", "test2"); map.put("test3", "test4"); @@ -71,7 +72,7 @@ public void testAddAllForMap() { } @Test - public void testAddAllForList() { + void testAddAllForList() { List list = new ArrayList<>(4); list.add("test1"); list.add("test2"); @@ -84,18 +85,20 @@ public void testAddAllForList() { assertEquals(4, header.getHeader().size()); } - @Test(expected = IllegalArgumentException.class) - public void testAddAllForListWithWrongLength() { - List list = new ArrayList<>(3); - list.add("test1"); - list.add("test2"); - list.add("test3"); - Header header = Header.newInstance(); - header.addAll(list); + @Test + void testAddAllForListWithWrongLength() { + assertThrows(IllegalArgumentException.class, () -> { + List list = new ArrayList<>(3); + list.add("test1"); + list.add("test2"); + list.add("test3"); + Header header = Header.newInstance(); + header.addAll(list); + }); } @Test - public void testAddOriginalResponseHeader() { + void testAddOriginalResponseHeader() { List list = new ArrayList<>(4); list.add("test1"); list.add("test2"); @@ -109,7 +112,7 @@ public void testAddOriginalResponseHeader() { } @Test - public void testGetCharset() { + void testGetCharset() { Header header = Header.newInstance(); assertEquals("UTF-8", header.getCharset()); header.addParam(HttpHeaderConsts.ACCEPT_CHARSET, null); @@ -124,7 +127,7 @@ public void testGetCharset() { } @Test - public void testClear() { + void testClear() { Header header = Header.newInstance(); header.addOriginalResponseHeader("test", Collections.singletonList("test")); assertEquals(3, header.getHeader().size()); diff --git a/common/src/test/java/com/alibaba/nacos/common/http/param/MediaTypeTest.java b/common/src/test/java/com/alibaba/nacos/common/http/param/MediaTypeTest.java index 86493082e2a..a4ae8f1b494 100644 --- a/common/src/test/java/com/alibaba/nacos/common/http/param/MediaTypeTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/http/param/MediaTypeTest.java @@ -16,19 +16,20 @@ package com.alibaba.nacos.common.http.param; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * MediaTypeTest. * * @author mai.jh */ -public class MediaTypeTest { +class MediaTypeTest { @Test - public void testValueOf() { + void testValueOf() { MediaType mediaType = MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED); String type = "application/x-www-form-urlencoded"; String charset = "UTF-8"; @@ -38,7 +39,7 @@ public void testValueOf() { } @Test - public void testValueOf2() { + void testValueOf2() { MediaType mediaType = MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED, "ISO-8859-1"); String type = "application/x-www-form-urlencoded"; String charset = "ISO-8859-1"; @@ -49,7 +50,7 @@ public void testValueOf2() { } @Test - public void testValueOf3() { + void testValueOf3() { MediaType mediaType = MediaType.valueOf("application/x-www-form-urlencoded", "ISO-8859-1"); String type = "application/x-www-form-urlencoded"; String charset = "ISO-8859-1"; @@ -59,13 +60,17 @@ public void testValueOf3() { assertEquals(excepted, mediaType.toString()); } - @Test(expected = IllegalArgumentException.class) - public void testValueOfWithEmpty() { - MediaType.valueOf(""); + @Test + void testValueOfWithEmpty() { + assertThrows(IllegalArgumentException.class, () -> { + MediaType.valueOf(""); + }); } - @Test(expected = IllegalArgumentException.class) - public void testValueOfWithEmpty2() { - MediaType.valueOf("", "UTF-8"); + @Test + void testValueOfWithEmpty2() { + assertThrows(IllegalArgumentException.class, () -> { + MediaType.valueOf("", "UTF-8"); + }); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/http/param/QueryTest.java b/common/src/test/java/com/alibaba/nacos/common/http/param/QueryTest.java index d3196160f2a..6f85fd7e0c3 100644 --- a/common/src/test/java/com/alibaba/nacos/common/http/param/QueryTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/http/param/QueryTest.java @@ -17,21 +17,21 @@ package com.alibaba.nacos.common.http.param; import com.alibaba.nacos.api.naming.CommonParams; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; 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 QueryTest { +class QueryTest { @Test - public void testInitParams() { + void testInitParams() { Map parameters = new LinkedHashMap(); parameters.put(CommonParams.NAMESPACE_ID, "namespace"); parameters.put(CommonParams.SERVICE_NAME, "service"); @@ -48,17 +48,18 @@ public void testInitParams() { } @Test - public void testAddParams() throws Exception { + void testAddParams() throws Exception { Query query = Query.newInstance().addParam("key-1", "value-1").addParam("key-2", "value-2"); String s1 = query.toQueryUrl(); - String s2 = "key-1=" + URLEncoder.encode("value-1", StandardCharsets.UTF_8.name()) + "&key-2=" + URLEncoder - .encode("value-2", StandardCharsets.UTF_8.name()); + String s2 = + "key-1=" + URLEncoder.encode("value-1", StandardCharsets.UTF_8.name()) + "&key-2=" + URLEncoder.encode("value-2", + StandardCharsets.UTF_8.name()); assertEquals(s2, s1); assertEquals("value-1", query.getValue("key-1")); } @Test - public void testClear() { + void testClear() { Query query = Query.newInstance().addParam("key-1", "value-1").addParam("key-2", "value-2"); assertFalse(query.isEmpty()); assertEquals("value-1", query.getValue("key-1")); diff --git a/common/src/test/java/com/alibaba/nacos/common/labels/impl/DefaultLabelsCollectorManagerTest.java b/common/src/test/java/com/alibaba/nacos/common/labels/impl/DefaultLabelsCollectorManagerTest.java index f011438c523..f624436412f 100644 --- a/common/src/test/java/com/alibaba/nacos/common/labels/impl/DefaultLabelsCollectorManagerTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/labels/impl/DefaultLabelsCollectorManagerTest.java @@ -17,38 +17,39 @@ package com.alibaba.nacos.common.labels.impl; import com.alibaba.nacos.api.common.Constants; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Map; import java.util.Properties; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * description. * * @author rong * @date 2024-02-29 20:13 */ -public class DefaultLabelsCollectorManagerTest { +class DefaultLabelsCollectorManagerTest { @Test - public void tagV2LabelsCollectorTest() { + void tagV2LabelsCollectorTest() { Properties properties = new Properties(); properties.put(Constants.APP_CONN_LABELS_KEY, "k1=v1,gray=properties_pre"); properties.put(Constants.CONFIG_GRAY_LABEL, "properties_after"); DefaultLabelsCollectorManager defaultLabelsCollectorManager = new DefaultLabelsCollectorManager(); Map labels = defaultLabelsCollectorManager.getLabels(properties); - Assert.assertEquals("properties_after", labels.get(Constants.CONFIG_GRAY_LABEL)); - Assert.assertEquals("v1", labels.get("k1")); + assertEquals("properties_after", labels.get(Constants.CONFIG_GRAY_LABEL)); + assertEquals("v1", labels.get("k1")); } @Test - public void tagV2LabelsCollectorOrderTest() { + void tagV2LabelsCollectorOrderTest() { Properties properties = new Properties(); DefaultLabelsCollectorManager defaultLabelsCollectorManager = new DefaultLabelsCollectorManager(); Map labels = defaultLabelsCollectorManager.getLabels(properties); String test = labels.get("test"); - Assert.assertEquals("test2", test); + assertEquals("test2", test); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/logging/NacosLoggingPropertiesTest.java b/common/src/test/java/com/alibaba/nacos/common/logging/NacosLoggingPropertiesTest.java index e823da97797..1224832cdc7 100644 --- a/common/src/test/java/com/alibaba/nacos/common/logging/NacosLoggingPropertiesTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/logging/NacosLoggingPropertiesTest.java @@ -16,58 +16,58 @@ package com.alibaba.nacos.common.logging; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Properties; -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; -public class NacosLoggingPropertiesTest { +class NacosLoggingPropertiesTest { NacosLoggingProperties loggingProperties; Properties properties; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { properties = new Properties(); loggingProperties = new NacosLoggingProperties("classpath:test.xml", properties); } @Test - public void testGetLocationWithDefault() { + void testGetLocationWithDefault() { assertEquals("classpath:test.xml", loggingProperties.getLocation()); } @Test - public void testGetLocationWithoutDefault() { + void testGetLocationWithoutDefault() { properties.setProperty("nacos.logging.default.config.enabled", "false"); assertNull(loggingProperties.getLocation()); } @Test - public void testGetLocationForSpecified() { + void testGetLocationForSpecified() { properties.setProperty("nacos.logging.config", "classpath:specified-test.xml"); properties.setProperty("nacos.logging.default.config.enabled", "false"); assertEquals("classpath:specified-test.xml", loggingProperties.getLocation()); } @Test - public void testGetLocationForSpecifiedWithDefault() { + void testGetLocationForSpecifiedWithDefault() { properties.setProperty("nacos.logging.config", "classpath:specified-test.xml"); assertEquals("classpath:specified-test.xml", loggingProperties.getLocation()); } @Test - public void testGetReloadInternal() { + void testGetReloadInternal() { properties.setProperty("nacos.logging.reload.interval.seconds", "50000"); assertEquals(50000L, loggingProperties.getReloadInternal()); } @Test - public void testGetValue() { + void testGetValue() { properties.setProperty("test.key", "test.value"); assertEquals("test.value", loggingProperties.getValue("test.key", "default.value")); properties.clear(); diff --git a/common/src/test/java/com/alibaba/nacos/common/model/RequestHttpEntityTest.java b/common/src/test/java/com/alibaba/nacos/common/model/RequestHttpEntityTest.java index 3abfaeead32..e1d0b438625 100644 --- a/common/src/test/java/com/alibaba/nacos/common/model/RequestHttpEntityTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/model/RequestHttpEntityTest.java @@ -19,20 +19,20 @@ import com.alibaba.nacos.common.http.HttpClientConfig; import com.alibaba.nacos.common.http.param.Header; import com.alibaba.nacos.common.http.param.Query; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.HashMap; -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; -@RunWith(MockitoJUnitRunner.class) -public class RequestHttpEntityTest { +@ExtendWith(MockitoExtension.class) +class RequestHttpEntityTest { Header header; @@ -42,8 +42,8 @@ public class RequestHttpEntityTest { Object body; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { header = Header.newInstance(); header.addParam("testHeader", "test"); query = Query.newInstance(); @@ -53,7 +53,7 @@ public void setUp() throws Exception { } @Test - public void testConstructWithoutConfigAndBody() { + void testConstructWithoutConfigAndBody() { RequestHttpEntity entity = new RequestHttpEntity(header, query); assertTrue(entity.isEmptyBody()); assertNull(entity.getHttpClientConfig()); @@ -63,7 +63,7 @@ public void testConstructWithoutConfigAndBody() { } @Test - public void testConstructWithoutConfigAndQuery() { + void testConstructWithoutConfigAndQuery() { RequestHttpEntity entity = new RequestHttpEntity(header, body); assertFalse(entity.isEmptyBody()); assertNull(entity.getHttpClientConfig()); @@ -73,7 +73,7 @@ public void testConstructWithoutConfigAndQuery() { } @Test - public void testConstructWithoutConfig() { + void testConstructWithoutConfig() { RequestHttpEntity entity = new RequestHttpEntity(header, query, body); assertFalse(entity.isEmptyBody()); assertNull(entity.getHttpClientConfig()); @@ -83,7 +83,7 @@ public void testConstructWithoutConfig() { } @Test - public void testConstructFull() { + void testConstructFull() { RequestHttpEntity entity = new RequestHttpEntity(clientConfig, header, query, body); assertFalse(entity.isEmptyBody()); assertEquals(clientConfig, entity.getHttpClientConfig()); diff --git a/common/src/test/java/com/alibaba/nacos/common/model/RestResultTest.java b/common/src/test/java/com/alibaba/nacos/common/model/RestResultTest.java index 4e66227d050..b82bed6236c 100644 --- a/common/src/test/java/com/alibaba/nacos/common/model/RestResultTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/model/RestResultTest.java @@ -17,15 +17,15 @@ package com.alibaba.nacos.common.model; import com.alibaba.nacos.common.utils.JacksonUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; -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 RestResultTest { +class RestResultTest { @Test - public void testSerialization() { + void testSerialization() { RestResult result = new RestResult<>(200, "test", "content"); String json = JacksonUtils.toJson(result); assertTrue(json.contains("\"code\":200")); @@ -34,7 +34,7 @@ public void testSerialization() { } @Test - public void testDeserialization() { + void testDeserialization() { String json = "{\"code\":200,\"message\":\"test\",\"data\":\"content\"}"; RestResult restResult = JacksonUtils.toObj(json, RestResult.class); assertEquals(200, restResult.getCode()); diff --git a/common/src/test/java/com/alibaba/nacos/common/model/RestResultUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/model/RestResultUtilsTest.java index 076f4afe5f7..3d0aa35e8f2 100644 --- a/common/src/test/java/com/alibaba/nacos/common/model/RestResultUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/model/RestResultUtilsTest.java @@ -17,68 +17,68 @@ package com.alibaba.nacos.common.model; import com.alibaba.nacos.common.model.core.IResultCode; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class RestResultUtilsTest { +class RestResultUtilsTest { @Test - public void testSuccessWithDefault() { + void testSuccessWithDefault() { RestResult restResult = RestResultUtils.success(); assertRestResult(restResult, 200, null, null, true); } @Test - public void testSuccessWithData() { + void testSuccessWithData() { RestResult restResult = RestResultUtils.success("content"); assertRestResult(restResult, 200, null, "content", true); } @Test - public void testSuccessWithMsg() { + void testSuccessWithMsg() { RestResult restResult = RestResultUtils.success("test", "content"); assertRestResult(restResult, 200, "test", "content", true); } @Test - public void testSuccessWithCode() { + void testSuccessWithCode() { RestResult restResult = RestResultUtils.success(203, "content"); assertRestResult(restResult, 203, null, "content", false); } @Test - public void testFailedWithDefault() { + void testFailedWithDefault() { RestResult restResult = RestResultUtils.failed(); assertRestResult(restResult, 500, null, null, false); } @Test - public void testFailedWithMsg() { + void testFailedWithMsg() { RestResult restResult = RestResultUtils.failed("test"); assertRestResult(restResult, 500, "test", null, false); } @Test - public void testFailedWithCode() { + void testFailedWithCode() { RestResult restResult = RestResultUtils.failed(400, "content"); assertRestResult(restResult, 400, null, "content", false); } @Test - public void testSuccessWithFull() { + void testSuccessWithFull() { RestResult restResult = RestResultUtils.failed(400, "content", "test"); assertRestResult(restResult, 400, "test", "content", false); } @Test - public void testFailedWithMsgMethod() { + void testFailedWithMsgMethod() { RestResult restResult = RestResultUtils.failedWithMsg(400, "content"); assertRestResult(restResult, 400, "content", null, false); } @Test - public void testBuildResult() { + void testBuildResult() { IResultCode mockCode = new IResultCode() { @Override public int getCode() { diff --git a/common/src/test/java/com/alibaba/nacos/common/notify/DefaultPublisherTest.java b/common/src/test/java/com/alibaba/nacos/common/notify/DefaultPublisherTest.java index 53ac32dfaec..ccc1a676abd 100644 --- a/common/src/test/java/com/alibaba/nacos/common/notify/DefaultPublisherTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/notify/DefaultPublisherTest.java @@ -17,18 +17,19 @@ package com.alibaba.nacos.common.notify; import com.alibaba.nacos.common.notify.listener.Subscriber; -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.util.concurrent.Executor; import java.util.concurrent.TimeUnit; -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.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -37,22 +38,22 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class DefaultPublisherTest { +@ExtendWith(MockitoExtension.class) +class DefaultPublisherTest { private DefaultPublisher publisher; @Mock private Subscriber subscriber; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { publisher = new DefaultPublisher(); publisher.init(MockEvent.class, 1); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { try { publisher.shutdown(); } catch (Exception ignored) { @@ -60,29 +61,31 @@ public void tearDown() throws Exception { } @Test - public void testInitWithIllegalSize() { + void testInitWithIllegalSize() { publisher.shutdown(); publisher = new DefaultPublisher(); publisher.init(MockEvent.class, -1); assertTrue(publisher.isInitialized()); } - @Test(expected = IllegalStateException.class) - public void testCheckIsStart() { - publisher.shutdown(); - publisher = new DefaultPublisher(); - publisher.checkIsStart(); + @Test + void testCheckIsStart() { + assertThrows(IllegalStateException.class, () -> { + publisher.shutdown(); + publisher = new DefaultPublisher(); + publisher.checkIsStart(); + }); } @Test - public void testCurrentEventSize() { + void testCurrentEventSize() { assertEquals(0, publisher.currentEventSize()); publisher.publish(new MockEvent()); assertEquals(1, publisher.currentEventSize()); } @Test - public void testRemoveSubscriber() { + void testRemoveSubscriber() { publisher.addSubscriber(subscriber); assertEquals(1, publisher.getSubscribers().size()); publisher.removeSubscriber(subscriber); @@ -90,7 +93,7 @@ public void testRemoveSubscriber() { } @Test - public void publishEventWhenQueueFull() { + void publishEventWhenQueueFull() { // Stop the publisher thread to mock queue full. publisher.shutdown(); publisher.publish(new MockEvent()); @@ -109,7 +112,7 @@ public void publishEventWhenQueueFull() { } @Test - public void publishEventQueueNotFull() throws InterruptedException { + void publishEventQueueNotFull() throws InterruptedException { when(subscriber.scopeMatches(any(MockEvent.class))).thenReturn(true); MockEvent mockEvent = new MockEvent(); // Make sure Publisher entry waiting subscribers. @@ -131,7 +134,7 @@ public void publishEventQueueNotFull() throws InterruptedException { } @Test - public void testHandleEventWithThrowable() throws InterruptedException { + void testHandleEventWithThrowable() throws InterruptedException { when(subscriber.scopeMatches(any(MockEvent.class))).thenReturn(true); doThrow(new RuntimeException("test")).when(subscriber).onEvent(any(MockEvent.class)); publisher.addSubscriber(subscriber); @@ -141,7 +144,7 @@ public void testHandleEventWithThrowable() throws InterruptedException { } @Test - public void testHandleEventWithExecutor() throws InterruptedException { + void testHandleEventWithExecutor() throws InterruptedException { Executor executor = mock(Executor.class); when(subscriber.scopeMatches(any(MockEvent.class))).thenReturn(true); when(subscriber.executor()).thenReturn(executor); @@ -152,7 +155,7 @@ public void testHandleEventWithExecutor() throws InterruptedException { } @Test - public void testReceiveEventWithException() throws InterruptedException { + void testReceiveEventWithException() throws InterruptedException { Executor executor = mock(Executor.class); when(subscriber.scopeMatches(any(MockEvent.class))).thenReturn(true); when(subscriber.executor()).thenThrow(new RuntimeException("test")); diff --git a/common/src/test/java/com/alibaba/nacos/common/notify/DefaultSharePublisherTest.java b/common/src/test/java/com/alibaba/nacos/common/notify/DefaultSharePublisherTest.java index 585c9d55e6e..3d297743186 100644 --- a/common/src/test/java/com/alibaba/nacos/common/notify/DefaultSharePublisherTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/notify/DefaultSharePublisherTest.java @@ -17,25 +17,25 @@ package com.alibaba.nacos.common.notify; import com.alibaba.nacos.common.notify.listener.SmartSubscriber; -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.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class DefaultSharePublisherTest { +@ExtendWith(MockitoExtension.class) +class DefaultSharePublisherTest { private static final AtomicLong TEST_SEQUENCE = new AtomicLong(); @@ -47,19 +47,19 @@ public class DefaultSharePublisherTest { @Mock SmartSubscriber smartSubscriber2; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { defaultSharePublisher = new DefaultSharePublisher(); defaultSharePublisher.init(SlowEvent.class, 2); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { defaultSharePublisher.shutdown(); } @Test - public void testRemoveSubscribers() { + void testRemoveSubscribers() { defaultSharePublisher.addSubscriber(smartSubscriber1, MockSlowEvent1.class); defaultSharePublisher.addSubscriber(smartSubscriber1, MockSlowEvent2.class); defaultSharePublisher.addSubscriber(smartSubscriber2, MockSlowEvent2.class); @@ -71,7 +71,7 @@ public void testRemoveSubscribers() { } @Test - public void testReceiveEventWithoutSubscriber() { + void testReceiveEventWithoutSubscriber() { defaultSharePublisher.addSubscriber(smartSubscriber1, MockSlowEvent1.class); defaultSharePublisher.addSubscriber(smartSubscriber2, MockSlowEvent2.class); defaultSharePublisher.receiveEvent(new SlowEvent() { @@ -87,7 +87,7 @@ public long sequence() { } @Test - public void testReceiveEventWithSubscriber() { + void testReceiveEventWithSubscriber() { defaultSharePublisher.addSubscriber(smartSubscriber1, MockSlowEvent1.class); defaultSharePublisher.addSubscriber(smartSubscriber2, MockSlowEvent2.class); defaultSharePublisher.receiveEvent(new MockSlowEvent1()); @@ -99,7 +99,7 @@ public void testReceiveEventWithSubscriber() { } @Test - public void testIgnoreExpiredEvent() throws InterruptedException { + void testIgnoreExpiredEvent() throws InterruptedException { MockSlowEvent1 mockSlowEvent1 = new MockSlowEvent1(); MockSlowEvent2 mockSlowEvent2 = new MockSlowEvent2(); defaultSharePublisher.addSubscriber(smartSubscriber1, MockSlowEvent1.class); diff --git a/common/src/test/java/com/alibaba/nacos/common/notify/NotifyCenterTest.java b/common/src/test/java/com/alibaba/nacos/common/notify/NotifyCenterTest.java index aed060a2cff..cc1c255486e 100644 --- a/common/src/test/java/com/alibaba/nacos/common/notify/NotifyCenterTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/notify/NotifyCenterTest.java @@ -20,13 +20,12 @@ import com.alibaba.nacos.common.notify.listener.SmartSubscriber; import com.alibaba.nacos.common.notify.listener.Subscriber; import com.alibaba.nacos.common.utils.ThreadUtils; -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.util.Collections; import java.util.LinkedList; @@ -36,23 +35,24 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class NotifyCenterTest { +@ExtendWith(MockitoExtension.class) +class NotifyCenterTest { + + private static AtomicInteger count; static { System.setProperty("nacos.core.notify.share-buffer-size", "8"); } - private static AtomicInteger count; - SmartSubscriber smartSubscriber; Subscriber subscriber; @@ -60,8 +60,8 @@ public class NotifyCenterTest { @Mock ShardedEventPublisher shardedEventPublisher; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { count = new AtomicInteger(); NotifyCenter.registerToSharePublisher(TestSlowEvent.class); NotifyCenter.registerToPublisher(TestSlowEvent1.class, 10); @@ -70,8 +70,8 @@ public void setUp() throws Exception { NotifyCenter.registerToPublisher(SharedEvent.class, shardedEventPublisher); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (null != smartSubscriber) { NotifyCenter.deregisterSubscriber(smartSubscriber); } @@ -83,45 +83,45 @@ public void tearDown() throws Exception { } @Test - public void testRegisterNullPublisher() { + void testRegisterNullPublisher() { int originalSize = NotifyCenter.getPublisherMap().size(); NotifyCenter.registerToPublisher(NoPublisherEvent.class, null); assertEquals(originalSize, NotifyCenter.getPublisherMap().size()); } @Test - public void testGetPublisher() { + void testGetPublisher() { assertEquals(NotifyCenter.getSharePublisher(), NotifyCenter.getPublisher(TestSlowEvent.class)); assertTrue(NotifyCenter.getPublisher(TestEvent.class) instanceof DefaultPublisher); } @Test - public void testEventsCanBeSubscribed() { + void testEventsCanBeSubscribed() { subscriber = new MockSubscriber<>(TestEvent.class, false); smartSubscriber = new MockSmartSubscriber(Collections.singletonList(TestSlowEvent.class)); NotifyCenter.registerSubscriber(subscriber); NotifyCenter.registerSubscriber(smartSubscriber); - Assert.assertTrue(NotifyCenter.publishEvent(new TestEvent())); - Assert.assertTrue(NotifyCenter.publishEvent(new TestSlowEvent())); + assertTrue(NotifyCenter.publishEvent(new TestEvent())); + assertTrue(NotifyCenter.publishEvent(new TestSlowEvent())); ThreadUtils.sleep(2000L); assertEquals(2, count.get()); } @Test - public void testCanIgnoreExpireEvent() throws Exception { + void testCanIgnoreExpireEvent() throws Exception { NotifyCenter.registerToPublisher(ExpireEvent.class, 16); CountDownLatch latch = new CountDownLatch(3); subscriber = new MockSubscriber<>(ExpireEvent.class, true, latch); NotifyCenter.registerSubscriber(subscriber); for (int i = 0; i < 3; i++) { - Assert.assertTrue(NotifyCenter.publishEvent(new ExpireEvent(3 - i))); + assertTrue(NotifyCenter.publishEvent(new ExpireEvent(3 - i))); } latch.await(5000L, TimeUnit.MILLISECONDS); assertEquals(1, count.get()); } @Test - public void testSharePublishEvent() throws InterruptedException { + void testSharePublishEvent() throws InterruptedException { CountDownLatch latch = new CountDownLatch(20); Subscriber subscriber = new MockSubscriber<>(TestSlowEvent.class, false, latch); Subscriber subscriber1 = new MockSubscriber<>(TestSlowEvent1.class, false, latch); @@ -129,8 +129,8 @@ public void testSharePublishEvent() throws InterruptedException { NotifyCenter.registerSubscriber(subscriber); NotifyCenter.registerSubscriber(subscriber1); for (int i = 0; i < 10; i++) { - Assert.assertTrue(NotifyCenter.publishEvent(new TestSlowEvent())); - Assert.assertTrue(NotifyCenter.publishEvent(new TestSlowEvent1())); + assertTrue(NotifyCenter.publishEvent(new TestSlowEvent())); + assertTrue(NotifyCenter.publishEvent(new TestSlowEvent1())); } latch.await(5000L, TimeUnit.MILLISECONDS); assertEquals(20, count.get()); @@ -141,7 +141,7 @@ public void testSharePublishEvent() throws InterruptedException { } @Test - public void testMutipleSlowEventsListenedBySmartSubscriber() throws Exception { + void testMutipleSlowEventsListenedBySmartSubscriber() throws Exception { List> subscribedEvents = new LinkedList<>(); subscribedEvents.add(TestSlowEvent.class); subscribedEvents.add(TestSlowEvent1.class); @@ -149,15 +149,15 @@ public void testMutipleSlowEventsListenedBySmartSubscriber() throws Exception { smartSubscriber = new MockSmartSubscriber(subscribedEvents, latch); NotifyCenter.registerSubscriber(smartSubscriber); for (int i = 0; i < 3; i++) { - Assert.assertTrue(NotifyCenter.publishEvent(new TestSlowEvent())); - Assert.assertTrue(NotifyCenter.publishEvent(new TestSlowEvent1())); + assertTrue(NotifyCenter.publishEvent(new TestSlowEvent())); + assertTrue(NotifyCenter.publishEvent(new TestSlowEvent1())); } latch.await(5000L, TimeUnit.MILLISECONDS); assertEquals(6, count.get()); } @Test - public void testMutipleKindsEventsCanListenBySmartsubscriber() throws Exception { + void testMutipleKindsEventsCanListenBySmartsubscriber() throws Exception { List> subscribedEvents = new LinkedList<>(); subscribedEvents.add(TestEvent.class); subscribedEvents.add(TestSlowEvent.class); @@ -165,29 +165,29 @@ public void testMutipleKindsEventsCanListenBySmartsubscriber() throws Exception smartSubscriber = new MockSmartSubscriber(subscribedEvents, latch); NotifyCenter.registerSubscriber(smartSubscriber); for (int i = 0; i < 3; i++) { - Assert.assertTrue(NotifyCenter.publishEvent(new TestEvent())); - Assert.assertTrue(NotifyCenter.publishEvent(new TestSlowEvent())); + assertTrue(NotifyCenter.publishEvent(new TestEvent())); + assertTrue(NotifyCenter.publishEvent(new TestSlowEvent())); } latch.await(5000L, TimeUnit.MILLISECONDS); assertEquals(6, count.get()); } @Test - public void testPublishEventByNoPublisher() { + void testPublishEventByNoPublisher() { for (int i = 0; i < 3; i++) { - Assert.assertFalse(NotifyCenter.publishEvent(new NoPublisherEvent())); + assertFalse(NotifyCenter.publishEvent(new NoPublisherEvent())); } } @Test - public void testPublishEventByPluginEvent() { + void testPublishEventByPluginEvent() { for (int i = 0; i < 3; i++) { - Assert.assertTrue(NotifyCenter.publishEvent(new PluginEvent())); + assertTrue(NotifyCenter.publishEvent(new PluginEvent())); } } @Test - public void testDeregisterPublisherWithException() throws NacosException { + void testDeregisterPublisherWithException() throws NacosException { final int originalSize = NotifyCenter.getPublisherMap().size(); doThrow(new RuntimeException("test")).when(shardedEventPublisher).shutdown(); NotifyCenter.getPublisherMap().put(SharedEvent.class.getCanonicalName(), shardedEventPublisher); @@ -196,14 +196,14 @@ public void testDeregisterPublisherWithException() throws NacosException { } @Test - public void testPublishEventWithException() { + void testPublishEventWithException() { when(shardedEventPublisher.publish(any(Event.class))).thenThrow(new RuntimeException("test")); NotifyCenter.getPublisherMap().put(SharedEvent.class.getCanonicalName(), shardedEventPublisher); assertFalse(NotifyCenter.publishEvent(new SharedEvent())); } @Test - public void testOperateSubscriberForShardedPublisher() { + void testOperateSubscriberForShardedPublisher() { subscriber = new MockSubscriber(SharedEvent.class, false); NotifyCenter.getPublisherMap().put(SharedEvent.class.getCanonicalName(), shardedEventPublisher); NotifyCenter.registerSubscriber(subscriber); @@ -212,14 +212,16 @@ public void testOperateSubscriberForShardedPublisher() { verify(shardedEventPublisher).removeSubscriber(subscriber, SharedEvent.class); } - @Test(expected = NoSuchElementException.class) - public void testDeregisterNonExistSubscriber() { - try { - subscriber = new MockSubscriber(NoPublisherEvent.class, false); - NotifyCenter.deregisterSubscriber(subscriber); - } finally { - subscriber = null; - } + @Test + void testDeregisterNonExistSubscriber() { + assertThrows(NoSuchElementException.class, () -> { + try { + subscriber = new MockSubscriber(NoPublisherEvent.class, false); + NotifyCenter.deregisterSubscriber(subscriber); + } finally { + subscriber = null; + } + }); } private static class MockSubscriber extends Subscriber { @@ -314,14 +316,14 @@ private static class NoPublisherEvent extends Event { } private static class SharedEvent extends Event { - + private static final long serialVersionUID = 7648766983252000074L; } private static class PluginEvent extends Event { - + private static final long serialVersionUID = -7787588724415976798L; - + @Override public boolean isPluginEvent() { return true; diff --git a/common/src/test/java/com/alibaba/nacos/common/packagescan/DefaultPackageScanTest.java b/common/src/test/java/com/alibaba/nacos/common/packagescan/DefaultPackageScanTest.java index 6eb7e07318d..07734e6c371 100644 --- a/common/src/test/java/com/alibaba/nacos/common/packagescan/DefaultPackageScanTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/packagescan/DefaultPackageScanTest.java @@ -21,11 +21,11 @@ import com.alibaba.nacos.common.packagescan.mock.TestScan; import com.alibaba.nacos.common.packagescan.resource.PathMatchingResourcePatternResolver; import com.alibaba.nacos.common.packagescan.resource.Resource; -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.io.ByteArrayInputStream; import java.io.IOException; @@ -33,44 +33,44 @@ import java.lang.reflect.Field; import java.util.Set; -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; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class DefaultPackageScanTest { +@ExtendWith(MockitoExtension.class) +class DefaultPackageScanTest { @Mock PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver; DefaultPackageScan packageScan; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { packageScan = new DefaultPackageScan(); } @Test - public void testGetSubTypesOf() { + void testGetSubTypesOf() { packageScan = new DefaultPackageScan(); - Set> subTypesOf = packageScan - .getSubTypesOf(AnnotationClass.class.getPackage().getName(), MockClass.class); + Set> subTypesOf = packageScan.getSubTypesOf(AnnotationClass.class.getPackage().getName(), + MockClass.class); assertEquals(3, subTypesOf.size()); } @Test - public void testGetTypesAnnotatedWith() { + void testGetTypesAnnotatedWith() { packageScan = new DefaultPackageScan(); - Set> actual = packageScan - .getTypesAnnotatedWith(AnnotationClass.class.getPackage().getName(), TestScan.class); + Set> actual = packageScan.getTypesAnnotatedWith(AnnotationClass.class.getPackage().getName(), + TestScan.class); assertEquals(1, actual.size()); assertEquals(AnnotationClass.class, actual.iterator().next()); } @Test - public void testGetSubTypesOfWithException() throws NoSuchFieldException, IllegalAccessException, IOException { + void testGetSubTypesOfWithException() throws NoSuchFieldException, IllegalAccessException, IOException { setResolver(); String path = AnnotationClass.class.getPackage().getName(); when(pathMatchingResourcePatternResolver.getResources(anyString())).thenThrow(new IOException("test")); @@ -79,7 +79,7 @@ public void testGetSubTypesOfWithException() throws NoSuchFieldException, Illega } @Test - public void testGetTypesAnnotatedWithException() throws NoSuchFieldException, IllegalAccessException, IOException { + void testGetTypesAnnotatedWithException() throws NoSuchFieldException, IllegalAccessException, IOException { setResolver(); String path = AnnotationClass.class.getPackage().getName(); when(pathMatchingResourcePatternResolver.getResources(anyString())).thenThrow(new IOException("test")); @@ -88,7 +88,7 @@ public void testGetTypesAnnotatedWithException() throws NoSuchFieldException, Il } @Test - public void testClassVersionNotMatch() throws NoSuchFieldException, IllegalAccessException, IOException { + void testClassVersionNotMatch() throws NoSuchFieldException, IllegalAccessException, IOException { setResolver(); Resource resource = mock(Resource.class); byte[] testCase = new byte[8]; diff --git a/common/src/test/java/com/alibaba/nacos/common/paramcheck/DefaultParamCheckerTest.java b/common/src/test/java/com/alibaba/nacos/common/paramcheck/DefaultParamCheckerTest.java index e31d494f148..519d76c1342 100644 --- a/common/src/test/java/com/alibaba/nacos/common/paramcheck/DefaultParamCheckerTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/paramcheck/DefaultParamCheckerTest.java @@ -16,34 +16,38 @@ package com.alibaba.nacos.common.paramcheck; -import org.junit.Before; -import org.junit.Test; +import com.alibaba.nacos.common.utils.RandomUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; 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 DefaultParamCheckerTest { +class DefaultParamCheckerTest { DefaultParamChecker paramChecker; - @Before - public void setUp() throws Exception { + int maxMetadataLength = RandomUtils.nextInt(1024, 10240); + + @BeforeEach + void setUp() throws Exception { + System.setProperty("nacos.naming.service.metadata.length", String.valueOf(maxMetadataLength)); paramChecker = new DefaultParamChecker(); } @Test - public void testCheckerType() { + void testCheckerType() { assertEquals("default", paramChecker.getCheckerType()); } @Test - public void testCheckEmptyParamInfoList() { + void testCheckEmptyParamInfoList() { ParamCheckResponse actual = paramChecker.checkParamInfoList(null); assertTrue(actual.isSuccess()); actual = paramChecker.checkParamInfoList(Collections.emptyList()); @@ -51,7 +55,7 @@ public void testCheckEmptyParamInfoList() { } @Test - public void testCheckEmptyParamInfo() { + void testCheckEmptyParamInfo() { ParamInfo paramInfo = new ParamInfo(); ArrayList paramInfos = new ArrayList<>(); paramInfos.add(paramInfo); @@ -61,7 +65,7 @@ public void testCheckEmptyParamInfo() { } @Test - public void testCheckParamInfoForNamespaceShowName() { + void testCheckParamInfoForNamespaceShowName() { ParamInfo paramInfo = new ParamInfo(); ArrayList paramInfos = new ArrayList<>(); paramInfos.add(paramInfo); @@ -70,14 +74,12 @@ public void testCheckParamInfoForNamespaceShowName() { paramInfo.setNamespaceShowName(namespaceShowName); ParamCheckResponse actual = paramChecker.checkParamInfoList(paramInfos); assertFalse(actual.isSuccess()); - assertEquals("Param 'namespaceShowName' is illegal, the param length should not exceed 256.", - actual.getMessage()); + assertEquals("Param 'namespaceShowName' is illegal, the param length should not exceed 256.", actual.getMessage()); // Pattern paramInfo.setNamespaceShowName("hsbfkj@$!#khdkad"); actual = paramChecker.checkParamInfoList(paramInfos); assertFalse(actual.isSuccess()); - assertEquals("Param 'namespaceShowName' is illegal, illegal characters should not appear in the param.", - actual.getMessage()); + assertEquals("Param 'namespaceShowName' is illegal, illegal characters should not appear in the param.", actual.getMessage()); // Success paramInfo.setNamespaceShowName("测试"); actual = paramChecker.checkParamInfoList(paramInfos); @@ -85,7 +87,7 @@ public void testCheckParamInfoForNamespaceShowName() { } @Test - public void testCheckParamInfoForNamespaceId() { + void testCheckParamInfoForNamespaceId() { ParamInfo paramInfo = new ParamInfo(); ArrayList paramInfos = new ArrayList<>(); paramInfos.add(paramInfo); @@ -94,14 +96,12 @@ public void testCheckParamInfoForNamespaceId() { paramInfo.setNamespaceId(namespaceId); ParamCheckResponse actual = paramChecker.checkParamInfoList(paramInfos); assertFalse(actual.isSuccess()); - assertEquals("Param 'namespaceId/tenant' is illegal, the param length should not exceed 64.", - actual.getMessage()); + assertEquals("Param 'namespaceId/tenant' is illegal, the param length should not exceed 64.", actual.getMessage()); // Pattern paramInfo.setNamespaceId("hsbfkj@$!#khdkad"); actual = paramChecker.checkParamInfoList(paramInfos); assertFalse(actual.isSuccess()); - assertEquals("Param 'namespaceId/tenant' is illegal, illegal characters should not appear in the param.", - actual.getMessage()); + assertEquals("Param 'namespaceId/tenant' is illegal, illegal characters should not appear in the param.", actual.getMessage()); // Success paramInfo.setNamespaceId("123-ashdal"); actual = paramChecker.checkParamInfoList(paramInfos); @@ -109,7 +109,7 @@ public void testCheckParamInfoForNamespaceId() { } @Test - public void testCheckParamInfoForDataId() { + void testCheckParamInfoForDataId() { ParamInfo paramInfo = new ParamInfo(); ArrayList paramInfos = new ArrayList<>(); paramInfos.add(paramInfo); @@ -123,8 +123,7 @@ public void testCheckParamInfoForDataId() { paramInfo.setDataId("hsbfkj@$!#khdkad"); actual = paramChecker.checkParamInfoList(paramInfos); assertFalse(actual.isSuccess()); - assertEquals("Param 'dataId' is illegal, illegal characters should not appear in the param.", - actual.getMessage()); + assertEquals("Param 'dataId' is illegal, illegal characters should not appear in the param.", actual.getMessage()); // Success paramInfo.setDataId("a-zA-Z0-9-_:."); actual = paramChecker.checkParamInfoList(paramInfos); @@ -132,7 +131,7 @@ public void testCheckParamInfoForDataId() { } @Test - public void testCheckParamInfoForServiceName() { + void testCheckParamInfoForServiceName() { ParamInfo paramInfo = new ParamInfo(); ArrayList paramInfos = new ArrayList<>(); paramInfos.add(paramInfo); @@ -146,8 +145,7 @@ public void testCheckParamInfoForServiceName() { paramInfo.setServiceName("@hsbfkj$@@!#khdkad啊"); actual = paramChecker.checkParamInfoList(paramInfos); assertFalse(actual.isSuccess()); - assertEquals("Param 'serviceName' is illegal, illegal characters should not appear in the param.", - actual.getMessage()); + assertEquals("Param 'serviceName' is illegal, illegal characters should not appear in the param.", actual.getMessage()); // Success paramInfo.setServiceName("com.aaa@bbb#_{}-b:v1.2.2"); actual = paramChecker.checkParamInfoList(paramInfos); @@ -155,7 +153,7 @@ public void testCheckParamInfoForServiceName() { } @Test - public void testCheckParamInfoForGroup() { + void testCheckParamInfoForGroup() { ParamInfo paramInfo = new ParamInfo(); ArrayList paramInfos = new ArrayList<>(); paramInfos.add(paramInfo); @@ -169,8 +167,7 @@ public void testCheckParamInfoForGroup() { paramInfo.setGroup("@hsbfkj$@@!#khdkad啊@@"); actual = paramChecker.checkParamInfoList(paramInfos); assertFalse(actual.isSuccess()); - assertEquals("Param 'group' is illegal, illegal characters should not appear in the param.", - actual.getMessage()); + assertEquals("Param 'group' is illegal, illegal characters should not appear in the param.", actual.getMessage()); // Success paramInfo.setGroup("a-zA-Z0-9-_:."); actual = paramChecker.checkParamInfoList(paramInfos); @@ -178,7 +175,7 @@ public void testCheckParamInfoForGroup() { } @Test - public void testCheckParamInfoForClusters() { + void testCheckParamInfoForClusters() { ParamInfo paramInfo = new ParamInfo(); ArrayList paramInfos = new ArrayList<>(); paramInfos.add(paramInfo); @@ -192,8 +189,7 @@ public void testCheckParamInfoForClusters() { paramInfo.setClusters("@hsbfkj$@@!#khdkad啊@@"); actual = paramChecker.checkParamInfoList(paramInfos); assertFalse(actual.isSuccess()); - assertEquals("Param 'cluster' is illegal, illegal characters should not appear in the param.", - actual.getMessage()); + assertEquals("Param 'cluster' is illegal, illegal characters should not appear in the param.", actual.getMessage()); // Success paramInfo.setClusters("0-9a-zA-Z-_,DEFAULT_abc-100"); actual = paramChecker.checkParamInfoList(paramInfos); @@ -201,7 +197,7 @@ public void testCheckParamInfoForClusters() { } @Test - public void testCheckParamInfoForCluster() { + void testCheckParamInfoForCluster() { ParamInfo paramInfo = new ParamInfo(); ArrayList paramInfos = new ArrayList<>(); paramInfos.add(paramInfo); @@ -215,8 +211,7 @@ public void testCheckParamInfoForCluster() { paramInfo.setCluster("@hsbfkj$@@!#khdkad啊@@"); actual = paramChecker.checkParamInfoList(paramInfos); assertFalse(actual.isSuccess()); - assertEquals("Param 'cluster' is illegal, illegal characters should not appear in the param.", - actual.getMessage()); + assertEquals("Param 'cluster' is illegal, illegal characters should not appear in the param.", actual.getMessage()); // Success paramInfo.setCluster("0-9a-zA-Z-_"); actual = paramChecker.checkParamInfoList(paramInfos); @@ -224,7 +219,7 @@ public void testCheckParamInfoForCluster() { } @Test - public void testCheckParamInfoForIp() { + void testCheckParamInfoForIp() { ParamInfo paramInfo = new ParamInfo(); ArrayList paramInfos = new ArrayList<>(); paramInfos.add(paramInfo); @@ -246,7 +241,7 @@ public void testCheckParamInfoForIp() { } @Test - public void testCheckParamInfoForPort() { + void testCheckParamInfoForPort() { ParamInfo paramInfo = new ParamInfo(); ArrayList paramInfos = new ArrayList<>(); paramInfos.add(paramInfo); @@ -272,7 +267,7 @@ public void testCheckParamInfoForPort() { } @Test - public void testCheckParamInfoForMetadata() { + void testCheckParamInfoForMetadata() { ParamInfo paramInfo = new ParamInfo(); ArrayList paramInfos = new ArrayList<>(); paramInfos.add(paramInfo); @@ -280,12 +275,12 @@ public void testCheckParamInfoForMetadata() { paramInfo.setMetadata(metadata); // Max length metadata.put("key1", ""); - metadata.put("key2", buildStringLength(1024)); + metadata.put("key2", buildStringLength(maxMetadataLength)); ParamCheckResponse actual = paramChecker.checkParamInfoList(paramInfos); assertFalse(actual.isSuccess()); - assertEquals("Param 'Metadata' is illegal, the param length should not exceed 1024.", actual.getMessage()); + assertEquals(String.format("Param 'Metadata' is illegal, the param length should not exceed %d.", maxMetadataLength), actual.getMessage()); // Success - metadata.put("key2", "Any key and value, only require length sum not more than 1024."); + metadata.put("key2", String.format("Any key and value, only require length sum not more than %d.", maxMetadataLength)); actual = paramChecker.checkParamInfoList(paramInfos); assertTrue(actual.isSuccess()); } diff --git a/common/src/test/java/com/alibaba/nacos/common/paramcheck/ParamCheckerManagerTest.java b/common/src/test/java/com/alibaba/nacos/common/paramcheck/ParamCheckerManagerTest.java index a776de9d46f..d9252290a3d 100644 --- a/common/src/test/java/com/alibaba/nacos/common/paramcheck/ParamCheckerManagerTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/paramcheck/ParamCheckerManagerTest.java @@ -16,30 +16,30 @@ package com.alibaba.nacos.common.paramcheck; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ParamCheckerManagerTest { +class ParamCheckerManagerTest { @Test - public void testGetParamCheckerNonExistType() { + void testGetParamCheckerNonExistType() { assertTrue(ParamCheckerManager.getInstance().getParamChecker("non") instanceof DefaultParamChecker); } @Test - public void testGetParamCheckerNull() { + void testGetParamCheckerNull() { assertTrue(ParamCheckerManager.getInstance().getParamChecker("") instanceof DefaultParamChecker); assertTrue(ParamCheckerManager.getInstance().getParamChecker(null) instanceof DefaultParamChecker); } @Test - public void testGetParamCheckerDefault() { + void testGetParamCheckerDefault() { assertTrue(ParamCheckerManager.getInstance().getParamChecker("default") instanceof DefaultParamChecker); } @Test - public void testGetParamCheckerOther() { + void testGetParamCheckerOther() { assertTrue(ParamCheckerManager.getInstance().getParamChecker("mock") instanceof MockParamChecker); } } \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/pathencoder/PathEncoderManagerTest.java b/common/src/test/java/com/alibaba/nacos/common/pathencoder/PathEncoderManagerTest.java index d3892abc782..3b4fffff880 100644 --- a/common/src/test/java/com/alibaba/nacos/common/pathencoder/PathEncoderManagerTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/pathencoder/PathEncoderManagerTest.java @@ -17,21 +17,23 @@ package com.alibaba.nacos.common.pathencoder; import com.alibaba.nacos.common.pathencoder.impl.WindowsEncoder; -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.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.nio.charset.Charset; +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.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -public class PathEncoderManagerTest { +class PathEncoderManagerTest { private String cachedOsName; @@ -39,64 +41,64 @@ public class PathEncoderManagerTest { private Object cachedEncoder; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { cachedOsName = System.getProperty("os.name"); targetEncoder = PathEncoderManager.class.getDeclaredField("targetEncoder"); targetEncoder.setAccessible(true); cachedEncoder = targetEncoder.get(PathEncoderManager.getInstance()); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { System.setProperty("os.name", cachedOsName); targetEncoder.set(PathEncoderManager.getInstance(), cachedEncoder); } @Test - public void testInitWithWindows() + void testInitWithWindows() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Constructor constructor = PathEncoderManager.class.getDeclaredConstructor(); constructor.setAccessible(true); System.setProperty("os.name", "window"); PathEncoderManager instance = constructor.newInstance(); - Assert.assertTrue(targetEncoder.get(instance) instanceof WindowsEncoder); + assertTrue(targetEncoder.get(instance) instanceof WindowsEncoder); } /** * test expose method. */ @Test - public void testWindowsEncode() throws Exception { + void testWindowsEncode() throws Exception { // load static PathEncoderManager instance = PathEncoderManager.getInstance(); String case1 = "aa||a"; String case2 = "aa%A9%%A9%a"; // try to encode if in windows targetEncoder.set(instance, new WindowsEncoder()); - Assert.assertEquals(PathEncoderManager.getInstance().encode(case1), case2); - Assert.assertEquals(PathEncoderManager.getInstance().decode(case2), case1); + assertEquals(PathEncoderManager.getInstance().encode(case1), case2); + assertEquals(PathEncoderManager.getInstance().decode(case2), case1); } @Test - public void testEncodeWithNonExistOs() throws Exception { + void testEncodeWithNonExistOs() throws Exception { // load static PathEncoderManager instance = PathEncoderManager.getInstance(); // remove impl targetEncoder.set(instance, null); // try to encode, non windows String case1 = "aa||a"; - Assert.assertEquals(PathEncoderManager.getInstance().encode(case1), case1); + assertEquals(PathEncoderManager.getInstance().encode(case1), case1); String case2 = "aa%A9%%A9%a"; - Assert.assertEquals(PathEncoderManager.getInstance().decode(case2), case2); + assertEquals(PathEncoderManager.getInstance().decode(case2), case2); } @Test - public void testEncodeForNull() throws IllegalAccessException { + void testEncodeForNull() throws IllegalAccessException { PathEncoder mockPathEncoder = mock(PathEncoder.class); targetEncoder.set(PathEncoderManager.getInstance(), mockPathEncoder); - Assert.assertNull(PathEncoderManager.getInstance().encode(null)); - Assert.assertNull(PathEncoderManager.getInstance().decode(null)); + assertNull(PathEncoderManager.getInstance().encode(null)); + assertNull(PathEncoderManager.getInstance().decode(null)); verify(mockPathEncoder, never()).encode(null, Charset.defaultCharset().name()); verify(mockPathEncoder, never()).decode(null, Charset.defaultCharset().name()); } diff --git a/common/src/test/java/com/alibaba/nacos/common/pathencoder/WindowsEncoderTest.java b/common/src/test/java/com/alibaba/nacos/common/pathencoder/WindowsEncoderTest.java index f35e2fcc5a1..6c35b7823f3 100644 --- a/common/src/test/java/com/alibaba/nacos/common/pathencoder/WindowsEncoderTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/pathencoder/WindowsEncoderTest.java @@ -17,106 +17,112 @@ package com.alibaba.nacos.common.pathencoder; import com.alibaba.nacos.common.pathencoder.impl.WindowsEncoder; -import junit.framework.TestCase; -import org.junit.Assert; +import org.junit.jupiter.api.Test; import java.nio.charset.Charset; -public class WindowsEncoderTest extends TestCase { +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 WindowsEncoderTest { + WindowsEncoder windowsEncoder = new WindowsEncoder(); - + /** * test encode. */ - public void testEncode() { + @Test + void testEncode() { String charset = Charset.defaultCharset().name(); String case1 = "aaaadsaknkf"; - Assert.assertEquals(windowsEncoder.encode(case1, charset), case1); + assertEquals(windowsEncoder.encode(case1, charset), case1); // matches one String case2 = "aaaa\\dsaknkf"; - Assert.assertEquals(windowsEncoder.encode(case2, charset), "aaaa%A1%dsaknkf"); + assertEquals("aaaa%A1%dsaknkf", windowsEncoder.encode(case2, charset)); String case3 = "aaaa/dsaknkf"; - Assert.assertEquals(windowsEncoder.encode(case3, charset), "aaaa%A2%dsaknkf"); + assertEquals("aaaa%A2%dsaknkf", windowsEncoder.encode(case3, charset)); String case4 = "aaaa:dsaknkf"; - Assert.assertEquals(windowsEncoder.encode(case4, charset), "aaaa%A3%dsaknkf"); + assertEquals("aaaa%A3%dsaknkf", windowsEncoder.encode(case4, charset)); String case5 = "aaaa*dsaknkf"; - Assert.assertEquals(windowsEncoder.encode(case5, charset), "aaaa%A4%dsaknkf"); + assertEquals("aaaa%A4%dsaknkf", windowsEncoder.encode(case5, charset)); String case6 = "aaaa?dsaknkf"; - Assert.assertEquals(windowsEncoder.encode(case6, charset), "aaaa%A5%dsaknkf"); + assertEquals("aaaa%A5%dsaknkf", windowsEncoder.encode(case6, charset)); String case7 = "aaaa\"dsaknkf"; - Assert.assertEquals(windowsEncoder.encode(case7, charset), "aaaa%A6%dsaknkf"); + assertEquals("aaaa%A6%dsaknkf", windowsEncoder.encode(case7, charset)); String case8 = "aaaadsaknkf"); + assertEquals("aaaa>dsaknkf", windowsEncoder.decode(case9, charset)); String case10 = "aaaa%A9%dsaknkf"; - Assert.assertEquals(windowsEncoder.decode(case10, charset), "aaaa|dsaknkf"); - + assertEquals("aaaa|dsaknkf", windowsEncoder.decode(case10, charset)); + // matches more String case11 = "aaaa%A7%dsa%A7%%A8%%A8%knkf"; - Assert.assertEquals(windowsEncoder.decode(case11, charset), "aaaa>knkf"); + assertEquals("aaaa>knkf", windowsEncoder.decode(case11, charset)); String case12 = "aaaa%A6%dsa%A6%%A1%%A1%knkf"; - Assert.assertEquals(windowsEncoder.decode(case12, charset), "aaaa\"dsa\"\\\\knkf"); + assertEquals("aaaa\"dsa\"\\\\knkf", windowsEncoder.decode(case12, charset)); } - + /** * test needEncode. */ - public void testNeedEncode() { - String case1 = "aaaadsaknkf"; + @Test + void testNeedEncode() { // / : ? " < > | \ + assertFalse(windowsEncoder.needEncode(null)); + String case1 = "aaaadsaknkf"; + assertFalse(windowsEncoder.needEncode(case1)); String case2 = "?asda"; + assertTrue(windowsEncoder.needEncode(case2)); String case3 = "/asdasd"; + assertTrue(windowsEncoder.needEncode(case3)); String case4 = "as\\dasda"; + assertTrue(windowsEncoder.needEncode(case4)); String case5 = "asd::as"; + assertTrue(windowsEncoder.needEncode(case5)); String case6 = "sda\"sda"; + assertTrue(windowsEncoder.needEncode(case6)); String case7 = "asdas { + PayloadRegistry.register("ErrorResponse", ErrorResponse.class); + }); } } \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/remote/TlsConfigTest.java b/common/src/test/java/com/alibaba/nacos/common/remote/TlsConfigTest.java index 5d08786f84c..ffaa43496f4 100644 --- a/common/src/test/java/com/alibaba/nacos/common/remote/TlsConfigTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/remote/TlsConfigTest.java @@ -16,17 +16,17 @@ package com.alibaba.nacos.common.remote; -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.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; -public class TlsConfigTest { +class TlsConfigTest { @Test - public void testTlsConfig() { + void testTlsConfig() { TlsConfig tlsConfig = new TlsConfig(); assertFalse(tlsConfig.getEnableTls()); assertFalse(tlsConfig.getMutualAuthEnable()); diff --git a/common/src/test/java/com/alibaba/nacos/common/remote/client/ConnectionTest.java b/common/src/test/java/com/alibaba/nacos/common/remote/client/ConnectionTest.java index 05c69d0a6c8..3ee29056841 100644 --- a/common/src/test/java/com/alibaba/nacos/common/remote/client/ConnectionTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/remote/client/ConnectionTest.java @@ -23,23 +23,23 @@ import com.alibaba.nacos.api.remote.RequestFuture; import com.alibaba.nacos.api.remote.request.Request; import com.alibaba.nacos.api.remote.response.Response; -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.Collections; -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; -public class ConnectionTest { +class ConnectionTest { Connection connection; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { connection = new Connection(new RpcClient.ServerInfo("127.0.0.1", 8848)) { @Override public Response request(Request request, long timeoutMills) throws NacosException { @@ -61,20 +61,20 @@ public void close() { }; } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { connection.close(); } @Test - public void testSetConnectionId() { + void testSetConnectionId() { assertNull(connection.getConnectionId()); connection.setConnectionId("testConnectionId"); assertEquals("testConnectionId", connection.getConnectionId()); } @Test - public void testGetConnectionAbility() { + void testGetConnectionAbility() { assertFalse(connection.isAbilitiesSet()); assertEquals(AbilityStatus.UNKNOWN, connection.getConnectionAbility(AbilityKey.SDK_CLIENT_TEST_1)); connection.setAbilityTable(Collections.singletonMap(AbilityKey.SERVER_TEST_2.getName(), true)); @@ -86,7 +86,7 @@ public void testGetConnectionAbility() { } @Test - public void testSetAbandon() { + void testSetAbandon() { assertFalse(connection.isAbandon()); connection.setAbandon(true); assertTrue(connection.isAbandon()); diff --git a/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClientFactoryTest.java b/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClientFactoryTest.java index 1857a707c6e..c07878e2702 100644 --- a/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClientFactoryTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClientFactoryTest.java @@ -19,14 +19,13 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.common.remote.ConnectionType; import com.alibaba.nacos.common.utils.CollectionUtils; -import org.junit.After; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +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.lang.reflect.Modifier; @@ -35,12 +34,16 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -@RunWith(MockitoJUnitRunner.class) -public class RpcClientFactoryTest { +@ExtendWith(MockitoExtension.class) +class RpcClientFactoryTest { static Field clientMapField; @@ -48,10 +51,13 @@ public class RpcClientFactoryTest { RpcClient rpcClient; @Mock(lenient = true) - RpcClientTlsConfig tlsConfig; + RpcClientTlsConfig clusterClientTlsConfig; - @BeforeClass - public static void setUpBeforeClass() throws NoSuchFieldException, IllegalAccessException { + @Mock(lenient = true) + RpcClientTlsConfig rpcClientTlsConfig; + + @BeforeAll + static void setUpBeforeClass() throws NoSuchFieldException, IllegalAccessException { clientMapField = RpcClientFactory.class.getDeclaredField("CLIENT_MAP"); clientMapField.setAccessible(true); Field modifiersField1 = Field.class.getDeclaredField("modifiers"); @@ -59,136 +65,135 @@ public static void setUpBeforeClass() throws NoSuchFieldException, IllegalAccess modifiersField1.setInt(clientMapField, clientMapField.getModifiers() & ~Modifier.FINAL); } - @After - public void tearDown() throws IllegalAccessException { + @AfterEach + void tearDown() throws IllegalAccessException { clientMapField.set(null, new ConcurrentHashMap<>()); } @Test - public void testGetAllClientEntries() throws IllegalAccessException { - Assert.assertTrue(RpcClientFactory.getAllClientEntries().isEmpty()); + void testGetAllClientEntries() throws IllegalAccessException { + assertTrue(RpcClientFactory.getAllClientEntries().isEmpty()); clientMapField.set(null, Collections.singletonMap("testClient", rpcClient)); - Assert.assertEquals(1, RpcClientFactory.getAllClientEntries().size()); + assertEquals(1, RpcClientFactory.getAllClientEntries().size()); } @Test - public void testDestroyClientWhenClientExistThenRemoveAndShutDownRpcClient() - throws IllegalAccessException, NacosException { + void testDestroyClientWhenClientExistThenRemoveAndShutDownRpcClient() throws IllegalAccessException, NacosException { clientMapField.set(null, new ConcurrentHashMap<>(Collections.singletonMap("testClient", rpcClient))); RpcClientFactory.destroyClient("testClient"); - Assert.assertTrue(RpcClientFactory.getAllClientEntries().isEmpty()); + assertTrue(RpcClientFactory.getAllClientEntries().isEmpty()); verify(rpcClient).shutdown(); } @Test - public void testDestroyClientWhenClientNotExistThenDoNothing() throws IllegalAccessException, NacosException { + void testDestroyClientWhenClientNotExistThenDoNothing() throws IllegalAccessException, NacosException { clientMapField.set(null, new ConcurrentHashMap<>(Collections.singletonMap("testClient", rpcClient))); RpcClientFactory.destroyClient("notExistClientName"); Map.Entry element = CollectionUtils.getOnlyElement(RpcClientFactory.getAllClientEntries()); - Assert.assertEquals("testClient", element.getKey()); - Assert.assertEquals(rpcClient, element.getValue()); + assertEquals("testClient", element.getKey()); + assertEquals(rpcClient, element.getValue()); verify(rpcClient, times(0)).shutdown(); } @Test - public void testGetClient() throws IllegalAccessException { + void testGetClient() throws IllegalAccessException { // may be null - Assert.assertNull(RpcClientFactory.getClient("notExistClientName")); + assertNull(RpcClientFactory.getClient("notExistClientName")); clientMapField.set(null, new ConcurrentHashMap<>(Collections.singletonMap("testClient", rpcClient))); - Assert.assertEquals(rpcClient, RpcClientFactory.getClient("testClient")); + assertEquals(rpcClient, RpcClientFactory.getClient("testClient")); } @Test - public void testCreateClientWhenNotCreatedThenCreate() { + void testCreateClientWhenNotCreatedThenCreate() { RpcClient client = RpcClientFactory.createClient("testClient", ConnectionType.GRPC, Collections.singletonMap("labelKey", "labelValue")); Map labesMap = new HashMap<>(); labesMap.put("labelKey", "labelValue"); labesMap.put("tls.enable", "false"); - Assert.assertEquals(labesMap, client.rpcClientConfig.labels()); - Assert.assertEquals(ConnectionType.GRPC, client.getConnectionType()); - Assert.assertEquals("testClient", - CollectionUtils.getOnlyElement(RpcClientFactory.getAllClientEntries()).getKey()); + assertEquals(labesMap, client.rpcClientConfig.labels()); + assertEquals(ConnectionType.GRPC, client.getConnectionType()); + assertEquals("testClient", CollectionUtils.getOnlyElement(RpcClientFactory.getAllClientEntries()).getKey()); } @Test - public void testCreateClientWhenAlreadyCreatedThenNotCreateAgain() { + void testCreateClientWhenAlreadyCreatedThenNotCreateAgain() { RpcClient client1 = RpcClientFactory.createClient("testClient", ConnectionType.GRPC, Collections.singletonMap("labelKey", "labelValue")); RpcClient client2 = RpcClientFactory.createClient("testClient", ConnectionType.GRPC, Collections.singletonMap("labelKey", "labelValue")); - Assert.assertEquals(client1, client2); - Assert.assertEquals(1, RpcClientFactory.getAllClientEntries().size()); + assertEquals(client1, client2); + assertEquals(1, RpcClientFactory.getAllClientEntries().size()); } - @Test(expected = Exception.class) - public void testCreatedClientWhenConnectionTypeNotMappingThenThrowException() { - RpcClientFactory.createClient("testClient", mock(ConnectionType.class), - Collections.singletonMap("labelKey", "labelValue")); + @Test + void testCreatedClientWhenConnectionTypeNotMappingThenThrowException() { + assertThrows(Exception.class, () -> { + RpcClientFactory.createClient("testClient", mock(ConnectionType.class), + Collections.singletonMap("labelKey", "labelValue")); + }); } @Test - public void testCreateClusterClientWhenNotCreatedThenCreate() { + void testCreateClusterClientWhenNotCreatedThenCreate() { RpcClient client = RpcClientFactory.createClusterClient("testClient", ConnectionType.GRPC, Collections.singletonMap("labelKey", "labelValue")); Map labesMap = new HashMap<>(); labesMap.put("labelKey", "labelValue"); labesMap.put("tls.enable", "false"); - Assert.assertEquals(labesMap, client.rpcClientConfig.labels()); - Assert.assertEquals(ConnectionType.GRPC, client.getConnectionType()); - Assert.assertEquals("testClient", - CollectionUtils.getOnlyElement(RpcClientFactory.getAllClientEntries()).getKey()); + assertEquals(labesMap, client.rpcClientConfig.labels()); + assertEquals(ConnectionType.GRPC, client.getConnectionType()); + assertEquals("testClient", CollectionUtils.getOnlyElement(RpcClientFactory.getAllClientEntries()).getKey()); } @Test - public void testCreateClusterClientWhenAlreadyCreatedThenNotCreateAgain() { + void testCreateClusterClientWhenAlreadyCreatedThenNotCreateAgain() { RpcClient client1 = RpcClientFactory.createClusterClient("testClient", ConnectionType.GRPC, Collections.singletonMap("labelKey", "labelValue")); RpcClient client2 = RpcClientFactory.createClusterClient("testClient", ConnectionType.GRPC, Collections.singletonMap("labelKey", "labelValue")); - Assert.assertEquals(client1, client2); - Assert.assertEquals(1, RpcClientFactory.getAllClientEntries().size()); + assertEquals(client1, client2); + assertEquals(1, RpcClientFactory.getAllClientEntries().size()); } - @Test(expected = Exception.class) - public void testCreatedClusterClientWhenConnectionTypeNotMappingThenThrowException() { - RpcClientFactory.createClusterClient("testClient", mock(ConnectionType.class), - Collections.singletonMap("labelKey", "labelValue")); + @Test + void testCreatedClusterClientWhenConnectionTypeNotMappingThenThrowException() { + assertThrows(Exception.class, () -> { + RpcClientFactory.createClusterClient("testClient", mock(ConnectionType.class), + Collections.singletonMap("labelKey", "labelValue")); + }); } @Test - public void testCreateClusterClientTsl() { - Mockito.when(tlsConfig.getEnableTls()).thenReturn(true); + void testCreateClusterClientTsl() { + Mockito.when(clusterClientTlsConfig.getEnableTls()).thenReturn(true); RpcClient client = RpcClientFactory.createClusterClient("testClient", ConnectionType.GRPC, - Collections.singletonMap("labelKey", "labelValue"), tlsConfig); + Collections.singletonMap("labelKey", "labelValue"), clusterClientTlsConfig); Map labesMap = new HashMap<>(); labesMap.put("labelKey", "labelValue"); labesMap.put("tls.enable", "true"); - Assert.assertEquals(labesMap, client.rpcClientConfig.labels()); - Assert.assertEquals(ConnectionType.GRPC, client.getConnectionType()); - Assert.assertEquals("testClient", - CollectionUtils.getOnlyElement(RpcClientFactory.getAllClientEntries()).getKey()); + assertEquals(labesMap, client.rpcClientConfig.labels()); + assertEquals(ConnectionType.GRPC, client.getConnectionType()); + assertEquals("testClient", CollectionUtils.getOnlyElement(RpcClientFactory.getAllClientEntries()).getKey()); } @Test - public void testCreateClientTsl() { - Mockito.when(tlsConfig.getEnableTls()).thenReturn(true); + void testCreateClientTsl() { + Mockito.when(rpcClientTlsConfig.getEnableTls()).thenReturn(true); RpcClient client = RpcClientFactory.createClient("testClient", ConnectionType.GRPC, - Collections.singletonMap("labelKey", "labelValue"), tlsConfig); + Collections.singletonMap("labelKey", "labelValue"), rpcClientTlsConfig); Map labesMap = new HashMap<>(); labesMap.put("labelKey", "labelValue"); labesMap.put("tls.enable", "true"); - Assert.assertEquals(labesMap, client.rpcClientConfig.labels()); - Assert.assertEquals(ConnectionType.GRPC, client.getConnectionType()); - Assert.assertEquals("testClient", - CollectionUtils.getOnlyElement(RpcClientFactory.getAllClientEntries()).getKey()); + assertEquals(labesMap, client.rpcClientConfig.labels()); + assertEquals(ConnectionType.GRPC, client.getConnectionType()); + assertEquals("testClient", CollectionUtils.getOnlyElement(RpcClientFactory.getAllClientEntries()).getKey()); } -} \ No newline at end of file +} diff --git a/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClientTest.java b/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClientTest.java index 763c1416dc2..817fb2e34da 100644 --- a/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClientTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClientTest.java @@ -32,13 +32,12 @@ import com.alibaba.nacos.common.remote.ConnectionType; import com.alibaba.nacos.common.remote.client.grpc.DefaultGrpcClientConfig; import com.alibaba.nacos.common.remote.client.grpc.GrpcConnection; -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 org.mockito.stubbing.Answer; import java.lang.reflect.Field; @@ -57,11 +56,12 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; -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.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.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.atLeastOnce; @@ -74,8 +74,8 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class RpcClientTest { +@ExtendWith(MockitoExtension.class) +class RpcClientTest { RpcClient rpcClient; @@ -99,8 +99,8 @@ public class RpcClientTest { RpcClientConfig rpcClientConfig; - @Before - public void setUp() throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException { + @BeforeEach + void setUp() throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException { rpcClientConfig = spy(new RpcClientConfig() { @Override public String name() { @@ -178,8 +178,8 @@ public Connection connectToServer(ServerInfo serverInfo) { notInvoke = invocationOnMock -> null; } - @After - public void tearDown() throws IllegalAccessException, NacosException { + @AfterEach + void tearDown() throws IllegalAccessException, NacosException { rpcClientConfig.labels().clear(); rpcClient.rpcClientStatus.set(RpcClientStatus.WAIT_INIT); serverListFactoryField.set(rpcClient, null); @@ -191,7 +191,7 @@ public void tearDown() throws IllegalAccessException, NacosException { } @Test - public void testInitServerListFactory() { + void testInitServerListFactory() { rpcClient.rpcClientStatus.set(RpcClientStatus.WAIT_INIT); rpcClient.serverListFactory(serverListFactory); assertEquals(RpcClientStatus.INITIALIZED, rpcClient.rpcClientStatus.get()); @@ -273,7 +273,7 @@ public Connection connectToServer(ServerInfo serverInfo) { } @Test - public void testLabels() { + void testLabels() { when(rpcClientConfig.labels()).thenReturn(Collections.singletonMap("labelKey1", "labelValue1")); Map.Entry element = rpcClient.getLabels().entrySet().iterator().next(); assertEquals("labelKey1", element.getKey()); @@ -288,7 +288,7 @@ public void testLabels() { } @Test - public void testOnServerListChangeWhenCurrentConnectionIsNullThenDoNothing() throws IllegalAccessException { + void testOnServerListChangeWhenCurrentConnectionIsNullThenDoNothing() throws IllegalAccessException { int beforeSize = ((Queue) reconnectionSignalField.get(rpcClient)).size(); rpcClient.serverListFactory(serverListFactory); @@ -299,7 +299,7 @@ public void testOnServerListChangeWhenCurrentConnectionIsNullThenDoNothing() thr } @Test - public void testOnServerListChangeWhenServiceInfoIsNullThenDoNothing() throws IllegalAccessException { + void testOnServerListChangeWhenServiceInfoIsNullThenDoNothing() throws IllegalAccessException { int beforeSize = ((Queue) reconnectionSignalField.get(rpcClient)).size(); rpcClient.currentConnection = mock(Connection.class); @@ -310,8 +310,7 @@ public void testOnServerListChangeWhenServiceInfoIsNullThenDoNothing() throws Il } @Test - public void testOnServerListChangeWhenCurrentConnectionIsNotInServerListThenSwitchServerAsync() - throws IllegalAccessException { + void testOnServerListChangeWhenCurrentConnectionIsNotInServerListThenSwitchServerAsync() throws IllegalAccessException { final int beforeSize = ((Queue) reconnectionSignalField.get(rpcClient)).size(); rpcClient.serverListFactory(serverListFactory); rpcClient.currentConnection = new GrpcConnection(new RpcClient.ServerInfo("10.10.10.10", 8848), null); @@ -324,7 +323,7 @@ public void testOnServerListChangeWhenCurrentConnectionIsNotInServerListThenSwit } @Test - public void testOnServerListChangeWhenCurrentConnectionIsInServerListThenDoNothing() throws IllegalAccessException { + void testOnServerListChangeWhenCurrentConnectionIsInServerListThenDoNothing() throws IllegalAccessException { final int beforeSize = ((Queue) reconnectionSignalField.get(rpcClient)).size(); rpcClient.serverListFactory(serverListFactory); rpcClient.currentConnection = new GrpcConnection(new RpcClient.ServerInfo("10.10.10.10", 8848), null); @@ -336,33 +335,30 @@ public void testOnServerListChangeWhenCurrentConnectionIsInServerListThenDoNothi } @Test - public void testResolveServerInfo1() throws InvocationTargetException, IllegalAccessException { + void testResolveServerInfo1() throws InvocationTargetException, IllegalAccessException { assertEquals("10.10.10.10:8848", ((RpcClient.ServerInfo) resolveServerInfoMethod.invoke(rpcClient, "10.10.10.10::8848")).getAddress()); assertEquals("10.10.10.10:8848", ((RpcClient.ServerInfo) resolveServerInfoMethod.invoke(rpcClient, "10.10.10.10:8848")).getAddress()); assertEquals("10.10.10.10:8848", - ((RpcClient.ServerInfo) resolveServerInfoMethod.invoke(rpcClient, "http://10.10.10.10:8848")) - .getAddress()); + ((RpcClient.ServerInfo) resolveServerInfoMethod.invoke(rpcClient, "http://10.10.10.10:8848")).getAddress()); assertEquals("10.10.10.10:8848", - ((RpcClient.ServerInfo) resolveServerInfoMethod.invoke(rpcClient, "http://10.10.10.10::8848")) - .getAddress()); + ((RpcClient.ServerInfo) resolveServerInfoMethod.invoke(rpcClient, "http://10.10.10.10::8848")).getAddress()); assertEquals("10.10.10.10:8848", ((RpcClient.ServerInfo) resolveServerInfoMethod.invoke(rpcClient, "http://10.10.10.10")).getAddress()); assertEquals("10.10.10.10:8848", - ((RpcClient.ServerInfo) resolveServerInfoMethod.invoke(rpcClient, "https://10.10.10.10::8848")) - .getAddress()); + ((RpcClient.ServerInfo) resolveServerInfoMethod.invoke(rpcClient, "https://10.10.10.10::8848")).getAddress()); } @Test - public void testResolveServerInfo2() throws InvocationTargetException, IllegalAccessException { + void testResolveServerInfo2() throws InvocationTargetException, IllegalAccessException { System.setProperty("nacos.server.port", "4424"); assertEquals("10.10.10.10:4424", ((RpcClient.ServerInfo) resolveServerInfoMethod.invoke(rpcClient, "http://10.10.10.10")).getAddress()); } @Test - public void testRequestSuccess() throws NacosException, NoSuchFieldException, IllegalAccessException { + void testRequestSuccess() throws NacosException, NoSuchFieldException, IllegalAccessException { rpcClient.currentConnection = connection; rpcClient.rpcClientStatus.set(RpcClientStatus.RUNNING); when(connection.request(any(), anyLong())).thenReturn(new HealthCheckResponse()); @@ -374,37 +370,45 @@ public void testRequestSuccess() throws NacosException, NoSuchFieldException, Il assertTrue(lastActiveTimeStamp <= (long) lastActiveTimeStampField.get(rpcClient)); } - @Test(expected = NacosException.class) - public void testRequestWithoutAnyTry() throws NacosException { - when(rpcClientConfig.retryTimes()).thenReturn(-1); - rpcClient.request(null); + @Test + void testRequestWithoutAnyTry() throws NacosException { + assertThrows(NacosException.class, () -> { + when(rpcClientConfig.retryTimes()).thenReturn(-1); + rpcClient.request(null); + }); } - @Test(expected = NacosException.class) - public void testRequestWhenClientAlreadyShutDownThenThrowException() throws NacosException { - rpcClient.rpcClientStatus.set(RpcClientStatus.SHUTDOWN); - rpcClient.currentConnection = connection; - rpcClient.request(null); + @Test + void testRequestWhenClientAlreadyShutDownThenThrowException() throws NacosException { + assertThrows(NacosException.class, () -> { + rpcClient.rpcClientStatus.set(RpcClientStatus.SHUTDOWN); + rpcClient.currentConnection = connection; + rpcClient.request(null); + }); } - @Test(expected = NacosException.class) - public void testRequestWhenTimeoutThenThrowException() throws NacosException { - rpcClient.rpcClientStatus.set(RpcClientStatus.RUNNING); - rpcClient.currentConnection = connection; - doReturn(null).when(connection).request(any(), anyLong()); - rpcClient.request(null, 10000); + @Test + void testRequestWhenTimeoutThenThrowException() throws NacosException { + assertThrows(NacosException.class, () -> { + rpcClient.rpcClientStatus.set(RpcClientStatus.RUNNING); + rpcClient.currentConnection = connection; + doReturn(null).when(connection).request(any(), anyLong()); + rpcClient.request(null, 10000); + }); } - @Test(expected = NacosException.class) - public void testRequestWhenResponseErrorThenThrowException() throws NacosException { - rpcClient.rpcClientStatus.set(RpcClientStatus.RUNNING); - rpcClient.currentConnection = connection; - doReturn(new ErrorResponse()).when(connection).request(any(), anyLong()); - rpcClient.request(null, 10000); + @Test + void testRequestWhenResponseErrorThenThrowException() throws NacosException { + assertThrows(NacosException.class, () -> { + rpcClient.rpcClientStatus.set(RpcClientStatus.RUNNING); + rpcClient.currentConnection = connection; + doReturn(new ErrorResponse()).when(connection).request(any(), anyLong()); + rpcClient.request(null, 10000); + }); } @Test - public void testRequestWhenResponseUnregisterThenSwitchServer() throws NacosException { + void testRequestWhenResponseUnregisterThenSwitchServer() throws NacosException { rpcClient.rpcClientStatus.set(RpcClientStatus.RUNNING); rpcClient.currentConnection = connection; ErrorResponse errorResponse = new ErrorResponse(); @@ -420,11 +424,11 @@ public void testRequestWhenResponseUnregisterThenSwitchServer() throws NacosExce assertEquals(RpcClientStatus.UNHEALTHY, rpcClient.rpcClientStatus.get()); verify(rpcClient).switchServerAsync(); - Assert.assertNotNull(exception); + assertNotNull(exception); } @Test - public void testAsyncRequestSuccess() throws NacosException { + void testAsyncRequestSuccess() throws NacosException { rpcClient.currentConnection = connection; rpcClient.rpcClientStatus.set(RpcClientStatus.RUNNING); RequestCallBack requestCallBack = mock(RequestCallBack.class); @@ -433,23 +437,27 @@ public void testAsyncRequestSuccess() throws NacosException { verify(connection).asyncRequest(any(), any()); } - @Test(expected = NacosException.class) - public void testAsyncRequestWithoutAnyTry() throws NacosException { - when(rpcClientConfig.retryTimes()).thenReturn(-1); - rpcClient.asyncRequest(null, null); + @Test + void testAsyncRequestWithoutAnyTry() throws NacosException { + assertThrows(NacosException.class, () -> { + when(rpcClientConfig.retryTimes()).thenReturn(-1); + rpcClient.asyncRequest(null, null); + }); } - @Test(expected = NacosException.class) - public void testAsyncRequestWhenClientAlreadyShutDownThenThrowException() throws NacosException { - rpcClient.rpcClientStatus.set(RpcClientStatus.SHUTDOWN); - rpcClient.currentConnection = connection; - RequestCallBack requestCallBack = mock(RequestCallBack.class); - doReturn(10000L).when(requestCallBack).getTimeout(); - rpcClient.asyncRequest(null, requestCallBack); + @Test + void testAsyncRequestWhenClientAlreadyShutDownThenThrowException() throws NacosException { + assertThrows(NacosException.class, () -> { + rpcClient.rpcClientStatus.set(RpcClientStatus.SHUTDOWN); + rpcClient.currentConnection = connection; + RequestCallBack requestCallBack = mock(RequestCallBack.class); + doReturn(10000L).when(requestCallBack).getTimeout(); + rpcClient.asyncRequest(null, requestCallBack); + }); } @Test - public void testAsyncRequestWhenSendRequestFailedMannyTimesThenSwitchServer() throws NacosException { + void testAsyncRequestWhenSendRequestFailedMannyTimesThenSwitchServer() throws NacosException { rpcClient.rpcClientStatus.set(RpcClientStatus.RUNNING); rpcClient.currentConnection = connection; doThrow(new NacosException()).when(connection).asyncRequest(any(), any()); @@ -465,25 +473,29 @@ public void testAsyncRequestWhenSendRequestFailedMannyTimesThenSwitchServer() th verify(connection, atLeastOnce()).asyncRequest(any(), any()); verify(rpcClient).switchServerAsyncOnRequestFail(); - Assert.assertNotNull(exception); + assertNotNull(exception); assertEquals(RpcClientStatus.UNHEALTHY, rpcClient.rpcClientStatus.get()); } - @Test(expected = NacosException.class) - public void testRequestFutureWithoutAnyTry() throws NacosException { - when(rpcClientConfig.retryTimes()).thenReturn(-1); - rpcClient.requestFuture(null); + @Test + void testRequestFutureWithoutAnyTry() throws NacosException { + assertThrows(NacosException.class, () -> { + when(rpcClientConfig.retryTimes()).thenReturn(-1); + rpcClient.requestFuture(null); + }); } - @Test(expected = NacosException.class) - public void testRequestFutureWhenClientAlreadyShutDownThenThrowException() throws NacosException { - rpcClient.rpcClientStatus.set(RpcClientStatus.SHUTDOWN); - rpcClient.currentConnection = connection; - rpcClient.requestFuture(null); + @Test + void testRequestFutureWhenClientAlreadyShutDownThenThrowException() throws NacosException { + assertThrows(NacosException.class, () -> { + rpcClient.rpcClientStatus.set(RpcClientStatus.SHUTDOWN); + rpcClient.currentConnection = connection; + rpcClient.requestFuture(null); + }); } @Test - public void testRequestFutureWhenRetryReachMaxRetryTimesThenSwitchServer() throws NacosException { + void testRequestFutureWhenRetryReachMaxRetryTimesThenSwitchServer() throws NacosException { when(rpcClientConfig.timeOutMills()).thenReturn(5000L); when(rpcClientConfig.retryTimes()).thenReturn(3); rpcClient.rpcClientStatus.set(RpcClientStatus.RUNNING); @@ -499,12 +511,12 @@ public void testRequestFutureWhenRetryReachMaxRetryTimesThenSwitchServer() throw verify(connection, times(4)).requestFuture(any()); verify(rpcClient).switchServerAsyncOnRequestFail(); - Assert.assertNotNull(exception); + assertNotNull(exception); assertEquals(RpcClientStatus.UNHEALTHY, rpcClient.rpcClientStatus.get()); } @Test - public void testRpcClientShutdownWhenClientDidntStart() throws NacosException { + void testRpcClientShutdownWhenClientDidntStart() throws NacosException { RpcClient rpcClient = new RpcClient(new RpcClientConfig() { @Override public String name() { @@ -562,7 +574,7 @@ public Connection connectToServer(ServerInfo serverInfo) { } @Test - public void testHealthCheck() throws IllegalAccessException, NacosException { + void testHealthCheck() throws IllegalAccessException, NacosException { Random random = new Random(); int retry = random.nextInt(10); when(rpcClientConfig.healthCheckRetryTimes()).thenReturn(retry); @@ -578,7 +590,7 @@ public void testHealthCheck() throws IllegalAccessException, NacosException { } @Test - public void testNextRpcServerForIpv4WithPort() { + void testNextRpcServerForIpv4WithPort() { RpcClient rpcClient = buildTestNextRpcServerClient(); rpcClient.serverListFactory(serverListFactory); when(serverListFactory.genNextServer()).thenReturn("127.0.0.1:7777"); @@ -589,7 +601,7 @@ public void testNextRpcServerForIpv4WithPort() { } @Test - public void testNextRpcServerForIpv4WithoutPort() { + void testNextRpcServerForIpv4WithoutPort() { RpcClient rpcClient = buildTestNextRpcServerClient(); rpcClient.serverListFactory(serverListFactory); when(serverListFactory.genNextServer()).thenReturn("127.0.0.1"); @@ -600,7 +612,7 @@ public void testNextRpcServerForIpv4WithoutPort() { } @Test - public void testNextRpcServerForIpv6WithPort() { + void testNextRpcServerForIpv6WithPort() { RpcClient rpcClient = buildTestNextRpcServerClient(); rpcClient.serverListFactory(serverListFactory); when(serverListFactory.genNextServer()).thenReturn("[fe80::35ba:6827:c5ff:d161%11]:7777"); @@ -611,7 +623,7 @@ public void testNextRpcServerForIpv6WithPort() { } @Test - public void testNextRpcServerForIpv6WithoutPort() { + void testNextRpcServerForIpv6WithoutPort() { RpcClient rpcClient = buildTestNextRpcServerClient(); rpcClient.serverListFactory(serverListFactory); when(serverListFactory.genNextServer()).thenReturn("[fe80::35ba:6827:c5ff:d161%11]"); @@ -622,7 +634,7 @@ public void testNextRpcServerForIpv6WithoutPort() { } @Test - public void testNextRpcServerForDomainWithPort() { + void testNextRpcServerForDomainWithPort() { RpcClient rpcClient = buildTestNextRpcServerClient(); rpcClient.serverListFactory(serverListFactory); when(serverListFactory.genNextServer()).thenReturn("nacos.io:7777"); @@ -633,7 +645,7 @@ public void testNextRpcServerForDomainWithPort() { } @Test - public void testNextRpcServerForDomainWithoutPort() { + void testNextRpcServerForDomainWithoutPort() { RpcClient rpcClient = buildTestNextRpcServerClient(); rpcClient.serverListFactory(serverListFactory); when(serverListFactory.genNextServer()).thenReturn("nacos.io"); @@ -644,7 +656,7 @@ public void testNextRpcServerForDomainWithoutPort() { } @Test - public void testNextRpcServerForLocalhostWithPort() { + void testNextRpcServerForLocalhostWithPort() { RpcClient rpcClient = buildTestNextRpcServerClient(); rpcClient.serverListFactory(serverListFactory); when(serverListFactory.genNextServer()).thenReturn("localhost:7777"); @@ -655,7 +667,7 @@ public void testNextRpcServerForLocalhostWithPort() { } @Test - public void testNextRpcServerForLocalhostWithoutPort() { + void testNextRpcServerForLocalhostWithoutPort() { RpcClient rpcClient = buildTestNextRpcServerClient(); rpcClient.serverListFactory(serverListFactory); when(serverListFactory.genNextServer()).thenReturn("localhost"); @@ -665,12 +677,14 @@ public void testNextRpcServerForLocalhostWithoutPort() { assertEquals(8848, actual.getServerPort()); } - @Test(expected = IllegalArgumentException.class) - public void testNextRpcServerForEmpty() { - RpcClient rpcClient = buildTestNextRpcServerClient(); - rpcClient.serverListFactory(serverListFactory); - when(serverListFactory.genNextServer()).thenReturn(""); - rpcClient.nextRpcServer(); + @Test + void testNextRpcServerForEmpty() { + assertThrows(IllegalArgumentException.class, () -> { + RpcClient rpcClient = buildTestNextRpcServerClient(); + rpcClient.serverListFactory(serverListFactory); + when(serverListFactory.genNextServer()).thenReturn(""); + rpcClient.nextRpcServer(); + }); } private RpcClient buildTestNextRpcServerClient() { @@ -697,29 +711,31 @@ public ServerInfo nextRpcServer() { }; } - @Test(expected = RuntimeException.class) - public void testHandleServerRequestWhenExceptionThenThrowException() throws RuntimeException { - RpcClient rpcClient = buildTestNextRpcServerClient(); - Request request = new Request() { - @Override - public String getModule() { - return null; - } - }; - rpcClient.serverRequestHandlers.add((req, conn) -> { - throw new RuntimeException(); + @Test + void testHandleServerRequestWhenExceptionThenThrowException() throws RuntimeException { + assertThrows(RuntimeException.class, () -> { + RpcClient rpcClient = buildTestNextRpcServerClient(); + Request request = new Request() { + @Override + public String getModule() { + return null; + } + }; + rpcClient.serverRequestHandlers.add((req, conn) -> { + throw new RuntimeException(); + }); + rpcClient.handleServerRequest(request); }); - rpcClient.handleServerRequest(request); } @Test - public void testNotifyDisConnectedForEmpty() { + void testNotifyDisConnectedForEmpty() { rpcClient.notifyDisConnected(null); verify(rpcClientConfig, never()).name(); } @Test - public void testNotifyDisConnected() { + void testNotifyDisConnected() { ConnectionEventListener listener = mock(ConnectionEventListener.class); rpcClient.registerConnectionListener(listener); rpcClient.notifyDisConnected(null); @@ -728,7 +744,7 @@ public void testNotifyDisConnected() { } @Test - public void testNotifyDisConnectedException() { + void testNotifyDisConnectedException() { ConnectionEventListener listener = mock(ConnectionEventListener.class); rpcClient.registerConnectionListener(listener); doThrow(new RuntimeException("test")).when(listener).onDisConnect(null); @@ -737,13 +753,13 @@ public void testNotifyDisConnectedException() { } @Test - public void testNotifyConnectedForEmpty() { + void testNotifyConnectedForEmpty() { rpcClient.notifyConnected(null); verify(rpcClientConfig, never()).name(); } @Test - public void testNotifyConnected() { + void testNotifyConnected() { ConnectionEventListener listener = mock(ConnectionEventListener.class); rpcClient.registerConnectionListener(listener); rpcClient.notifyConnected(null); @@ -752,7 +768,7 @@ public void testNotifyConnected() { } @Test - public void testNotifyConnectedException() { + void testNotifyConnectedException() { ConnectionEventListener listener = mock(ConnectionEventListener.class); rpcClient.registerConnectionListener(listener); doThrow(new RuntimeException("test")).when(listener).onConnected(null); @@ -761,7 +777,7 @@ public void testNotifyConnectedException() { } @Test - public void testStartClient() throws NacosException { + void testStartClient() throws NacosException { when(serverListFactory.genNextServer()).thenReturn("127.0.0.1:8848"); connection.serverInfo = new RpcClient.ServerInfo("127.0.0.1", 8848); RpcClient rpcClient = buildTestStartClient(new Function() { @@ -786,7 +802,7 @@ public Connection apply(RpcClient.ServerInfo serverInfo) { } @Test - public void testStartClientWithFailed() throws NacosException, InterruptedException { + void testStartClientWithFailed() throws NacosException, InterruptedException { RpcClient rpcClient = buildTestStartClient(serverInfo -> null); try { rpcClient.start(); @@ -798,7 +814,7 @@ public void testStartClientWithFailed() throws NacosException, InterruptedExcept } @Test - public void testStartClientAfterShutdown() throws NacosException { + void testStartClientAfterShutdown() throws NacosException { RpcClient rpcClient = buildTestStartClient(serverInfo -> null); rpcClient.shutdown(); rpcClient.start(); @@ -806,7 +822,7 @@ public void testStartClientAfterShutdown() throws NacosException { } @Test - public void testDisConnectionEventAfterStart() throws NacosException, InterruptedException { + void testDisConnectionEventAfterStart() throws NacosException, InterruptedException { when(serverListFactory.genNextServer()).thenReturn("127.0.0.1:8848"); connection.serverInfo = new RpcClient.ServerInfo("127.0.0.1", 8848); RpcClient rpcClient = buildTestStartClient(serverInfo -> connection); @@ -824,7 +840,7 @@ public void testDisConnectionEventAfterStart() throws NacosException, Interrupte } @Test - public void testReconnectContextAfterStartWithNullConnection() throws NacosException, InterruptedException { + void testReconnectContextAfterStartWithNullConnection() throws NacosException, InterruptedException { RpcClient rpcClient = buildTestStartClient(serverInfo -> null); try { when(rpcClientConfig.connectionKeepAlive()).thenReturn(-1L); @@ -837,8 +853,7 @@ public void testReconnectContextAfterStartWithNullConnection() throws NacosExcep } @Test - public void testReconnectContextAfterStartWithConnectionHealthCheckFail() - throws NacosException, InterruptedException { + void testReconnectContextAfterStartWithConnectionHealthCheckFail() throws NacosException, InterruptedException { when(serverListFactory.genNextServer()).thenReturn("127.0.0.1:8848"); connection.serverInfo = new RpcClient.ServerInfo("127.0.0.1", 8848); RpcClient rpcClient = buildTestStartClient(new Function() { @@ -865,7 +880,7 @@ public Connection apply(RpcClient.ServerInfo serverInfo) { } @Test - public void testReconnectContextAfterStartWithConnectionHealthCheckSuccess() + void testReconnectContextAfterStartWithConnectionHealthCheckSuccess() throws NacosException, InterruptedException, NoSuchFieldException, IllegalAccessException { when(serverListFactory.genNextServer()).thenReturn("127.0.0.1:8848"); connection.serverInfo = new RpcClient.ServerInfo("127.0.0.1", 8848); @@ -887,7 +902,7 @@ public void testReconnectContextAfterStartWithConnectionHealthCheckSuccess() } @Test - public void testReconnectContextAfterStartWithActiveTimeIsNew() + void testReconnectContextAfterStartWithActiveTimeIsNew() throws NacosException, InterruptedException, NoSuchFieldException, IllegalAccessException { when(serverListFactory.genNextServer()).thenReturn("127.0.0.1:8848"); connection.serverInfo = new RpcClient.ServerInfo("127.0.0.1", 8848); @@ -909,16 +924,15 @@ public void testReconnectContextAfterStartWithActiveTimeIsNew() } @Test - public void testReconnectContextAfterStartWithOldServiceInfo() - throws NacosException, InterruptedException, IllegalAccessException { + void testReconnectContextAfterStartWithOldServiceInfo() throws NacosException, InterruptedException, IllegalAccessException { when(serverListFactory.genNextServer()).thenReturn("127.0.0.1:8848"); when(serverListFactory.getServerList()).thenReturn(Collections.singletonList("127.0.0.1:8848")); connection.serverInfo = new RpcClient.ServerInfo("127.0.0.1", 8848); RpcClient rpcClient = buildTestStartClient(serverInfo -> connection); try { rpcClient.start(); - RpcClient.ReconnectContext reconnectContext = new RpcClient.ReconnectContext( - new RpcClient.ServerInfo("127.0.0.1", 0), false); + RpcClient.ReconnectContext reconnectContext = new RpcClient.ReconnectContext(new RpcClient.ServerInfo("127.0.0.1", 0), + false); ((BlockingQueue) reconnectionSignalField.get(rpcClient)).put(reconnectContext); TimeUnit.MILLISECONDS.sleep(100); assertEquals(RpcClientStatus.RUNNING, rpcClient.rpcClientStatus.get()); @@ -929,16 +943,15 @@ public void testReconnectContextAfterStartWithOldServiceInfo() } @Test - public void testReconnectContextAfterStartWithNewServiceInfo() - throws NacosException, InterruptedException, IllegalAccessException { + void testReconnectContextAfterStartWithNewServiceInfo() throws NacosException, InterruptedException, IllegalAccessException { when(serverListFactory.genNextServer()).thenReturn("127.0.0.1:8848"); when(serverListFactory.getServerList()).thenReturn(Collections.singletonList("1.1.1.1:8848")); connection.serverInfo = new RpcClient.ServerInfo("127.0.0.1", 8848); RpcClient rpcClient = buildTestStartClient(serverInfo -> connection); try { rpcClient.start(); - RpcClient.ReconnectContext reconnectContext = new RpcClient.ReconnectContext( - new RpcClient.ServerInfo("127.0.0.1", 0), false); + RpcClient.ReconnectContext reconnectContext = new RpcClient.ReconnectContext(new RpcClient.ServerInfo("127.0.0.1", 0), + false); ((BlockingQueue) reconnectionSignalField.get(rpcClient)).put(reconnectContext); TimeUnit.MILLISECONDS.sleep(100); assertEquals(RpcClientStatus.RUNNING, rpcClient.rpcClientStatus.get()); @@ -949,7 +962,7 @@ public void testReconnectContextAfterStartWithNewServiceInfo() } @Test - public void testHandleConnectionResetRequestWithoutServer() throws NacosException, InterruptedException { + void testHandleConnectionResetRequestWithoutServer() throws NacosException, InterruptedException { when(serverListFactory.genNextServer()).thenReturn("127.0.0.1:8848", "1.1.1.1:8848"); connection.serverInfo = new RpcClient.ServerInfo("127.0.0.1", 8848); RpcClient rpcClient = buildTestStartClient(serverInfo -> { @@ -968,7 +981,7 @@ public void testHandleConnectionResetRequestWithoutServer() throws NacosExceptio } @Test - public void testHandleConnectionResetRequestWithServer() throws NacosException, InterruptedException { + void testHandleConnectionResetRequestWithServer() throws NacosException, InterruptedException { when(serverListFactory.genNextServer()).thenReturn("127.0.0.1:8848", "1.1.1.1:8848"); List serverList = new LinkedList<>(); serverList.add("127.0.0.1:8848"); @@ -995,7 +1008,7 @@ public void testHandleConnectionResetRequestWithServer() throws NacosException, } @Test - public void testHandleConnectionResetRequestWithException() throws NacosException, InterruptedException { + void testHandleConnectionResetRequestWithException() throws NacosException, InterruptedException { when(serverListFactory.genNextServer()).thenReturn("127.0.0.1:8848", "1.1.1.1:8848"); connection.serverInfo = new RpcClient.ServerInfo("127.0.0.1", 8848); RpcClient rpcClient = buildTestStartClient(serverInfo -> { @@ -1017,7 +1030,7 @@ public void testHandleConnectionResetRequestWithException() throws NacosExceptio } @Test - public void testHandleClientDetectionRequest() throws NacosException { + void testHandleClientDetectionRequest() throws NacosException { RpcClient rpcClient = buildTestStartClient(serverInfo -> null); try { rpcClient.start(); @@ -1029,7 +1042,7 @@ public void testHandleClientDetectionRequest() throws NacosException { } @Test - public void testHandleOtherRequest() throws NacosException { + void testHandleOtherRequest() throws NacosException { RpcClient rpcClient = buildTestStartClient(serverInfo -> null); try { rpcClient.start(); @@ -1041,7 +1054,7 @@ public void testHandleOtherRequest() throws NacosException { } @Test - public void testReconnectForRequestFailButHealthCheckOK() throws NacosException { + void testReconnectForRequestFailButHealthCheckOK() throws NacosException { RpcClient rpcClient = buildTestStartClient(serverInfo -> null); rpcClient.currentConnection = connection; connection.serverInfo = new RpcClient.ServerInfo("127.0.0.1", 8848); @@ -1051,7 +1064,7 @@ public void testReconnectForRequestFailButHealthCheckOK() throws NacosException } @Test - public void testReconnectFailTimes() throws NacosException { + void testReconnectFailTimes() throws NacosException { when(serverListFactory.genNextServer()).thenReturn("127.0.0.1:8848"); when(serverListFactory.getServerList()).thenReturn(Collections.singletonList("127.0.0.1:8848")); final AtomicInteger count = new AtomicInteger(0); @@ -1068,7 +1081,7 @@ public void testReconnectFailTimes() throws NacosException { } @Test - public void testGetCurrentServer() { + void testGetCurrentServer() { assertNull(rpcClient.getCurrentServer()); rpcClient.currentConnection = connection; rpcClient.serverListFactory(serverListFactory); @@ -1077,7 +1090,7 @@ public void testGetCurrentServer() { } @Test - public void testCurrentRpcServer() throws IllegalAccessException { + void testCurrentRpcServer() throws IllegalAccessException { when(serverListFactory.getCurrentServer()).thenReturn("127.0.0.1:8848"); serverListFactoryField.set(rpcClient, serverListFactory); RpcClient.ServerInfo serverInfo = rpcClient.currentRpcServer(); @@ -1107,7 +1120,7 @@ public Connection connectToServer(ServerInfo serverInfo) { } @Test - public void testServerInfoSet() { + void testServerInfoSet() { RpcClient.ServerInfo serverInfo = new RpcClient.ServerInfo(); String ip = "127.0.0.1"; int port = 80; @@ -1121,7 +1134,7 @@ public void testServerInfoSet() { } @Test - public void testSetTenant() { + void testSetTenant() { String tenant = "testTenant"; assertNull(rpcClient.getTenant()); rpcClient.setTenant(tenant); @@ -1129,13 +1142,13 @@ public void testSetTenant() { } @Test - public void testGetConnectionAbilityWithNullConnection() { + void testGetConnectionAbilityWithNullConnection() { AbilityStatus abilityStatus = rpcClient.getConnectionAbility(AbilityKey.SERVER_TEST_1); assertNull(abilityStatus); } @Test - public void testGetConnectionAbilityWithReadyConnection() { + void testGetConnectionAbilityWithReadyConnection() { when(connection.getConnectionAbility(AbilityKey.SERVER_TEST_1)).thenReturn(AbilityStatus.SUPPORTED); rpcClient.currentConnection = connection; AbilityStatus abilityStatus = rpcClient.getConnectionAbility(AbilityKey.SERVER_TEST_1); diff --git a/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClientTlsConfigTest.java b/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClientTlsConfigTest.java index f0e6b59ba02..e60b19dc0b7 100644 --- a/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClientTlsConfigTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClientTlsConfigTest.java @@ -16,92 +16,92 @@ package com.alibaba.nacos.common.remote.client; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Properties; -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 RpcClientTlsConfigTest { +class RpcClientTlsConfigTest { @Test - public void testEnableTls() { + void testEnableTls() { Properties properties = new Properties(); properties.setProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE, "true"); - RpcClientTlsConfig tlsConfig = RpcClientTlsConfig.properties(properties); + RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createSdkConfig(properties); assertTrue(tlsConfig.getEnableTls()); } @Test - public void testSslProvider() { + void testSslProvider() { Properties properties = new Properties(); properties.setProperty(RpcConstants.RPC_CLIENT_TLS_PROVIDER, "provider"); - RpcClientTlsConfig tlsConfig = RpcClientTlsConfig.properties(properties); + RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createSdkConfig(properties); assertEquals("provider", tlsConfig.getSslProvider()); } @Test - public void testMutualAuthEnable() { + void testMutualAuthEnable() { Properties properties = new Properties(); properties.setProperty(RpcConstants.RPC_CLIENT_MUTUAL_AUTH, "true"); - RpcClientTlsConfig tlsConfig = RpcClientTlsConfig.properties(properties); + RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createSdkConfig(properties); assertTrue(tlsConfig.getMutualAuthEnable()); } @Test - public void testProtocols() { + void testProtocols() { Properties properties = new Properties(); properties.setProperty(RpcConstants.RPC_CLIENT_TLS_PROTOCOLS, "protocols"); - RpcClientTlsConfig tlsConfig = RpcClientTlsConfig.properties(properties); + RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createSdkConfig(properties); assertEquals("protocols", tlsConfig.getProtocols()); } @Test - public void testCiphers() { + void testCiphers() { Properties properties = new Properties(); properties.setProperty(RpcConstants.RPC_CLIENT_TLS_CIPHERS, "ciphers"); - RpcClientTlsConfig tlsConfig = RpcClientTlsConfig.properties(properties); + RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createSdkConfig(properties); assertEquals("ciphers", tlsConfig.getCiphers()); } @Test - public void testTrustCollectionCertFile() { + void testTrustCollectionCertFile() { Properties properties = new Properties(); properties.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH, "trustCollectionCertFile"); - RpcClientTlsConfig tlsConfig = RpcClientTlsConfig.properties(properties); + RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createSdkConfig(properties); assertEquals("trustCollectionCertFile", tlsConfig.getTrustCollectionCertFile()); } @Test - public void testCertChainFile() { + void testCertChainFile() { Properties properties = new Properties(); properties.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_CHAIN_PATH, "certChainFile"); - RpcClientTlsConfig tlsConfig = RpcClientTlsConfig.properties(properties); + RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createSdkConfig(properties); assertEquals("certChainFile", tlsConfig.getCertChainFile()); } @Test - public void testCertPrivateKey() { + void testCertPrivateKey() { Properties properties = new Properties(); properties.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_KEY, "certPrivateKey"); - RpcClientTlsConfig tlsConfig = RpcClientTlsConfig.properties(properties); + RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createSdkConfig(properties); assertEquals("certPrivateKey", tlsConfig.getCertPrivateKey()); } @Test - public void testTrustAll() { + void testTrustAll() { Properties properties = new Properties(); properties.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_ALL, "true"); - RpcClientTlsConfig tlsConfig = RpcClientTlsConfig.properties(properties); + RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createSdkConfig(properties); assertTrue(tlsConfig.getTrustAll()); } @Test - public void testCertPrivateKeyPassword() { + void testCertPrivateKeyPassword() { Properties properties = new Properties(); properties.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_PWD, "trustPwd"); - RpcClientTlsConfig tlsConfig = RpcClientTlsConfig.properties(properties); + RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createSdkConfig(properties); assertEquals("trustPwd", tlsConfig.getCertPrivateKeyPassword()); } -} \ No newline at end of file +} diff --git a/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClusterClientTlsConfigTest.java b/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClusterClientTlsConfigTest.java new file mode 100644 index 00000000000..605b53cd5eb --- /dev/null +++ b/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcClusterClientTlsConfigTest.java @@ -0,0 +1,128 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.common.remote.client; + +import org.junit.jupiter.api.Test; + +import java.util.Properties; + +import static com.alibaba.nacos.common.remote.client.RpcConstants.NACOS_PEER_RPC; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.MUTUAL_AUTH; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.TLS_CERT_CHAIN_PATH; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.TLS_CERT_KEY; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.TLS_CIPHERS; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.TLS_ENABLE; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.TLS_PROTOCOLS; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.TLS_PROVIDER; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.TLS_TRUST_ALL; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.TLS_TRUST_COLLECTION_CHAIN_PATH; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.TLS_TRUST_PWD; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class RpcClusterClientTlsConfigTest { + + @Test + void testEnableTls() { + Properties properties = new Properties(); + properties.setProperty(NACOS_PEER_RPC + TLS_ENABLE, "true"); + RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createClusterConfig(properties); + assertTrue(tlsConfig.getEnableTls()); + } + + @Test + void testSslProvider() { + Properties properties = new Properties(); + properties.setProperty(NACOS_PEER_RPC + TLS_ENABLE, "true"); + properties.setProperty(NACOS_PEER_RPC + TLS_PROVIDER, "provider"); + RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createClusterConfig(properties); + assertEquals("provider", tlsConfig.getSslProvider()); + } + + @Test + void testMutualAuthEnable() { + Properties properties = new Properties(); + properties.setProperty(NACOS_PEER_RPC + TLS_ENABLE, "true"); + properties.setProperty(NACOS_PEER_RPC + MUTUAL_AUTH, "true"); + RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createClusterConfig(properties); + assertTrue(tlsConfig.getMutualAuthEnable()); + } + + @Test + void testProtocols() { + Properties properties = new Properties(); + properties.setProperty(NACOS_PEER_RPC + TLS_ENABLE, "true"); + properties.setProperty(NACOS_PEER_RPC + TLS_PROTOCOLS, "protocols"); + RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createClusterConfig(properties); + assertEquals("protocols", tlsConfig.getProtocols()); + } + + @Test + void testCiphers() { + Properties properties = new Properties(); + properties.setProperty(NACOS_PEER_RPC + TLS_ENABLE, "true"); + properties.setProperty(NACOS_PEER_RPC + TLS_CIPHERS, "ciphers"); + RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createClusterConfig(properties); + assertEquals("ciphers", tlsConfig.getCiphers()); + } + + @Test + void testTrustCollectionCertFile() { + Properties properties = new Properties(); + properties.setProperty(NACOS_PEER_RPC + TLS_ENABLE, "true"); + properties.setProperty(NACOS_PEER_RPC + TLS_TRUST_COLLECTION_CHAIN_PATH, "trustCollectionCertFile"); + RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createClusterConfig(properties); + assertEquals("trustCollectionCertFile", tlsConfig.getTrustCollectionCertFile()); + } + + @Test + void testCertChainFile() { + Properties properties = new Properties(); + properties.setProperty(NACOS_PEER_RPC + TLS_ENABLE, "true"); + properties.setProperty(NACOS_PEER_RPC + TLS_CERT_CHAIN_PATH, "certChainFile"); + RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createClusterConfig(properties); + assertEquals("certChainFile", tlsConfig.getCertChainFile()); + } + + @Test + void testCertPrivateKey() { + Properties properties = new Properties(); + properties.setProperty(NACOS_PEER_RPC + TLS_ENABLE, "true"); + properties.setProperty(NACOS_PEER_RPC + TLS_CERT_KEY, "certPrivateKey"); + RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createClusterConfig(properties); + assertEquals("certPrivateKey", tlsConfig.getCertPrivateKey()); + } + + @Test + void testTrustAll() { + Properties properties = new Properties(); + properties.setProperty(NACOS_PEER_RPC + TLS_ENABLE, "true"); + properties.setProperty(NACOS_PEER_RPC + TLS_TRUST_ALL, "true"); + RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createClusterConfig(properties); + assertTrue(tlsConfig.getTrustAll()); + } + + @Test + void testCertPrivateKeyPassword() { + Properties properties = new Properties(); + properties.setProperty(NACOS_PEER_RPC + TLS_ENABLE, "true"); + properties.setProperty(NACOS_PEER_RPC + TLS_TRUST_PWD, "trustPwd"); + RpcClientTlsConfig tlsConfig = RpcClientTlsConfigFactory.getInstance().createClusterConfig(properties); + assertEquals("trustPwd", tlsConfig.getCertPrivateKeyPassword()); + } +} + diff --git a/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcConstantsTest.java b/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcConstantsTest.java index 6d4a88400f5..7a99fc9f641 100644 --- a/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcConstantsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/remote/client/RpcConstantsTest.java @@ -16,18 +16,17 @@ package com.alibaba.nacos.common.remote.client; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class RpcConstantsTest { +class RpcConstantsTest { @Test - public void testGetRpcParams() { - Class clazz = RpcConstants.class; - Field[] declaredFields = clazz.getDeclaredFields(); + void testGetRpcParams() { + Field[] declaredFields = RpcConstants.class.getDeclaredFields(); int i = 0; for (Field declaredField : declaredFields) { declaredField.setAccessible(true); diff --git a/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/DefaultGrpcClientConfigTest.java b/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/DefaultGrpcClientConfigTest.java index 718bab454e5..0a54ffe242f 100644 --- a/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/DefaultGrpcClientConfigTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/DefaultGrpcClientConfigTest.java @@ -17,33 +17,33 @@ package com.alibaba.nacos.common.remote.client.grpc; import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig; -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.HashMap; import java.util.Map; import java.util.Properties; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; -public class DefaultGrpcClientConfigTest { +class DefaultGrpcClientConfigTest { - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { System.setProperty("nacos.common.processors", "2"); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { System.clearProperty("nacos.common.processors"); } @Test - public void testDefault() { + void testDefault() { DefaultGrpcClientConfig config = (DefaultGrpcClientConfig) DefaultGrpcClientConfig.newBuilder().build(); assertNull(config.name()); assertEquals(3, config.retryTimes()); @@ -65,7 +65,7 @@ public void testDefault() { } @Test - public void testFromProperties() { + void testFromProperties() { Properties properties = new Properties(); properties.setProperty(GrpcConstants.GRPC_NAME, "test"); properties.setProperty(GrpcConstants.GRPC_RETRY_TIMES, "3"); @@ -84,7 +84,7 @@ public void testFromProperties() { properties.setProperty(GrpcConstants.GRPC_CHANNEL_CAPABILITY_NEGOTIATION_TIMEOUT, "5000"); DefaultGrpcClientConfig config = (DefaultGrpcClientConfig) DefaultGrpcClientConfig.newBuilder() - .fromProperties(properties).build(); + .fromProperties(properties, null).build(); assertEquals("test", config.name()); assertEquals(3, config.retryTimes()); @@ -106,7 +106,7 @@ public void testFromProperties() { } @Test - public void testName() { + void testName() { String name = "test"; DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder(); builder.setName(name); @@ -115,7 +115,7 @@ public void testName() { } @Test - public void testSetRetryTimes() { + void testSetRetryTimes() { int retryTimes = 3; DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder(); builder.setRetryTimes(retryTimes); @@ -124,7 +124,7 @@ public void testSetRetryTimes() { } @Test - public void testSetTimeOutMills() { + void testSetTimeOutMills() { long timeOutMills = 3000; DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder(); builder.setTimeOutMills(timeOutMills); @@ -133,7 +133,7 @@ public void testSetTimeOutMills() { } @Test - public void testSetConnectionKeepAlive() { + void testSetConnectionKeepAlive() { long connectionKeepAlive = 5000; DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder(); builder.setConnectionKeepAlive(connectionKeepAlive); @@ -142,7 +142,7 @@ public void testSetConnectionKeepAlive() { } @Test - public void testSetThreadPoolKeepAlive() { + void testSetThreadPoolKeepAlive() { long threadPoolKeepAlive = 10000; DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder(); builder.setThreadPoolKeepAlive(threadPoolKeepAlive); @@ -151,7 +151,7 @@ public void testSetThreadPoolKeepAlive() { } @Test - public void testSetThreadPoolCoreSize() { + void testSetThreadPoolCoreSize() { int threadPoolCoreSize = 2; DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder(); builder.setThreadPoolCoreSize(threadPoolCoreSize); @@ -160,7 +160,7 @@ public void testSetThreadPoolCoreSize() { } @Test - public void testSetThreadPoolMaxSize() { + void testSetThreadPoolMaxSize() { int threadPoolMaxSize = 8; DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder(); builder.setThreadPoolMaxSize(threadPoolMaxSize); @@ -169,7 +169,7 @@ public void testSetThreadPoolMaxSize() { } @Test - public void testSetServerCheckTimeOut() { + void testSetServerCheckTimeOut() { long serverCheckTimeOut = 3000; DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder(); builder.setServerCheckTimeOut(serverCheckTimeOut); @@ -178,7 +178,7 @@ public void testSetServerCheckTimeOut() { } @Test - public void testSetThreadPoolQueueSize() { + void testSetThreadPoolQueueSize() { int threadPoolQueueSize = 10000; DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder(); builder.setThreadPoolQueueSize(threadPoolQueueSize); @@ -187,7 +187,7 @@ public void testSetThreadPoolQueueSize() { } @Test - public void testSetMaxInboundMessageSize() { + void testSetMaxInboundMessageSize() { int maxInboundMessageSize = 10485760; DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder(); builder.setMaxInboundMessageSize(maxInboundMessageSize); @@ -196,7 +196,7 @@ public void testSetMaxInboundMessageSize() { } @Test - public void testSetChannelKeepAlive() { + void testSetChannelKeepAlive() { int channelKeepAlive = 60000; DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder(); builder.setChannelKeepAlive(channelKeepAlive); @@ -205,7 +205,7 @@ public void testSetChannelKeepAlive() { } @Test - public void testSetChannelKeepAliveTimeout() { + void testSetChannelKeepAliveTimeout() { int channelKeepAliveTimeout = 20000; DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder(); builder.setChannelKeepAliveTimeout(channelKeepAliveTimeout); @@ -214,7 +214,7 @@ public void testSetChannelKeepAliveTimeout() { } @Test - public void testSetCapabilityNegotiationTimeout() { + void testSetCapabilityNegotiationTimeout() { long capabilityNegotiationTimeout = 5000; DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder(); builder.setCapabilityNegotiationTimeout(capabilityNegotiationTimeout); @@ -223,7 +223,7 @@ public void testSetCapabilityNegotiationTimeout() { } @Test - public void testSetHealthCheckRetryTimes() { + void testSetHealthCheckRetryTimes() { int healthCheckRetryTimes = 3; DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder(); builder.setHealthCheckRetryTimes(healthCheckRetryTimes); @@ -232,7 +232,7 @@ public void testSetHealthCheckRetryTimes() { } @Test - public void testSetHealthCheckTimeOut() { + void testSetHealthCheckTimeOut() { long healthCheckTimeOut = 3000; DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder(); builder.setHealthCheckTimeOut(healthCheckTimeOut); @@ -241,7 +241,7 @@ public void testSetHealthCheckTimeOut() { } @Test - public void testSetLabels() { + void testSetLabels() { Map labels = new HashMap<>(); labels.put("key1", "value1"); labels.put("key2", "value2"); @@ -254,7 +254,7 @@ public void testSetLabels() { } @Test - public void testSetTlsConfig() { + void testSetTlsConfig() { RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig(); DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder(); builder.setTlsConfig(tlsConfig); @@ -263,7 +263,7 @@ public void testSetTlsConfig() { } @Test - public void testSetTlsConfigDirectly() { + void testSetTlsConfigDirectly() { RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig(); DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder(); DefaultGrpcClientConfig config = (DefaultGrpcClientConfig) builder.build(); diff --git a/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClientTest.java b/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClientTest.java index 28b89e8c4f8..474d585955a 100644 --- a/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClientTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClientTest.java @@ -38,12 +38,14 @@ import io.grpc.ClientCall; import io.grpc.ManagedChannel; import io.grpc.stub.StreamObserver; -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 org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.mockito.stubbing.Answer; import java.lang.reflect.Field; @@ -55,11 +57,11 @@ import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReference; -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.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.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.Mockito.doReturn; @@ -70,23 +72,25 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class GrpcClientTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class GrpcClientTest { protected GrpcClient grpcClient; - @Mock - RpcClientTlsConfig tlsConfig; - protected RpcClient.ServerInfo serverInfo; protected GrpcClientConfig clientConfig; - @Before - public void setUp() throws Exception { - clientConfig = DefaultGrpcClientConfig.newBuilder().setServerCheckTimeOut(100L) - .setCapabilityNegotiationTimeout(100L).setChannelKeepAliveTimeout((int) TimeUnit.SECONDS.toMillis(3L)) - .setChannelKeepAlive(1000).setName("testClient").build(); + @Mock + RpcClientTlsConfig tlsConfig; + + @BeforeEach + void setUp() throws Exception { + clientConfig = DefaultGrpcClientConfig.newBuilder().setServerCheckTimeOut(100L).setCapabilityNegotiationTimeout(100L) + .setChannelKeepAliveTimeout((int) TimeUnit.SECONDS.toMillis(3L)).setChannelKeepAlive(1000).setName("testClient") + .build(); clientConfig.setTlsConfig(tlsConfig); grpcClient = spy(new GrpcClient(clientConfig) { @Override @@ -102,29 +106,29 @@ public int rpcPortOffset() { serverInfo = new RpcClient.ServerInfo("10.10.10.10", 8848); } - @After - public void tearDown() throws NacosException { + @AfterEach + void tearDown() throws NacosException { grpcClient.shutdown(); } @Test - public void testGetConnectionType() { + void testGetConnectionType() { assertEquals(ConnectionType.GRPC, grpcClient.getConnectionType()); } @Test - public void testConnectToServerFailed() { + void testConnectToServerFailed() { assertNull(grpcClient.connectToServer(serverInfo)); } @Test - public void testConnectToServerException() { + void testConnectToServerException() { doThrow(new RuntimeException("test")).when(grpcClient).createNewChannelStub(any(ManagedChannel.class)); assertNull(grpcClient.connectToServer(serverInfo)); } @Test - public void testConnectToServerMockSuccess() throws ExecutionException, InterruptedException, TimeoutException { + void testConnectToServerMockSuccess() throws ExecutionException, InterruptedException, TimeoutException { RequestGrpc.RequestFutureStub stub = mockStub(new ServerCheckResponse(), null); doReturn(stub).when(grpcClient).createNewChannelStub(any(ManagedChannel.class)); Connection connection = grpcClient.connectToServer(serverInfo); @@ -134,8 +138,7 @@ public void testConnectToServerMockSuccess() throws ExecutionException, Interrup } @Test - public void testConnectToServerMockSuccessWithAbility() - throws ExecutionException, InterruptedException, TimeoutException { + void testConnectToServerMockSuccessWithAbility() throws ExecutionException, InterruptedException, TimeoutException { ServerCheckResponse response = new ServerCheckResponse(); response.setSupportAbilityNegotiation(true); RequestGrpc.RequestFutureStub stub = mockStub(response, null); @@ -145,8 +148,7 @@ public void testConnectToServerMockSuccessWithAbility() } @Test - public void testConnectToServerMockHealthCheckFailed() - throws ExecutionException, InterruptedException, TimeoutException { + void testConnectToServerMockHealthCheckFailed() throws ExecutionException, InterruptedException, TimeoutException { RequestGrpc.RequestFutureStub stub = mockStub(null, new RuntimeException("test")); doReturn(stub).when(grpcClient).createNewChannelStub(any(ManagedChannel.class)); Connection connection = grpcClient.connectToServer(serverInfo); @@ -171,13 +173,12 @@ private RequestGrpc.RequestFutureStub mockStub(ServerCheckResponse response, Thr } @Test - public void testBindRequestStreamOnNextSetupAckRequest() + void testBindRequestStreamOnNextSetupAckRequest() throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class); GrpcConnection grpcConnection = mock(GrpcConnection.class); when(stub.requestBiStream(any())).thenAnswer((Answer>) invocationOnMock -> { - ((StreamObserver) invocationOnMock.getArgument(0)) - .onNext(GrpcUtils.convert(new SetupAckRequest())); + ((StreamObserver) invocationOnMock.getArgument(0)).onNext(GrpcUtils.convert(new SetupAckRequest())); return null; }); setCurrentConnection(grpcConnection, grpcClient); @@ -186,13 +187,12 @@ public void testBindRequestStreamOnNextSetupAckRequest() } @Test - public void testBindRequestStreamOnNextOtherRequest() + void testBindRequestStreamOnNextOtherRequest() throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class); GrpcConnection grpcConnection = mock(GrpcConnection.class); when(stub.requestBiStream(any())).thenAnswer((Answer>) invocationOnMock -> { - ((StreamObserver) invocationOnMock.getArgument(0)) - .onNext(GrpcUtils.convert(new ConnectResetRequest())); + ((StreamObserver) invocationOnMock.getArgument(0)).onNext(GrpcUtils.convert(new ConnectResetRequest())); return null; }); grpcClient.registerServerRequestHandler((request, connection) -> { @@ -207,13 +207,12 @@ public void testBindRequestStreamOnNextOtherRequest() } @Test - public void testBindRequestStreamOnNextNoRequest() + void testBindRequestStreamOnNextNoRequest() throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class); GrpcConnection grpcConnection = mock(GrpcConnection.class); when(stub.requestBiStream(any())).thenAnswer((Answer>) invocationOnMock -> { - ((StreamObserver) invocationOnMock.getArgument(0)) - .onNext(GrpcUtils.convert(new ConnectResetRequest())); + ((StreamObserver) invocationOnMock.getArgument(0)).onNext(GrpcUtils.convert(new ConnectResetRequest())); return null; }); grpcClient.registerServerRequestHandler((request, connection) -> null); @@ -223,13 +222,12 @@ public void testBindRequestStreamOnNextNoRequest() } @Test - public void testBindRequestStreamOnNextHandleException() + void testBindRequestStreamOnNextHandleException() throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class); GrpcConnection grpcConnection = mock(GrpcConnection.class); when(stub.requestBiStream(any())).thenAnswer((Answer>) invocationOnMock -> { - ((StreamObserver) invocationOnMock.getArgument(0)) - .onNext(GrpcUtils.convert(new ConnectResetRequest())); + ((StreamObserver) invocationOnMock.getArgument(0)).onNext(GrpcUtils.convert(new ConnectResetRequest())); return null; }); grpcClient.registerServerRequestHandler((request, connection) -> { @@ -241,7 +239,7 @@ public void testBindRequestStreamOnNextHandleException() } @Test - public void testBindRequestStreamOnNextParseException() + void testBindRequestStreamOnNextParseException() throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class); GrpcConnection grpcConnection = mock(GrpcConnection.class); @@ -255,7 +253,7 @@ public void testBindRequestStreamOnNextParseException() } @Test - public void testBindRequestStreamOnErrorFromRunning() + void testBindRequestStreamOnErrorFromRunning() throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class); GrpcConnection grpcConnection = mock(GrpcConnection.class); @@ -271,7 +269,7 @@ public void testBindRequestStreamOnErrorFromRunning() } @Test - public void testBindRequestStreamOnErrorFromNotRunning() + void testBindRequestStreamOnErrorFromNotRunning() throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class); GrpcConnection grpcConnection = mock(GrpcConnection.class); @@ -289,7 +287,7 @@ public void testBindRequestStreamOnErrorFromNotRunning() } @Test - public void testBindRequestStreamOnCompletedFromRunning() + void testBindRequestStreamOnCompletedFromRunning() throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class); GrpcConnection grpcConnection = mock(GrpcConnection.class); @@ -305,7 +303,7 @@ public void testBindRequestStreamOnCompletedFromRunning() } @Test - public void testBindRequestStreamOnCompletedFromNotRunning() + void testBindRequestStreamOnCompletedFromNotRunning() throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class); GrpcConnection grpcConnection = mock(GrpcConnection.class); @@ -323,11 +321,9 @@ public void testBindRequestStreamOnCompletedFromNotRunning() } private void invokeBindRequestStream(GrpcClient grpcClient, BiRequestStreamGrpc.BiRequestStreamStub stub, - GrpcConnection grpcConnection) - throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { - Method bindRequestStreamMethod = GrpcClient.class - .getDeclaredMethod("bindRequestStream", BiRequestStreamGrpc.BiRequestStreamStub.class, - GrpcConnection.class); + GrpcConnection grpcConnection) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + Method bindRequestStreamMethod = GrpcClient.class.getDeclaredMethod("bindRequestStream", + BiRequestStreamGrpc.BiRequestStreamStub.class, GrpcConnection.class); bindRequestStreamMethod.setAccessible(true); bindRequestStreamMethod.invoke(grpcClient, stub, grpcConnection); } @@ -339,15 +335,14 @@ private void setCurrentConnection(GrpcConnection connection, GrpcClient client) connectionField.set(client, connection); } - private void setStatus(GrpcClient grpcClient, RpcClientStatus status) - throws IllegalAccessException, NoSuchFieldException { + private void setStatus(GrpcClient grpcClient, RpcClientStatus status) throws IllegalAccessException, NoSuchFieldException { Field statusField = RpcClient.class.getDeclaredField("rpcClientStatus"); statusField.setAccessible(true); statusField.set(grpcClient, new AtomicReference<>(status)); } @Test - public void testAfterReset() throws NoSuchFieldException, IllegalAccessException { + void testAfterReset() throws NoSuchFieldException, IllegalAccessException { Field recAbilityContextField = GrpcClient.class.getDeclaredField("recAbilityContext"); recAbilityContextField.setAccessible(true); GrpcClient.RecAbilityContext context = mock(GrpcClient.RecAbilityContext.class); @@ -357,7 +352,7 @@ public void testAfterReset() throws NoSuchFieldException, IllegalAccessException } @Test - public void testAppendRecAbilityContext() { + void testAppendRecAbilityContext() { GrpcClient.RecAbilityContext context = new GrpcClient.RecAbilityContext(null); GrpcConnection connection = mock(GrpcConnection.class); context.reset(connection); @@ -371,7 +366,7 @@ public void testAppendRecAbilityContext() { } @Test - public void testSendResponseWithException() + void testSendResponseWithException() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException { GrpcConnection connection = mock(GrpcConnection.class); setCurrentConnection(connection, grpcClient); @@ -383,7 +378,7 @@ public void testSendResponseWithException() } @Test - public void testConstructorWithServerListFactory() { + void testConstructorWithServerListFactory() { ServerListFactory serverListFactory = mock(ServerListFactory.class); GrpcClient grpcClient = new GrpcClient(clientConfig, serverListFactory) { @Override @@ -400,7 +395,7 @@ public int rpcPortOffset() { } @Test - public void testConstructorWithoutServerListFactory() { + void testConstructorWithoutServerListFactory() { GrpcClient grpcClient = new GrpcClient("testNoFactory", 2, 2, Collections.emptyMap()) { @Override protected AbilityMode abilityMode() { diff --git a/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClientTlsTest.java b/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClientTlsTest.java index 801ead87003..d5cff6bd529 100644 --- a/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClientTlsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClientTlsTest.java @@ -16,18 +16,18 @@ package com.alibaba.nacos.common.remote.client.grpc; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.when; /** * Currently not good way to test tls relative codes, and it's a optional feature, single test first. */ -public class GrpcClientTlsTest extends GrpcClientTest { +class GrpcClientTlsTest extends GrpcClientTest { @Test - public void testGrpcEnableTlsAndTrustPart() throws Exception { + void testGrpcEnableTlsAndTrustPart() throws Exception { when(tlsConfig.getEnableTls()).thenReturn(true); when(tlsConfig.getTrustCollectionCertFile()).thenReturn("ca-cert.pem"); when(tlsConfig.getCiphers()).thenReturn("ECDHE-RSA-AES128-GCM-SHA256", "ECDHE-RSA-AES256-GCM-SHA384"); @@ -36,7 +36,7 @@ public void testGrpcEnableTlsAndTrustPart() throws Exception { } @Test - public void testGrpcEnableTlsAndTrustAll() throws Exception { + void testGrpcEnableTlsAndTrustAll() throws Exception { when(tlsConfig.getEnableTls()).thenReturn(true); when(tlsConfig.getTrustCollectionCertFile()).thenReturn("ca-cert.pem"); when(tlsConfig.getCiphers()).thenReturn("ECDHE-RSA-AES128-GCM-SHA256", "ECDHE-RSA-AES256-GCM-SHA384"); @@ -46,7 +46,7 @@ public void testGrpcEnableTlsAndTrustAll() throws Exception { } @Test - public void testGrpcEnableTlsAndEnableMutualAuth() throws Exception { + void testGrpcEnableTlsAndEnableMutualAuth() throws Exception { when(tlsConfig.getEnableTls()).thenReturn(true); when(tlsConfig.getTrustCollectionCertFile()).thenReturn("ca-cert.pem"); when(tlsConfig.getCiphers()).thenReturn("ECDHE-RSA-AES128-GCM-SHA256", "ECDHE-RSA-AES256-GCM-SHA384"); @@ -58,7 +58,7 @@ public void testGrpcEnableTlsAndEnableMutualAuth() throws Exception { } @Test - public void testGrpcSslProvider() { + void testGrpcSslProvider() { when(tlsConfig.getEnableTls()).thenReturn(true); when(tlsConfig.getTrustCollectionCertFile()).thenReturn("ca-cert.pem"); when(tlsConfig.getCiphers()).thenReturn("ECDHE-RSA-AES128-GCM-SHA256", "ECDHE-RSA-AES256-GCM-SHA384"); @@ -71,7 +71,7 @@ public void testGrpcSslProvider() { } @Test - public void testGrpcEmptyTrustCollectionCertFile() { + void testGrpcEmptyTrustCollectionCertFile() { when(tlsConfig.getEnableTls()).thenReturn(true); when(tlsConfig.getTrustCollectionCertFile()).thenReturn(""); when(tlsConfig.getCiphers()).thenReturn("ECDHE-RSA-AES128-GCM-SHA256", "ECDHE-RSA-AES256-GCM-SHA384"); @@ -80,7 +80,7 @@ public void testGrpcEmptyTrustCollectionCertFile() { } @Test - public void testGrpcMutualAuth() { + void testGrpcMutualAuth() { when(tlsConfig.getEnableTls()).thenReturn(true); when(tlsConfig.getCiphers()).thenReturn("ECDHE-RSA-AES128-GCM-SHA256", "ECDHE-RSA-AES256-GCM-SHA384"); when(tlsConfig.getProtocols()).thenReturn("TLSv1.2,TLSv1.3"); diff --git a/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClusterClientTest.java b/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClusterClientTest.java index d50b3bfe2a2..3ccda6bfd33 100644 --- a/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClusterClientTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClusterClientTest.java @@ -18,20 +18,20 @@ import com.alibaba.nacos.api.ability.constant.AbilityMode; import com.alibaba.nacos.api.exception.NacosException; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.Properties; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class GrpcClusterClientTest { +class GrpcClusterClientTest { GrpcClusterClient grpcClusterClient; - @After - public void tearDown() throws NacosException { + @AfterEach + void tearDown() throws NacosException { System.clearProperty(GrpcConstants.NACOS_SERVER_GRPC_PORT_OFFSET_KEY); if (grpcClusterClient != null) { grpcClusterClient.shutdown(); @@ -39,26 +39,28 @@ public void tearDown() throws NacosException { } @Test - public void testAbilityMode() { + void testAbilityMode() { grpcClusterClient = new GrpcClusterClient("test"); assertEquals(AbilityMode.CLUSTER_CLIENT, grpcClusterClient.abilityMode()); } @Test - public void testRpcPortOffsetDefault() { - grpcClusterClient = new GrpcClusterClient(new Properties()); + void testRpcPortOffsetDefault() { + DefaultGrpcClientConfig.Builder builder = DefaultGrpcClientConfig.newBuilder() + .buildClusterFromProperties(new Properties()); + grpcClusterClient = new GrpcClusterClient(builder.build()); assertEquals(1001, grpcClusterClient.rpcPortOffset()); } @Test - public void testRpcPortOffsetFromSystemProperty() { + void testRpcPortOffsetFromSystemProperty() { System.setProperty(GrpcConstants.NACOS_SERVER_GRPC_PORT_OFFSET_KEY, "10001"); grpcClusterClient = new GrpcClusterClient("test", 8, 8, Collections.emptyMap()); assertEquals(10001, grpcClusterClient.rpcPortOffset()); } @Test - public void testGrpcClientByConfig() { + void testGrpcClientByConfig() { GrpcClientConfig config = DefaultGrpcClientConfig.newBuilder().setName("test111").build(); grpcClusterClient = new GrpcClusterClient(config); assertEquals("test111", grpcClusterClient.getName()); diff --git a/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcConnectionTest.java b/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcConnectionTest.java index 65468cfb127..fb312fed736 100644 --- a/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcConnectionTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcConnectionTest.java @@ -34,13 +34,15 @@ import com.google.protobuf.UnsafeByteOperations; import io.grpc.ManagedChannel; import io.grpc.stub.StreamObserver; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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 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.concurrent.CancellationException; import java.util.concurrent.ExecutionException; @@ -48,8 +50,9 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; -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.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; @@ -58,8 +61,19 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class GrpcConnectionTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class GrpcConnectionTest { + + @Mock + ListenableFuture future; + + Payload responsePayload; + + Payload errorResponsePayload; + + GrpcConnection connection; @Mock private Executor executor; @@ -73,22 +87,13 @@ public class GrpcConnectionTest { @Mock private RequestGrpc.RequestFutureStub requestFutureStub; - @Mock - ListenableFuture future; - - Payload responsePayload; - - Payload errorResponsePayload; - - GrpcConnection connection; - - @BeforeClass - public static void setUpBeforeClass() { + @BeforeAll + static void setUpBeforeClass() { PayloadRegistry.init(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { connection = new GrpcConnection(new RpcClient.ServerInfo(), executor); connection.setChannel(channel); connection.setPayloadStreamObserver(payloadStreamObserver); @@ -101,38 +106,40 @@ public void setUp() throws Exception { when(future.isDone()).thenReturn(true); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { connection.close(); } @Test - public void testGetAll() { + void testGetAll() { assertEquals(channel, connection.getChannel()); assertEquals(payloadStreamObserver, connection.getPayloadStreamObserver()); assertEquals(requestFutureStub, connection.getGrpcFutureServiceStub()); } @Test - public void testRequestSuccessSync() throws NacosException { + void testRequestSuccessSync() throws NacosException { Response response = connection.request(new HealthCheckRequest(), -1); assertTrue(response instanceof HealthCheckResponse); } @Test - public void testRequestSuccessAsync() throws NacosException { + void testRequestSuccessAsync() throws NacosException { Response response = connection.request(new HealthCheckRequest(), 100); assertTrue(response instanceof HealthCheckResponse); } - @Test(expected = NacosException.class) - public void testRequestTimeout() throws InterruptedException, ExecutionException, TimeoutException, NacosException { - when(future.get(100L, TimeUnit.MILLISECONDS)).thenThrow(new TimeoutException("test")); - connection.request(new HealthCheckRequest(), 100); + @Test + void testRequestTimeout() throws InterruptedException, ExecutionException, TimeoutException, NacosException { + assertThrows(NacosException.class, () -> { + when(future.get(100L, TimeUnit.MILLISECONDS)).thenThrow(new TimeoutException("test")); + connection.request(new HealthCheckRequest(), 100); + }); } @Test - public void testRequestFuture() throws Exception { + void testRequestFuture() throws Exception { RequestFuture requestFuture = connection.requestFuture(new HealthCheckRequest()); assertTrue(requestFuture.isDone()); Response response = requestFuture.get(); @@ -140,43 +147,47 @@ public void testRequestFuture() throws Exception { } @Test - public void testRequestFutureWithTimeout() throws Exception { + void testRequestFutureWithTimeout() throws Exception { RequestFuture requestFuture = connection.requestFuture(new HealthCheckRequest()); assertTrue(requestFuture.isDone()); Response response = requestFuture.get(100L); assertTrue(response instanceof HealthCheckResponse); } - @Test(expected = NacosException.class) - public void testRequestFutureFailure() throws Exception { - when(future.get()).thenReturn(errorResponsePayload); - RequestFuture requestFuture = connection.requestFuture(new HealthCheckRequest()); - assertTrue(requestFuture.isDone()); - requestFuture.get(); + @Test + void testRequestFutureFailure() throws Exception { + assertThrows(NacosException.class, () -> { + when(future.get()).thenReturn(errorResponsePayload); + RequestFuture requestFuture = connection.requestFuture(new HealthCheckRequest()); + assertTrue(requestFuture.isDone()); + requestFuture.get(); + }); } - @Test(expected = NacosException.class) - public void testRequestFutureWithTimeoutFailure() throws Exception { - when(future.get(100L, TimeUnit.MILLISECONDS)).thenReturn(errorResponsePayload); - RequestFuture requestFuture = connection.requestFuture(new HealthCheckRequest()); - assertTrue(requestFuture.isDone()); - requestFuture.get(100L); + @Test + void testRequestFutureWithTimeoutFailure() throws Exception { + assertThrows(NacosException.class, () -> { + when(future.get(100L, TimeUnit.MILLISECONDS)).thenReturn(errorResponsePayload); + RequestFuture requestFuture = connection.requestFuture(new HealthCheckRequest()); + assertTrue(requestFuture.isDone()); + requestFuture.get(100L); + }); } @Test - public void testSendResponse() { + void testSendResponse() { connection.sendResponse(new HealthCheckResponse()); verify(payloadStreamObserver).onNext(any(Payload.class)); } @Test - public void testSendRequest() { + void testSendRequest() { connection.sendRequest(new HealthCheckRequest()); verify(payloadStreamObserver).onNext(any(Payload.class)); } @Test - public void testAsyncRequestSuccess() throws NacosException { + void testAsyncRequestSuccess() throws NacosException { doAnswer(invocationOnMock -> { ((Runnable) invocationOnMock.getArgument(0)).run(); return null; @@ -187,7 +198,7 @@ public void testAsyncRequestSuccess() throws NacosException { } @Test - public void testAsyncRequestError() throws NacosException, ExecutionException, InterruptedException { + void testAsyncRequestError() throws NacosException, ExecutionException, InterruptedException { when(future.get()).thenReturn(errorResponsePayload); doAnswer(invocationOnMock -> { ((Runnable) invocationOnMock.getArgument(0)).run(); @@ -199,12 +210,12 @@ public void testAsyncRequestError() throws NacosException, ExecutionException, I } @Test - public void testAsyncRequestNullResponse() throws NacosException, ExecutionException, InterruptedException { + void testAsyncRequestNullResponse() throws NacosException, ExecutionException, InterruptedException { byte[] jsonBytes = JacksonUtils.toJsonBytes(null); Metadata.Builder metaBuilder = Metadata.newBuilder().setType(HealthCheckResponse.class.getSimpleName()); Payload nullResponsePayload = Payload.newBuilder() - .setBody(Any.newBuilder().setValue(UnsafeByteOperations.unsafeWrap(jsonBytes))) - .setMetadata(metaBuilder.build()).build(); + .setBody(Any.newBuilder().setValue(UnsafeByteOperations.unsafeWrap(jsonBytes))).setMetadata(metaBuilder.build()) + .build(); when(future.get()).thenReturn(nullResponsePayload); doAnswer(invocationOnMock -> { ((Runnable) invocationOnMock.getArgument(0)).run(); @@ -216,7 +227,7 @@ public void testAsyncRequestNullResponse() throws NacosException, ExecutionExcep } @Test - public void testAsyncRequestWithCancelException() throws NacosException, ExecutionException, InterruptedException { + void testAsyncRequestWithCancelException() throws NacosException, ExecutionException, InterruptedException { when(future.get()).thenThrow(new CancellationException("test")); doAnswer(invocationOnMock -> { ((Runnable) invocationOnMock.getArgument(0)).run(); @@ -228,7 +239,7 @@ public void testAsyncRequestWithCancelException() throws NacosException, Executi } @Test - public void testAsyncRequestWithOtherException() throws NacosException, ExecutionException, InterruptedException { + void testAsyncRequestWithOtherException() throws NacosException, ExecutionException, InterruptedException { when(future.get()).thenThrow(new RuntimeException("test")); doAnswer(invocationOnMock -> { ((Runnable) invocationOnMock.getArgument(0)).run(); @@ -240,7 +251,7 @@ public void testAsyncRequestWithOtherException() throws NacosException, Executio } @Test - public void testCloseWithException() { + void testCloseWithException() { doThrow(new RuntimeException("test")).when(payloadStreamObserver).onCompleted(); when(channel.shutdownNow()).thenThrow(new RuntimeException("test")); connection.close(); diff --git a/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcConstantsTest.java b/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcConstantsTest.java index f74adfdd9ee..65140c8335a 100644 --- a/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcConstantsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcConstantsTest.java @@ -16,16 +16,16 @@ package com.alibaba.nacos.common.remote.client.grpc; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class GrpcConstantsTest { +class GrpcConstantsTest { @Test - public void testGetRpcParams() { + void testGetRpcParams() { Class clazz = GrpcConstants.class; Field[] declaredFields = clazz.getDeclaredFields(); int i = 0; diff --git a/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcSdkClientTest.java b/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcSdkClientTest.java index 30b812ba862..ea875b7b751 100644 --- a/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcSdkClientTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcSdkClientTest.java @@ -18,20 +18,19 @@ import com.alibaba.nacos.api.ability.constant.AbilityMode; import com.alibaba.nacos.api.exception.NacosException; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import java.util.Collections; -import java.util.Properties; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class GrpcSdkClientTest { +class GrpcSdkClientTest { GrpcSdkClient grpcSdkClient; - @After - public void tearDown() throws NacosException { + @AfterEach + void tearDown() throws NacosException { System.clearProperty(GrpcConstants.NACOS_SERVER_GRPC_PORT_OFFSET_KEY); if (grpcSdkClient != null) { grpcSdkClient.shutdown(); @@ -39,26 +38,26 @@ public void tearDown() throws NacosException { } @Test - public void testAbilityMode() { + void testAbilityMode() { grpcSdkClient = new GrpcSdkClient("test"); assertEquals(AbilityMode.SDK_CLIENT, grpcSdkClient.abilityMode()); } @Test - public void testRpcPortOffsetDefault() { - grpcSdkClient = new GrpcSdkClient(new Properties()); + void testRpcPortOffsetDefault() { + grpcSdkClient = new GrpcSdkClient("test"); assertEquals(1000, grpcSdkClient.rpcPortOffset()); } @Test - public void testRpcPortOffsetFromSystemProperty() { + void testRpcPortOffsetFromSystemProperty() { System.setProperty(GrpcConstants.NACOS_SERVER_GRPC_PORT_OFFSET_KEY, "10000"); grpcSdkClient = new GrpcSdkClient("test", 8, 8, Collections.emptyMap()); assertEquals(10000, grpcSdkClient.rpcPortOffset()); } @Test - public void testGrpcClientByConfig() { + void testGrpcClientByConfig() { GrpcClientConfig config = DefaultGrpcClientConfig.newBuilder().setName("test111").build(); grpcSdkClient = new GrpcSdkClient(config); assertEquals("test111", grpcSdkClient.getName()); diff --git a/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcUtilsTest.java index 37560eeb8c1..7e18107641b 100644 --- a/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcUtilsTest.java @@ -25,23 +25,24 @@ import com.alibaba.nacos.api.remote.request.RequestMeta; import com.alibaba.nacos.common.remote.PayloadRegistry; import com.alibaba.nacos.common.remote.exception.RemoteException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.HashMap; -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.Mockito.mock; import static org.mockito.Mockito.when; -public class GrpcUtilsTest { +class GrpcUtilsTest { private ServiceQueryRequest request; private ClientConfigMetricResponse response; - @Before - public void setup() { + @BeforeEach + void setup() { PayloadRegistry.init(); this.request = createRequest(); this.response = createResponse(); @@ -73,7 +74,7 @@ private ServiceQueryRequest createRequest() { } @Test - public void testConvertRequest() { + void testConvertRequest() { Payload convert = GrpcUtils.convert(request); assertEquals(request.getClass().getSimpleName(), convert.getMetadata().getType()); assertEquals("v1", convert.getMetadata().getHeadersMap().get("h1")); @@ -82,7 +83,7 @@ public void testConvertRequest() { } @Test - public void testConvertRequestWithMeta() { + void testConvertRequestWithMeta() { RequestMeta meta = new RequestMeta(); Payload convert = GrpcUtils.convert(request, meta); assertEquals(request.getClass().getSimpleName(), convert.getMetadata().getType()); @@ -92,32 +93,34 @@ public void testConvertRequestWithMeta() { } @Test - public void testConvertResponse() { + void testConvertResponse() { Payload convert = GrpcUtils.convert(response); assertEquals(response.getClass().getSimpleName(), convert.getMetadata().getType()); } @Test - public void testParse() { + void testParse() { Payload requestPayload = GrpcUtils.convert(request); - + ServiceQueryRequest request = (ServiceQueryRequest) GrpcUtils.parse(requestPayload); assertEquals(this.request.getHeaders(), request.getHeaders()); assertEquals(this.request.getCluster(), request.getCluster()); assertEquals(this.request.isHealthyOnly(), request.isHealthyOnly()); assertEquals(this.request.getNamespace(), request.getNamespace()); - + Payload responsePayload = GrpcUtils.convert(response); ClientConfigMetricResponse response = (ClientConfigMetricResponse) GrpcUtils.parse(responsePayload); assertEquals(this.response.getMetrics(), response.getMetrics()); } - @Test(expected = RemoteException.class) - public void testParseNullType() { - Payload mockPayload = mock(Payload.class); - Metadata mockMetadata = mock(Metadata.class); - when(mockPayload.getMetadata()).thenReturn(mockMetadata); - GrpcUtils.parse(mockPayload); + @Test + void testParseNullType() { + assertThrows(RemoteException.class, () -> { + Payload mockPayload = mock(Payload.class); + Metadata mockMetadata = mock(Metadata.class); + when(mockPayload.getMetadata()).thenReturn(mockMetadata); + GrpcUtils.parse(mockPayload); + }); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/remote/exception/RemoteExceptionTest.java b/common/src/test/java/com/alibaba/nacos/common/remote/exception/RemoteExceptionTest.java index 138a28cea66..676a1c669c0 100644 --- a/common/src/test/java/com/alibaba/nacos/common/remote/exception/RemoteExceptionTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/remote/exception/RemoteExceptionTest.java @@ -16,15 +16,15 @@ package com.alibaba.nacos.common.remote.exception; -import org.junit.Test; +import org.junit.jupiter.api.Test; -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; -public class RemoteExceptionTest { +class RemoteExceptionTest { @Test - public void testConnectionAlreadyClosedException() { + void testConnectionAlreadyClosedException() { ConnectionAlreadyClosedException exception = new ConnectionAlreadyClosedException("test message"); assertEquals(600, exception.getErrCode()); @@ -45,7 +45,7 @@ public void testConnectionAlreadyClosedException() { } @Test - public void testConnectionBusyException() { + void testConnectionBusyException() { String msg = "Connection is busy"; ConnectionBusyException exception = new ConnectionBusyException(msg); diff --git a/common/src/test/java/com/alibaba/nacos/common/spi/NacosServiceLoaderTest.java b/common/src/test/java/com/alibaba/nacos/common/spi/NacosServiceLoaderTest.java index fba646bcaf1..7f395e65947 100644 --- a/common/src/test/java/com/alibaba/nacos/common/spi/NacosServiceLoaderTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/spi/NacosServiceLoaderTest.java @@ -16,30 +16,30 @@ package com.alibaba.nacos.common.spi; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import java.util.Collection; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; -public class NacosServiceLoaderTest { +class NacosServiceLoaderTest { - @After - public void tearDown() { + @AfterEach + void tearDown() { SpiTestImpl.newInstanceException = false; } @Test - public void testLoad() { + void testLoad() { Collection actual = NacosServiceLoader.load(SpiTestInterface.class); assertEquals(1, actual.size()); assertEquals(SpiTestImpl.class, actual.iterator().next().getClass()); } @Test - public void newServiceInstances() { + void newServiceInstances() { SpiTestInterface loadInstance = NacosServiceLoader.load(SpiTestInterface.class).iterator().next(); Collection actual = NacosServiceLoader.newServiceInstances(SpiTestInterface.class); assertEquals(1, actual.size()); @@ -48,7 +48,7 @@ public void newServiceInstances() { } @Test - public void newServiceInstancesWithException() { + void newServiceInstancesWithException() { NacosServiceLoader.load(SpiTestInterface.class); SpiTestImpl.newInstanceException = true; try { diff --git a/common/src/test/java/com/alibaba/nacos/common/task/engine/NacosDelayTaskExecuteEngineTest.java b/common/src/test/java/com/alibaba/nacos/common/task/engine/NacosDelayTaskExecuteEngineTest.java index 485645d189d..73a77b16f0b 100644 --- a/common/src/test/java/com/alibaba/nacos/common/task/engine/NacosDelayTaskExecuteEngineTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/task/engine/NacosDelayTaskExecuteEngineTest.java @@ -18,25 +18,25 @@ import com.alibaba.nacos.common.task.AbstractDelayTask; import com.alibaba.nacos.common.task.NacosTaskProcessor; -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.internal.verification.Times; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.concurrent.TimeUnit; -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; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class NacosDelayTaskExecuteEngineTest { +@ExtendWith(MockitoExtension.class) +class NacosDelayTaskExecuteEngineTest { private NacosDelayTaskExecuteEngine nacosDelayTaskExecuteEngine; @@ -48,8 +48,8 @@ public class NacosDelayTaskExecuteEngineTest { private AbstractDelayTask abstractTask; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { nacosDelayTaskExecuteEngine = new NacosDelayTaskExecuteEngine(NacosDelayTaskExecuteEngineTest.class.getName()); nacosDelayTaskExecuteEngine.setDefaultTaskProcessor(taskProcessor); abstractTask = new AbstractDelayTask() { @@ -59,13 +59,13 @@ public void merge(AbstractDelayTask task) { }; } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { nacosDelayTaskExecuteEngine.shutdown(); } @Test - public void testSize() { + void testSize() { assertEquals(0, nacosDelayTaskExecuteEngine.size()); nacosDelayTaskExecuteEngine.addTask("test", abstractTask); assertEquals(1, nacosDelayTaskExecuteEngine.size()); @@ -74,7 +74,7 @@ public void testSize() { } @Test - public void testIsEmpty() { + void testIsEmpty() { assertTrue(nacosDelayTaskExecuteEngine.isEmpty()); nacosDelayTaskExecuteEngine.addTask("test", abstractTask); assertFalse(nacosDelayTaskExecuteEngine.isEmpty()); @@ -83,7 +83,7 @@ public void testIsEmpty() { } @Test - public void testAddProcessor() throws InterruptedException { + void testAddProcessor() throws InterruptedException { when(testTaskProcessor.process(abstractTask)).thenReturn(true); nacosDelayTaskExecuteEngine.addProcessor("test", testTaskProcessor); nacosDelayTaskExecuteEngine.addTask("test", abstractTask); @@ -94,7 +94,7 @@ public void testAddProcessor() throws InterruptedException { } @Test - public void testRemoveProcessor() throws InterruptedException { + void testRemoveProcessor() throws InterruptedException { when(taskProcessor.process(abstractTask)).thenReturn(true); nacosDelayTaskExecuteEngine.addProcessor("test", testTaskProcessor); nacosDelayTaskExecuteEngine.removeProcessor("test"); @@ -105,7 +105,7 @@ public void testRemoveProcessor() throws InterruptedException { } @Test - public void testRetryTaskAfterFail() throws InterruptedException { + void testRetryTaskAfterFail() throws InterruptedException { when(taskProcessor.process(abstractTask)).thenReturn(false, true); nacosDelayTaskExecuteEngine.addTask("test", abstractTask); TimeUnit.MILLISECONDS.sleep(300); @@ -113,7 +113,7 @@ public void testRetryTaskAfterFail() throws InterruptedException { } @Test - public void testProcessorWithException() throws InterruptedException { + void testProcessorWithException() throws InterruptedException { when(taskProcessor.process(abstractTask)).thenThrow(new RuntimeException("test")); nacosDelayTaskExecuteEngine.addProcessor("test", testTaskProcessor); nacosDelayTaskExecuteEngine.removeProcessor("test"); @@ -123,7 +123,7 @@ public void testProcessorWithException() throws InterruptedException { } @Test - public void testTaskShouldNotExecute() throws InterruptedException { + void testTaskShouldNotExecute() throws InterruptedException { nacosDelayTaskExecuteEngine.addProcessor("test", testTaskProcessor); nacosDelayTaskExecuteEngine.addTask("test", abstractTask); abstractTask.setTaskInterval(10000L); @@ -134,7 +134,7 @@ public void testTaskShouldNotExecute() throws InterruptedException { } @Test - public void testTaskMerge() { + void testTaskMerge() { nacosDelayTaskExecuteEngine.addProcessor("test", testTaskProcessor); nacosDelayTaskExecuteEngine.addTask("test", abstractTask); nacosDelayTaskExecuteEngine.addTask("test", new AbstractDelayTask() { diff --git a/common/src/test/java/com/alibaba/nacos/common/task/engine/NacosExecuteTaskExecuteEngineTest.java b/common/src/test/java/com/alibaba/nacos/common/task/engine/NacosExecuteTaskExecuteEngineTest.java index 43a926b57e3..8855390820c 100644 --- a/common/src/test/java/com/alibaba/nacos/common/task/engine/NacosExecuteTaskExecuteEngineTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/task/engine/NacosExecuteTaskExecuteEngineTest.java @@ -19,47 +19,48 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.common.task.AbstractExecuteTask; import com.alibaba.nacos.common.task.NacosTaskProcessor; -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.util.concurrent.TimeUnit; -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.verify; -@RunWith(MockitoJUnitRunner.class) -public class NacosExecuteTaskExecuteEngineTest { - - private NacosExecuteTaskExecuteEngine executeTaskExecuteEngine; +@ExtendWith(MockitoExtension.class) +class NacosExecuteTaskExecuteEngineTest { @Mock NacosTaskProcessor taskProcessor; String cachedProcessor; - @Before - public void setUp() { + private NacosExecuteTaskExecuteEngine executeTaskExecuteEngine; + + @Mock + private AbstractExecuteTask task; + + @BeforeEach + void setUp() { cachedProcessor = System.getProperty("nacos.common.processors"); System.setProperty("nacos.common.processors", "1"); executeTaskExecuteEngine = new NacosExecuteTaskExecuteEngine("TEST", null); } - @After - public void tearDown() throws NacosException { + @AfterEach + void tearDown() throws NacosException { System.setProperty("nacos.common.processors", null == cachedProcessor ? "" : cachedProcessor); executeTaskExecuteEngine.shutdown(); } - @Mock - private AbstractExecuteTask task; - @Test - public void testAddTask() throws InterruptedException { + void testAddTask() throws InterruptedException { executeTaskExecuteEngine.addTask("test", task); TimeUnit.SECONDS.sleep(1); verify(task).run(); @@ -68,7 +69,7 @@ public void testAddTask() throws InterruptedException { } @Test - public void testAddTaskByProcessor() throws InterruptedException { + void testAddTaskByProcessor() throws InterruptedException { executeTaskExecuteEngine.addProcessor("test", taskProcessor); executeTaskExecuteEngine.addTask("test", task); verify(taskProcessor).process(task); @@ -76,18 +77,22 @@ public void testAddTaskByProcessor() throws InterruptedException { assertEquals(0, executeTaskExecuteEngine.size()); } - @Test(expected = UnsupportedOperationException.class) - public void testRemoveTask() { - executeTaskExecuteEngine.removeTask(task); + @Test + void testRemoveTask() { + assertThrows(UnsupportedOperationException.class, () -> { + executeTaskExecuteEngine.removeTask(task); + }); } - @Test(expected = UnsupportedOperationException.class) - public void testGetAllTaskKeys() { - executeTaskExecuteEngine.getAllTaskKeys(); + @Test + void testGetAllTaskKeys() { + assertThrows(UnsupportedOperationException.class, () -> { + executeTaskExecuteEngine.getAllTaskKeys(); + }); } @Test - public void testWorkersStatus() { + void testWorkersStatus() { assertEquals("TEST_0%1, pending tasks: 0\n", executeTaskExecuteEngine.workersStatus()); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/tls/SelfHostnameVerifierTest.java b/common/src/test/java/com/alibaba/nacos/common/tls/SelfHostnameVerifierTest.java index c08fe7d71c0..4242eee67c9 100644 --- a/common/src/test/java/com/alibaba/nacos/common/tls/SelfHostnameVerifierTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/tls/SelfHostnameVerifierTest.java @@ -16,16 +16,17 @@ package com.alibaba.nacos.common.tls; -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 javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; +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.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -33,8 +34,9 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -@RunWith(MockitoJUnitRunner.class) -public class SelfHostnameVerifierTest { +@ExtendWith(MockitoExtension.class) +class SelfHostnameVerifierTest { + @Mock HostnameVerifier hostnameVerifier; @@ -43,22 +45,22 @@ public class SelfHostnameVerifierTest { SelfHostnameVerifier selfHostnameVerifier; - @Before - public void setUp() { + @BeforeEach + void setUp() { selfHostnameVerifier = new SelfHostnameVerifier(hostnameVerifier); doReturn(false).when(hostnameVerifier).verify(anyString(), eq(sslSession)); } @Test - public void testVerify() { - Assert.assertTrue(selfHostnameVerifier.verify("localhost", sslSession)); - Assert.assertTrue(selfHostnameVerifier.verify("127.0.0.1", sslSession)); - Assert.assertTrue(selfHostnameVerifier.verify("10.10.10.10", sslSession)); + void testVerify() { + assertTrue(selfHostnameVerifier.verify("localhost", sslSession)); + assertTrue(selfHostnameVerifier.verify("127.0.0.1", sslSession)); + assertTrue(selfHostnameVerifier.verify("10.10.10.10", sslSession)); // hit cache - Assert.assertTrue(selfHostnameVerifier.verify("10.10.10.10", sslSession)); + assertTrue(selfHostnameVerifier.verify("10.10.10.10", sslSession)); - Assert.assertFalse(selfHostnameVerifier.verify("", sslSession)); - Assert.assertFalse(selfHostnameVerifier.verify(null, sslSession)); + assertFalse(selfHostnameVerifier.verify("", sslSession)); + assertFalse(selfHostnameVerifier.verify(null, sslSession)); verify(hostnameVerifier, times(2)).verify(any(), eq(sslSession)); } } \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/tls/SelfTrustManagerTest.java b/common/src/test/java/com/alibaba/nacos/common/tls/SelfTrustManagerTest.java index fa18a635d83..3c3b4e81650 100644 --- a/common/src/test/java/com/alibaba/nacos/common/tls/SelfTrustManagerTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/tls/SelfTrustManagerTest.java @@ -16,9 +16,9 @@ package com.alibaba.nacos.common.tls; -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 javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; @@ -26,24 +26,24 @@ import java.security.cert.CertificateException; import java.security.cert.X509Certificate; -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.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; -public class SelfTrustManagerTest { +class SelfTrustManagerTest { - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { } @Test - public void testTrustManagerSuccess() throws CertificateException { + void testTrustManagerSuccess() throws CertificateException { URL url = SelfTrustManagerTest.class.getClassLoader().getResource("test-tls-cert.pem"); String path = url.getPath(); TrustManager[] actual = SelfTrustManager.trustManager(true, path); @@ -59,7 +59,7 @@ public void testTrustManagerSuccess() throws CertificateException { } @Test - public void testTrustManagerNonExist() throws CertificateException { + void testTrustManagerNonExist() throws CertificateException { TrustManager[] actual = SelfTrustManager.trustManager(true, "non-exist-cert.pem"); assertNotNull(actual); assertEquals(1, actual.length); diff --git a/common/src/test/java/com/alibaba/nacos/common/tls/TlsFileWatcherTest.java b/common/src/test/java/com/alibaba/nacos/common/tls/TlsFileWatcherTest.java index f974d955c80..2425aeb959d 100644 --- a/common/src/test/java/com/alibaba/nacos/common/tls/TlsFileWatcherTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/tls/TlsFileWatcherTest.java @@ -16,14 +16,15 @@ package com.alibaba.nacos.common.tls; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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 org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.mockito.stubbing.Answer; import java.io.File; @@ -35,14 +36,19 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +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.ArgumentMatchers.anyLong; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -@RunWith(MockitoJUnitRunner.class) -public class TlsFileWatcherTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class TlsFileWatcherTest { static Field watchFilesMapField; @@ -57,23 +63,23 @@ public class TlsFileWatcherTest { @Mock ScheduledExecutorService executorService; - @BeforeClass - public static void setUpBeforeClass() throws NoSuchFieldException, IllegalAccessException { + @BeforeAll + static void setUpBeforeClass() throws NoSuchFieldException, IllegalAccessException { watchFilesMapField = TlsFileWatcher.getInstance().getClass().getDeclaredField("watchFilesMap"); watchFilesMapField.setAccessible(true); Field modifiersField1 = Field.class.getDeclaredField("modifiers"); modifiersField1.setAccessible(true); modifiersField1.setInt(watchFilesMapField, watchFilesMapField.getModifiers() & ~Modifier.FINAL); - + fileMd5MapField = TlsFileWatcher.getInstance().getClass().getDeclaredField("fileMd5Map"); fileMd5MapField.setAccessible(true); - + serviceField = TlsFileWatcher.getInstance().getClass().getDeclaredField("service"); serviceField.setAccessible(true); Field modifiersField2 = Field.class.getDeclaredField("modifiers"); modifiersField2.setAccessible(true); modifiersField2.setInt(watchFilesMapField, watchFilesMapField.getModifiers() & ~Modifier.FINAL); - + startedField = TlsFileWatcher.getInstance().getClass().getDeclaredField("started"); startedField.setAccessible(true); Field modifiersField3 = Field.class.getDeclaredField("modifiers"); @@ -81,8 +87,8 @@ public static void setUpBeforeClass() throws NoSuchFieldException, IllegalAccess modifiersField3.setInt(watchFilesMapField, watchFilesMapField.getModifiers() & ~Modifier.FINAL); } - @Before - public void setUp() throws IOException, IllegalAccessException { + @BeforeEach + void setUp() throws IOException, IllegalAccessException { tempFile = new File("test.txt"); tempFile.createNewFile(); serviceField.set(TlsFileWatcher.getInstance(), executorService); @@ -95,86 +101,74 @@ public void setUp() throws IOException, IllegalAccessException { doAnswer(answer).when(executorService).scheduleAtFixedRate(any(), anyLong(), anyLong(), any()); } - @After - public void tearDown() throws IllegalAccessException { + @AfterEach + void tearDown() throws IllegalAccessException { ((Map) watchFilesMapField.get(TlsFileWatcher.getInstance())).clear(); ((Map) fileMd5MapField.get(TlsFileWatcher.getInstance())).clear(); tempFile.deleteOnExit(); } @Test - public void testAddFileChangeListener1() throws IOException, IllegalAccessException { - TlsFileWatcher.getInstance().addFileChangeListener( - filePath -> { }, - "not/exist/path" - ); - - Assert.assertTrue(((Map) watchFilesMapField.get(TlsFileWatcher.getInstance())).isEmpty()); - Assert.assertTrue(((Map) fileMd5MapField.get(TlsFileWatcher.getInstance())).isEmpty()); + void testAddFileChangeListener1() throws IOException, IllegalAccessException { + TlsFileWatcher.getInstance().addFileChangeListener(filePath -> { + }, "not/exist/path"); + + assertTrue(((Map) watchFilesMapField.get(TlsFileWatcher.getInstance())).isEmpty()); + assertTrue(((Map) fileMd5MapField.get(TlsFileWatcher.getInstance())).isEmpty()); } @Test - public void testAddFileChangeListener2() throws IOException, IllegalAccessException { - TlsFileWatcher.getInstance().addFileChangeListener( - filePath -> { }, - (String) null - ); + void testAddFileChangeListener2() throws IOException, IllegalAccessException { + TlsFileWatcher.getInstance().addFileChangeListener(filePath -> { + }, (String) null); - Assert.assertTrue(((Map) watchFilesMapField.get(TlsFileWatcher.getInstance())).isEmpty()); - Assert.assertTrue(((Map) fileMd5MapField.get(TlsFileWatcher.getInstance())).isEmpty()); + assertTrue(((Map) watchFilesMapField.get(TlsFileWatcher.getInstance())).isEmpty()); + assertTrue(((Map) fileMd5MapField.get(TlsFileWatcher.getInstance())).isEmpty()); } @Test - public void testAddFileChangeListener3() throws IOException, IllegalAccessException { - TlsFileWatcher.getInstance().addFileChangeListener( - filePath -> { }, - tempFile.getPath() - ); + void testAddFileChangeListener3() throws IOException, IllegalAccessException { + TlsFileWatcher.getInstance().addFileChangeListener(filePath -> { + }, tempFile.getPath()); - Assert.assertEquals(1, ((Map) watchFilesMapField.get(TlsFileWatcher.getInstance())).size()); - Assert.assertEquals(1, ((Map) fileMd5MapField.get(TlsFileWatcher.getInstance())).size()); + assertEquals(1, ((Map) watchFilesMapField.get(TlsFileWatcher.getInstance())).size()); + assertEquals(1, ((Map) fileMd5MapField.get(TlsFileWatcher.getInstance())).size()); } @Test - public void testStartGivenTlsFileNotChangeThenNoNotify() throws IllegalAccessException, InterruptedException, IOException { + void testStartGivenTlsFileNotChangeThenNoNotify() throws IllegalAccessException, InterruptedException, IOException { // given AtomicBoolean notified = new AtomicBoolean(false); - TlsFileWatcher.getInstance().addFileChangeListener( - filePath -> notified.set(true), - tempFile.getPath() - ); + TlsFileWatcher.getInstance().addFileChangeListener(filePath -> notified.set(true), tempFile.getPath()); // when TlsFileWatcher.getInstance().start(); // then - Assert.assertFalse(notified.get()); + assertFalse(notified.get()); } @Test - public void testStartGivenTlsFileChangeThenNotifyTheChangeFilePath() throws IllegalAccessException, IOException { + void testStartGivenTlsFileChangeThenNotifyTheChangeFilePath() throws IllegalAccessException, IOException { // given AtomicBoolean notified = new AtomicBoolean(false); AtomicReference changedFilePath = new AtomicReference<>(); - TlsFileWatcher.getInstance().addFileChangeListener( - filePath -> { - notified.set(true); - changedFilePath.set(filePath); - }, - tempFile.getPath() - ); + TlsFileWatcher.getInstance().addFileChangeListener(filePath -> { + notified.set(true); + changedFilePath.set(filePath); + }, tempFile.getPath()); ((Map) fileMd5MapField.get(TlsFileWatcher.getInstance())).put("test.txt", ""); - + // when TlsFileWatcher.getInstance().start(); // then - Assert.assertTrue(notified.get()); - Assert.assertEquals("test.txt", changedFilePath.get()); + assertTrue(notified.get()); + assertEquals("test.txt", changedFilePath.get()); } @Test - public void testStartGivenTaskIsAlreadyRunThenNotRunAgain() { + void testStartGivenTaskIsAlreadyRunThenNotRunAgain() { TlsFileWatcher.getInstance().start(); TlsFileWatcher.getInstance().start(); diff --git a/common/src/test/java/com/alibaba/nacos/common/tls/TlsHelperTest.java b/common/src/test/java/com/alibaba/nacos/common/tls/TlsHelperTest.java index 211f170c713..e2980e8dd39 100644 --- a/common/src/test/java/com/alibaba/nacos/common/tls/TlsHelperTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/tls/TlsHelperTest.java @@ -16,18 +16,18 @@ package com.alibaba.nacos.common.tls; -import org.junit.Test; +import org.junit.jupiter.api.Test; import javax.net.ssl.SSLContext; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; -public class TlsHelperTest { +class TlsHelperTest { @Test - public void testBuildSslContext() throws KeyManagementException, NoSuchAlgorithmException { + void testBuildSslContext() throws KeyManagementException, NoSuchAlgorithmException { SSLContext actual = TlsHelper.buildSslContext(true); assertNotNull(actual); } diff --git a/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/HealthStateChangeTraceEventTest.java b/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/HealthStateChangeTraceEventTest.java index a9d6d9e2e63..36c7d8d3861 100644 --- a/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/HealthStateChangeTraceEventTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/HealthStateChangeTraceEventTest.java @@ -17,17 +17,17 @@ package com.alibaba.nacos.common.trace.event.naming; import com.alibaba.nacos.common.trace.HealthCheckType; -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.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; -public class HealthStateChangeTraceEventTest extends NamingTraceEventTest { +class HealthStateChangeTraceEventTest extends NamingTraceEventTest { @Test - public void testHealthStateChangeTraceEventForClientBeat() { - HealthStateChangeTraceEvent healthStateChangeTraceEvent = new HealthStateChangeTraceEvent(TIME, NAMESPACE_ID, - GROUP_NAME, SERVICE_NAME, IP, PORT, false, "client_beat"); + void testHealthStateChangeTraceEventForClientBeat() { + HealthStateChangeTraceEvent healthStateChangeTraceEvent = new HealthStateChangeTraceEvent(TIME, NAMESPACE_ID, GROUP_NAME, + SERVICE_NAME, IP, PORT, false, "client_beat"); assertBasicInfo(healthStateChangeTraceEvent); assertHealthChangeInfo(healthStateChangeTraceEvent); assertEquals(HealthCheckType.CLIENT_BEAT, healthStateChangeTraceEvent.getHealthCheckType()); @@ -35,9 +35,9 @@ public void testHealthStateChangeTraceEventForClientBeat() { } @Test - public void testHealthStateChangeTraceEventForTcp() { - HealthStateChangeTraceEvent healthStateChangeTraceEvent = new HealthStateChangeTraceEvent(TIME, NAMESPACE_ID, - GROUP_NAME, SERVICE_NAME, IP, PORT, false, "tcp:unable2connect:"); + void testHealthStateChangeTraceEventForTcp() { + HealthStateChangeTraceEvent healthStateChangeTraceEvent = new HealthStateChangeTraceEvent(TIME, NAMESPACE_ID, GROUP_NAME, + SERVICE_NAME, IP, PORT, false, "tcp:unable2connect:"); assertBasicInfo(healthStateChangeTraceEvent); assertHealthChangeInfo(healthStateChangeTraceEvent); assertEquals(HealthCheckType.TCP_SUPER_SENSE, healthStateChangeTraceEvent.getHealthCheckType()); @@ -45,9 +45,9 @@ public void testHealthStateChangeTraceEventForTcp() { } @Test - public void testHealthStateChangeTraceEventForHttp() { - HealthStateChangeTraceEvent healthStateChangeTraceEvent = new HealthStateChangeTraceEvent(TIME, NAMESPACE_ID, - GROUP_NAME, SERVICE_NAME, IP, PORT, false, "http:error:"); + void testHealthStateChangeTraceEventForHttp() { + HealthStateChangeTraceEvent healthStateChangeTraceEvent = new HealthStateChangeTraceEvent(TIME, NAMESPACE_ID, GROUP_NAME, + SERVICE_NAME, IP, PORT, false, "http:error:"); assertBasicInfo(healthStateChangeTraceEvent); assertHealthChangeInfo(healthStateChangeTraceEvent); assertEquals(HealthCheckType.HTTP_HEALTH_CHECK, healthStateChangeTraceEvent.getHealthCheckType()); @@ -55,9 +55,9 @@ public void testHealthStateChangeTraceEventForHttp() { } @Test - public void testHealthStateChangeTraceEventForMysql() { - HealthStateChangeTraceEvent healthStateChangeTraceEvent = new HealthStateChangeTraceEvent(TIME, NAMESPACE_ID, - GROUP_NAME, SERVICE_NAME, IP, PORT, false, "mysql:timeout:"); + void testHealthStateChangeTraceEventForMysql() { + HealthStateChangeTraceEvent healthStateChangeTraceEvent = new HealthStateChangeTraceEvent(TIME, NAMESPACE_ID, GROUP_NAME, + SERVICE_NAME, IP, PORT, false, "mysql:timeout:"); assertBasicInfo(healthStateChangeTraceEvent); assertHealthChangeInfo(healthStateChangeTraceEvent); assertEquals(HealthCheckType.MYSQL_HEALTH_CHECK, healthStateChangeTraceEvent.getHealthCheckType()); diff --git a/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/InstanceTraceEventTest.java b/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/InstanceTraceEventTest.java index 6123a8aea83..f72b3058fb3 100644 --- a/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/InstanceTraceEventTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/InstanceTraceEventTest.java @@ -17,18 +17,18 @@ package com.alibaba.nacos.common.trace.event.naming; import com.alibaba.nacos.common.trace.DeregisterInstanceReason; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashMap; 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 InstanceTraceEventTest extends NamingTraceEventTest { +class InstanceTraceEventTest extends NamingTraceEventTest { @Test - public void testRegisterInstanceTraceEvent() { + void testRegisterInstanceTraceEvent() { RegisterInstanceTraceEvent registerInstanceTraceEvent = new RegisterInstanceTraceEvent(TIME, CLIENT_IP, true, NAMESPACE_ID, GROUP_NAME, SERVICE_NAME, IP, PORT); assertBasicInfo(registerInstanceTraceEvent); @@ -41,9 +41,9 @@ public void testRegisterInstanceTraceEvent() { } @Test - public void testDeregisterInstanceTraceEvent() { - DeregisterInstanceTraceEvent deregisterInstanceTraceEvent = new DeregisterInstanceTraceEvent(TIME, CLIENT_IP, - true, DeregisterInstanceReason.NATIVE_DISCONNECTED, NAMESPACE_ID, GROUP_NAME, SERVICE_NAME, IP, PORT); + void testDeregisterInstanceTraceEvent() { + DeregisterInstanceTraceEvent deregisterInstanceTraceEvent = new DeregisterInstanceTraceEvent(TIME, CLIENT_IP, true, + DeregisterInstanceReason.NATIVE_DISCONNECTED, NAMESPACE_ID, GROUP_NAME, SERVICE_NAME, IP, PORT); assertBasicInfo(deregisterInstanceTraceEvent); assertEquals("DEREGISTER_INSTANCE_TRACE_EVENT", deregisterInstanceTraceEvent.getType()); assertEquals(CLIENT_IP, deregisterInstanceTraceEvent.getClientIp()); @@ -55,7 +55,7 @@ public void testDeregisterInstanceTraceEvent() { } @Test - public void testUpdateInstanceTraceEvent() { + void testUpdateInstanceTraceEvent() { Map metadata = new HashMap<>(); metadata.put("test1", "testValue"); UpdateInstanceTraceEvent updateInstanceTraceEvent = new UpdateInstanceTraceEvent(TIME, CLIENT_IP, NAMESPACE_ID, diff --git a/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/NamingTraceEventTest.java b/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/NamingTraceEventTest.java index f7d15840d2f..ea25444eddd 100644 --- a/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/NamingTraceEventTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/NamingTraceEventTest.java @@ -16,8 +16,8 @@ package com.alibaba.nacos.common.trace.event.naming; -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 NamingTraceEventTest { diff --git a/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/ServiceTraceEventTest.java b/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/ServiceTraceEventTest.java index 7ab0c2d98cd..02610a62249 100644 --- a/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/ServiceTraceEventTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/ServiceTraceEventTest.java @@ -16,33 +16,33 @@ package com.alibaba.nacos.common.trace.event.naming; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class ServiceTraceEventTest extends NamingTraceEventTest { +class ServiceTraceEventTest extends NamingTraceEventTest { @Test - public void testRegisterInstanceTraceEvent() { - RegisterServiceTraceEvent registerServiceTraceEvent = new RegisterServiceTraceEvent(TIME, NAMESPACE_ID, - GROUP_NAME, SERVICE_NAME); + void testRegisterInstanceTraceEvent() { + RegisterServiceTraceEvent registerServiceTraceEvent = new RegisterServiceTraceEvent(TIME, NAMESPACE_ID, GROUP_NAME, + SERVICE_NAME); assertBasicInfo(registerServiceTraceEvent); assertEquals("REGISTER_SERVICE_TRACE_EVENT", registerServiceTraceEvent.getType()); } @Test - public void testDeregisterInstanceTraceEvent() { - DeregisterServiceTraceEvent deregisterServiceTraceEvent = new DeregisterServiceTraceEvent(TIME, NAMESPACE_ID, - GROUP_NAME, SERVICE_NAME); + void testDeregisterInstanceTraceEvent() { + DeregisterServiceTraceEvent deregisterServiceTraceEvent = new DeregisterServiceTraceEvent(TIME, NAMESPACE_ID, GROUP_NAME, + SERVICE_NAME); assertBasicInfo(deregisterServiceTraceEvent); assertEquals("DEREGISTER_SERVICE_TRACE_EVENT", deregisterServiceTraceEvent.getType()); } @Test - public void testUpdateInstanceTraceEvent() { + void testUpdateInstanceTraceEvent() { Map metadata = new HashMap<>(); metadata.put("test1", "testValue"); UpdateServiceTraceEvent updateServiceTraceEvent = new UpdateServiceTraceEvent(TIME, NAMESPACE_ID, GROUP_NAME, diff --git a/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/SubscribeTraceEventTest.java b/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/SubscribeTraceEventTest.java index 9adfb214c5f..8aecdc957d1 100644 --- a/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/SubscribeTraceEventTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/trace/event/naming/SubscribeTraceEventTest.java @@ -16,23 +16,23 @@ package com.alibaba.nacos.common.trace.event.naming; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class SubscribeTraceEventTest extends NamingTraceEventTest { +class SubscribeTraceEventTest extends NamingTraceEventTest { @Test - public void testRegisterInstanceTraceEvent() { - SubscribeServiceTraceEvent subscribeServiceTraceEvent = new SubscribeServiceTraceEvent(TIME, CLIENT_IP, - NAMESPACE_ID, GROUP_NAME, SERVICE_NAME); + void testRegisterInstanceTraceEvent() { + SubscribeServiceTraceEvent subscribeServiceTraceEvent = new SubscribeServiceTraceEvent(TIME, CLIENT_IP, NAMESPACE_ID, + GROUP_NAME, SERVICE_NAME); assertBasicInfo(subscribeServiceTraceEvent); assertEquals("SUBSCRIBE_SERVICE_TRACE_EVENT", subscribeServiceTraceEvent.getType()); assertEquals(CLIENT_IP, subscribeServiceTraceEvent.getClientIp()); } @Test - public void testDeregisterInstanceTraceEvent() { + void testDeregisterInstanceTraceEvent() { UnsubscribeServiceTraceEvent unsubscribeServiceTraceEvent = new UnsubscribeServiceTraceEvent(TIME, CLIENT_IP, NAMESPACE_ID, GROUP_NAME, SERVICE_NAME); assertBasicInfo(unsubscribeServiceTraceEvent); @@ -41,9 +41,9 @@ public void testDeregisterInstanceTraceEvent() { } @Test - public void testPushServiceTraceEvent() { - PushServiceTraceEvent pushServiceTraceEvent = new PushServiceTraceEvent(TIME, 10, 510, 510, CLIENT_IP, - NAMESPACE_ID, GROUP_NAME, SERVICE_NAME, 100); + void testPushServiceTraceEvent() { + PushServiceTraceEvent pushServiceTraceEvent = new PushServiceTraceEvent(TIME, 10, 510, 510, CLIENT_IP, NAMESPACE_ID, + GROUP_NAME, SERVICE_NAME, 100); assertBasicInfo(pushServiceTraceEvent); assertEquals("PUSH_SERVICE_TRACE_EVENT", pushServiceTraceEvent.getType()); assertEquals(CLIENT_IP, pushServiceTraceEvent.getClientIp()); diff --git a/common/src/test/java/com/alibaba/nacos/common/trace/publisher/TraceEventPublisherFactoryTest.java b/common/src/test/java/com/alibaba/nacos/common/trace/publisher/TraceEventPublisherFactoryTest.java index 2d996eacc76..7a373203092 100644 --- a/common/src/test/java/com/alibaba/nacos/common/trace/publisher/TraceEventPublisherFactoryTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/trace/publisher/TraceEventPublisherFactoryTest.java @@ -18,22 +18,22 @@ import com.alibaba.nacos.common.notify.EventPublisher; import com.alibaba.nacos.common.notify.NotifyCenter; -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.Field; import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class TraceEventPublisherFactoryTest { +class TraceEventPublisherFactoryTest { private Map originalEventPublisherMap; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { originalEventPublisherMap = new HashMap<>(NotifyCenter.getPublisherMap()); NotifyCenter.getPublisherMap().clear(); // Protect other unit test publisher affect this case. @@ -43,15 +43,15 @@ public void setUp() throws Exception { map.clear(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { NotifyCenter.getPublisherMap().clear(); NotifyCenter.getPublisherMap().putAll(originalEventPublisherMap); originalEventPublisherMap = null; } @Test - public void testApply() { + void testApply() { TraceEventPublisherFactory.getInstance().apply(TraceTestEvent.TraceTestEvent1.class, Byte.SIZE); TraceEventPublisherFactory.getInstance().apply(TraceTestEvent.TraceTestEvent2.class, Byte.SIZE); TraceEventPublisherFactory.getInstance().apply(TraceTestEvent.class, Byte.SIZE); @@ -61,7 +61,7 @@ public void testApply() { } @Test - public void testApplyAfterAddEventType() { + void testApplyAfterAddEventType() { TraceEventPublisherFactory.getInstance().addPublisherEvent(TraceTestEvent.class); TraceEventPublisherFactory.getInstance().apply(TraceTestEvent.TraceTestEvent1.class, Byte.SIZE); TraceEventPublisherFactory.getInstance().apply(TraceTestEvent.TraceTestEvent2.class, Byte.SIZE); diff --git a/common/src/test/java/com/alibaba/nacos/common/trace/publisher/TraceEventPublisherTest.java b/common/src/test/java/com/alibaba/nacos/common/trace/publisher/TraceEventPublisherTest.java index 86ab30e1648..4cf991267d9 100644 --- a/common/src/test/java/com/alibaba/nacos/common/trace/publisher/TraceEventPublisherTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/trace/publisher/TraceEventPublisherTest.java @@ -20,22 +20,21 @@ import com.alibaba.nacos.common.notify.listener.SmartSubscriber; import com.alibaba.nacos.common.notify.listener.Subscriber; import com.alibaba.nacos.common.utils.ThreadUtils; -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 static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class TraceEventPublisherTest { +@ExtendWith(MockitoExtension.class) +class TraceEventPublisherTest { @Mock private Subscriber subscriber; @@ -45,19 +44,19 @@ public class TraceEventPublisherTest { private TraceEventPublisher traceEventPublisher; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { traceEventPublisher = new TraceEventPublisher(); traceEventPublisher.init(TraceTestEvent.class, Byte.SIZE); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { traceEventPublisher.shutdown(); } @Test - public void testAddSubscriber() { + void testAddSubscriber() { when(subscriber.subscribeType()).thenReturn(TraceTestEvent.TraceTestEvent1.class); traceEventPublisher.addSubscriber(subscriber); traceEventPublisher.addSubscriber(smartSubscriber, TraceTestEvent.TraceTestEvent2.class); @@ -71,7 +70,7 @@ public void testAddSubscriber() { } @Test - public void testRemoveSubscriber() { + void testRemoveSubscriber() { traceEventPublisher.addSubscriber(subscriber, TraceTestEvent.TraceTestEvent1.class); traceEventPublisher.addSubscriber(smartSubscriber, TraceTestEvent.TraceTestEvent1.class); TraceTestEvent.TraceTestEvent1 traceTestEvent1 = new TraceTestEvent.TraceTestEvent1(); @@ -95,18 +94,18 @@ public void testRemoveSubscriber() { } @Test - public void getStatus() throws NacosException { + void getStatus() throws NacosException { traceEventPublisher.publish(new TraceTestEvent()); traceEventPublisher.publish(new TraceTestEvent.TraceTestEvent1()); traceEventPublisher.publish(new TraceTestEvent.TraceTestEvent2()); String expectedStatus = "Publisher TraceTestEvent : shutdown=false, queue= 3/8 "; - assertThat(traceEventPublisher.getStatus(), is(expectedStatus)); + assertEquals(traceEventPublisher.getStatus(), expectedStatus); traceEventPublisher.addSubscriber(subscriber, TraceTestEvent.TraceTestEvent1.class); ThreadUtils.sleep(2000L); expectedStatus = "Publisher TraceTestEvent : shutdown=false, queue= 0/8 "; - assertThat(traceEventPublisher.getStatus(), is(expectedStatus)); + assertEquals(traceEventPublisher.getStatus(), expectedStatus); traceEventPublisher.shutdown(); expectedStatus = "Publisher TraceTestEvent : shutdown= true, queue= 0/8 "; - assertThat(traceEventPublisher.getStatus(), is(expectedStatus)); + assertEquals(traceEventPublisher.getStatus(), expectedStatus); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/trace/publisher/TraceTestEvent.java b/common/src/test/java/com/alibaba/nacos/common/trace/publisher/TraceTestEvent.java index c239bc2d156..2813c728973 100644 --- a/common/src/test/java/com/alibaba/nacos/common/trace/publisher/TraceTestEvent.java +++ b/common/src/test/java/com/alibaba/nacos/common/trace/publisher/TraceTestEvent.java @@ -19,6 +19,7 @@ import com.alibaba.nacos.common.notify.Event; public class TraceTestEvent extends Event { + private static final long serialVersionUID = 8568231862586636388L; static class TraceTestEvent1 extends TraceTestEvent { diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/ArrayUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/ArrayUtilsTest.java index 48ec56a0a34..d456e1c79d0 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/ArrayUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/ArrayUtilsTest.java @@ -16,37 +16,40 @@ package com.alibaba.nacos.common.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; /** * Test ArrayUtils. + * * @author zzq */ -public class ArrayUtilsTest { +class ArrayUtilsTest { Integer[] nullArr = null; - Integer[] nothingArr = new Integer[]{}; + Integer[] nothingArr = new Integer[] {}; @Test - public void testisEmpty() { - Integer[] arr = new Integer[]{1, 2}; - Assert.assertTrue(ArrayUtils.isEmpty(nullArr)); - Assert.assertTrue(ArrayUtils.isEmpty(nothingArr)); - Assert.assertFalse(ArrayUtils.isEmpty(arr)); + void testisEmpty() { + Integer[] arr = new Integer[] {1, 2}; + assertTrue(ArrayUtils.isEmpty(nullArr)); + assertTrue(ArrayUtils.isEmpty(nothingArr)); + assertFalse(ArrayUtils.isEmpty(arr)); } @Test - public void contains() { - Integer[] arr = new Integer[]{1, 2, 3}; - Integer[] arr1 = new Integer[]{1, 2, 3, null}; - Assert.assertFalse(ArrayUtils.contains(nullArr, "a")); - Assert.assertFalse(ArrayUtils.contains(nullArr, null)); - Assert.assertFalse(ArrayUtils.contains(nothingArr, "b")); - Assert.assertFalse(ArrayUtils.contains(arr, null)); - Assert.assertTrue(ArrayUtils.contains(arr1, null)); - Assert.assertTrue(ArrayUtils.contains(arr, 1)); - Assert.assertFalse(ArrayUtils.contains(arr, "1")); + void contains() { + assertFalse(ArrayUtils.contains(nullArr, "a")); + assertFalse(ArrayUtils.contains(nullArr, null)); + assertFalse(ArrayUtils.contains(nothingArr, "b")); + Integer[] arr = new Integer[] {1, 2, 3}; + assertFalse(ArrayUtils.contains(arr, null)); + Integer[] arr1 = new Integer[] {1, 2, 3, null}; + assertTrue(ArrayUtils.contains(arr1, null)); + assertTrue(ArrayUtils.contains(arr, 1)); + assertFalse(ArrayUtils.contains(arr, "1")); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/ByteUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/ByteUtilsTest.java index 153291d6f8e..ab00c287758 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/ByteUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/ByteUtilsTest.java @@ -17,8 +17,12 @@ package com.alibaba.nacos.common.utils; import com.alibaba.nacos.common.utils.to.User; -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.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * ByteUtils Test. @@ -27,51 +31,51 @@ * @Author: ChenHao26 * @Date: 2022/8/22 10:58 */ -public class ByteUtilsTest { +class ByteUtilsTest { @Test - public void objectToByte() { + void objectToByte() { User user = new User(1, "google"); byte[] bytes = ByteUtils.toBytes(user); - Assert.assertNotNull(bytes); + assertNotNull(bytes); } @Test - public void stringToByte() { + void stringToByte() { byte[] bytes = ByteUtils.toBytes("google"); - Assert.assertNotNull(bytes); + assertNotNull(bytes); } @Test - public void toStringTest() { + void toStringTest() { byte[] bytes = ByteUtils.toBytes("google"); String str = ByteUtils.toString(bytes); - Assert.assertEquals(str, "google"); + assertEquals("google", str); } @Test - public void testForInputNull() { - Assert.assertEquals(0, ByteUtils.toBytes(null).length); - Assert.assertEquals(0, ByteUtils.toBytes((Object) null).length); - Assert.assertEquals("", ByteUtils.toString(null)); + void testForInputNull() { + assertEquals(0, ByteUtils.toBytes(null).length); + assertEquals(0, ByteUtils.toBytes((Object) null).length); + assertEquals("", ByteUtils.toString(null)); } @Test - public void isEmpty() { + void isEmpty() { byte[] bytes = ByteUtils.toBytes(""); - Assert.assertTrue(ByteUtils.isEmpty(bytes)); + assertTrue(ByteUtils.isEmpty(bytes)); byte[] byte2 = new byte[1024]; - Assert.assertFalse(ByteUtils.isEmpty(byte2)); + assertFalse(ByteUtils.isEmpty(byte2)); byte[] byte3 = null; - Assert.assertTrue(ByteUtils.isEmpty(byte3)); + assertTrue(ByteUtils.isEmpty(byte3)); } @Test - public void isNotEmpty() { + void isNotEmpty() { byte[] bytes = ByteUtils.toBytes("google"); - Assert.assertTrue(ByteUtils.isNotEmpty(bytes)); + assertTrue(ByteUtils.isNotEmpty(bytes)); byte[] bytes2 = ByteUtils.toBytes(""); - Assert.assertFalse(ByteUtils.isNotEmpty(bytes2)); + assertFalse(ByteUtils.isNotEmpty(bytes2)); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/ClassUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/ClassUtilsTest.java index b7068dacf4c..31dbcefb0c5 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/ClassUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/ClassUtilsTest.java @@ -17,94 +17,99 @@ package com.alibaba.nacos.common.utils; import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.util.Map; -public class ClassUtilsTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ClassUtilsTest { @Test - public void testFindClassByName1() { + void testFindClassByName1() { Class clazz = ClassUtils.findClassByName("java.lang.Integer"); - Assert.assertEquals("java.lang.Integer", clazz.getName()); + assertEquals("java.lang.Integer", clazz.getName()); } - @Test(expected = NacosRuntimeException.class) - public void testFindClassByName2() { - ClassUtils.findClassByName("not.exist.Class"); + @Test + void testFindClassByName2() { + assertThrows(NacosRuntimeException.class, () -> { + ClassUtils.findClassByName("not.exist.Class"); + }); } @Test - public void testGetName() { + void testGetName() { final String name = "java.lang.Integer"; Integer val = 1; - Assert.assertEquals(name, ClassUtils.getName(val)); - Assert.assertEquals(name, ClassUtils.getName(Integer.class)); + assertEquals(name, ClassUtils.getName(val)); + assertEquals(name, ClassUtils.getName(Integer.class)); - Assert.assertEquals(name, ClassUtils.getCanonicalName(val)); - Assert.assertEquals(name, ClassUtils.getCanonicalName(Integer.class)); + assertEquals(name, ClassUtils.getCanonicalName(val)); + assertEquals(name, ClassUtils.getCanonicalName(Integer.class)); - Assert.assertEquals("Integer", ClassUtils.getSimpleName(val)); - Assert.assertEquals("Integer", ClassUtils.getSimpleName(Integer.class)); + assertEquals("Integer", ClassUtils.getSimpleName(val)); + assertEquals("Integer", ClassUtils.getSimpleName(Integer.class)); } @Test - public void testIsAssignableFrom() { - Assert.assertTrue(ClassUtils.isAssignableFrom(Object.class, Integer.class)); + void testIsAssignableFrom() { + assertTrue(ClassUtils.isAssignableFrom(Object.class, Integer.class)); } @Test - public void testForNameArray() throws ClassNotFoundException { + void testForNameArray() throws ClassNotFoundException { Class clazz = ClassUtils.forName("[Lcom.alibaba.nacos.common.utils.ClassUtilsTest;", null); - Assert.assertEquals("[Lcom.alibaba.nacos.common.utils.ClassUtilsTest;", clazz.getName()); + assertEquals("[Lcom.alibaba.nacos.common.utils.ClassUtilsTest;", clazz.getName()); clazz = ClassUtils.forName("java.lang.String[]", null); - Assert.assertEquals("[Ljava.lang.String;", clazz.getName()); + assertEquals("[Ljava.lang.String;", clazz.getName()); clazz = ClassUtils.forName("[[Ljava.lang.String;", null); - Assert.assertEquals("[[Ljava.lang.String;", clazz.getName()); + assertEquals("[[Ljava.lang.String;", clazz.getName()); } - @Test(expected = ClassNotFoundException.class) - public void testForNameNonExist() throws ClassNotFoundException { - ClassUtils.forName("com.alibaba.nacos.common.NonExistClass", null); + @Test + void testForNameNonExist() throws ClassNotFoundException { + assertThrows(ClassNotFoundException.class, () -> { + ClassUtils.forName("com.alibaba.nacos.common.NonExistClass", null); + }); } @Test - public void testForNameFromPrimitive() throws NoSuchFieldException, IllegalAccessException, ClassNotFoundException { + void testForNameFromPrimitive() throws NoSuchFieldException, IllegalAccessException, ClassNotFoundException { Field field = ClassUtils.class.getDeclaredField("PRIMITIVE_TYPE_NAME_MAP"); field.setAccessible(true); Map> map = (Map>) field.get(null); map.put("Test", ClassUtilsTest.class); - Assert.assertEquals(ClassUtilsTest.class, ClassUtils.forName("Test", null)); + assertEquals(ClassUtilsTest.class, ClassUtils.forName("Test", null)); } @Test - public void testGetDefaultClassLoader() { + void testGetDefaultClassLoader() { ClassLoader cachedClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(null); - Assert.assertNotNull(ClassUtils.getDefaultClassLoader()); + assertNotNull(ClassUtils.getDefaultClassLoader()); } finally { Thread.currentThread().setContextClassLoader(cachedClassLoader); } } @Test - public void testClassPackageAsResourcePath() throws ClassNotFoundException { + void testClassPackageAsResourcePath() throws ClassNotFoundException { Class noPackageClass = ClassUtils.forName("ClassUtilsTestMockClass", null); - Assert.assertEquals("", ClassUtils.classPackageAsResourcePath(null)); - Assert.assertEquals("", ClassUtils.classPackageAsResourcePath(noPackageClass)); - Assert.assertEquals("com/alibaba/nacos/common/utils", - ClassUtils.classPackageAsResourcePath(ClassUtilsTest.class)); + assertEquals("", ClassUtils.classPackageAsResourcePath(null)); + assertEquals("", ClassUtils.classPackageAsResourcePath(noPackageClass)); + assertEquals("com/alibaba/nacos/common/utils", ClassUtils.classPackageAsResourcePath(ClassUtilsTest.class)); } @Test - public void testConvertClassNameAndClassPath() { + void testConvertClassNameAndClassPath() { String name = ClassUtilsTest.class.getName(); - Assert.assertEquals("com/alibaba/nacos/common/utils/ClassUtilsTest", - ClassUtils.convertClassNameToResourcePath(name)); - Assert.assertEquals(name, - ClassUtils.resourcePathToConvertClassName("com/alibaba/nacos/common/utils/ClassUtilsTest")); + assertEquals("com/alibaba/nacos/common/utils/ClassUtilsTest", ClassUtils.convertClassNameToResourcePath(name)); + assertEquals(name, ClassUtils.resourcePathToConvertClassName("com/alibaba/nacos/common/utils/ClassUtilsTest")); } } \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/CollectionUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/CollectionUtilsTest.java index 8531c1c6138..6aea046f3a7 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/CollectionUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/CollectionUtilsTest.java @@ -16,8 +16,7 @@ package com.alibaba.nacos.common.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; @@ -36,277 +35,323 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; +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; + /** * Unit test of CollectionUtil. * * @author sunjifeng */ -public class CollectionUtilsTest { +class CollectionUtilsTest { - @Test(expected = IndexOutOfBoundsException.class) - public void testGetList1() { - CollectionUtils.get(Collections.emptyList(), -1); + @Test + void testGetList1() { + assertThrows(IndexOutOfBoundsException.class, () -> { + CollectionUtils.get(Collections.emptyList(), -1); + }); } - @Test(expected = IndexOutOfBoundsException.class) - public void testGetList2() { - CollectionUtils.get(Collections.emptyList(), 1); + @Test + void testGetList2() { + assertThrows(IndexOutOfBoundsException.class, () -> { + CollectionUtils.get(Collections.emptyList(), 1); + }); } @Test - public void testGetList3() { - Assert.assertEquals("element", CollectionUtils.get(Collections.singletonList("element"), 0)); - Assert.assertEquals("element2", CollectionUtils.get(Arrays.asList("element1", "element2"), 1)); + void testGetList3() { + assertEquals("element", CollectionUtils.get(Collections.singletonList("element"), 0)); + assertEquals("element2", CollectionUtils.get(Arrays.asList("element1", "element2"), 1)); } - @Test(expected = IndexOutOfBoundsException.class) - public void testGetMap1() { - Map map = new HashMap<>(); - map.put("key1", "value1"); - CollectionUtils.get(map, -1); + @Test + void testGetMap1() { + assertThrows(IndexOutOfBoundsException.class, () -> { + Map map = new HashMap<>(); + map.put("key1", "value1"); + CollectionUtils.get(map, -1); + }); } - @Test(expected = IndexOutOfBoundsException.class) - public void testGetMap2() { - Map map = new HashMap<>(); - map.put("key1", "value1"); - CollectionUtils.get(map, -1); - CollectionUtils.get(map, 1); + @Test + void testGetMap2() { + assertThrows(IndexOutOfBoundsException.class, () -> { + Map map = new HashMap<>(); + map.put("key1", "value1"); + CollectionUtils.get(map, -1); + CollectionUtils.get(map, 1); + }); } @Test - public void testGetMap3() { + void testGetMap3() { Map map1 = new LinkedHashMap(1); Map map2 = new LinkedHashMap(2); map1.put("key", "value"); map2.put("key1", "value1"); map2.put("key2", "value2"); Iterator> iter = map1.entrySet().iterator(); - Assert.assertEquals(iter.next(), CollectionUtils.get(map1, 0)); + assertEquals(iter.next(), CollectionUtils.get(map1, 0)); Iterator> iter2 = map2.entrySet().iterator(); iter2.next(); Map.Entry second = iter2.next(); - Assert.assertEquals(second, CollectionUtils.get(map2, 1)); + assertEquals(second, CollectionUtils.get(map2, 1)); } - @Test(expected = IndexOutOfBoundsException.class) - public void testGetArray1() { - CollectionUtils.get(new Object[] {}, -1); + @Test + void testGetArray1() { + assertThrows(IndexOutOfBoundsException.class, () -> { + CollectionUtils.get(new Object[] {}, -1); + }); } - @Test(expected = IndexOutOfBoundsException.class) - public void testGetArray2() { - CollectionUtils.get(new Object[] {}, 0); + @Test + void testGetArray2() { + assertThrows(IndexOutOfBoundsException.class, () -> { + CollectionUtils.get(new Object[] {}, 0); + }); } @Test - public void testGetArray3() { - Assert.assertEquals("1", CollectionUtils.get(new Object[] {"1"}, 0)); - Assert.assertEquals("2", CollectionUtils.get(new Object[] {"1", "2"}, 1)); + void testGetArray3() { + assertEquals("1", CollectionUtils.get(new Object[] {"1"}, 0)); + assertEquals("2", CollectionUtils.get(new Object[] {"1", "2"}, 1)); } - @Test(expected = ArrayIndexOutOfBoundsException.class) - public void testGetArray4() { - CollectionUtils.get(new int[] {}, 0); + @Test + void testGetArray4() { + assertThrows(ArrayIndexOutOfBoundsException.class, () -> { + CollectionUtils.get(new int[] {}, 0); + }); } - @Test(expected = IndexOutOfBoundsException.class) - public void testGetArray5() { - CollectionUtils.get(new int[] {}, -1); + @Test + void testGetArray5() { + assertThrows(IndexOutOfBoundsException.class, () -> { + CollectionUtils.get(new int[] {}, -1); + }); } @Test - public void testGetArray6() { - Assert.assertEquals(1, CollectionUtils.get(new int[] {1, 2}, 0)); - Assert.assertEquals(2, CollectionUtils.get(new int[] {1, 2}, 1)); + void testGetArray6() { + assertEquals(1, CollectionUtils.get(new int[] {1, 2}, 0)); + assertEquals(2, CollectionUtils.get(new int[] {1, 2}, 1)); } - @Test(expected = IndexOutOfBoundsException.class) - public void testGetIterator1() { - CollectionUtils.get(Collections.emptyIterator(), 0); + @Test + void testGetIterator1() { + assertThrows(IndexOutOfBoundsException.class, () -> { + CollectionUtils.get(Collections.emptyIterator(), 0); + }); } - @Test(expected = IndexOutOfBoundsException.class) - public void testGetIterator2() { - CollectionUtils.get(Collections.emptyIterator(), -1); + @Test + void testGetIterator2() { + assertThrows(IndexOutOfBoundsException.class, () -> { + CollectionUtils.get(Collections.emptyIterator(), -1); + }); } @Test - public void testGetIterator3() { - Assert.assertEquals("1", CollectionUtils.get(Collections.singleton("1").iterator(), 0)); - Assert.assertEquals("2", CollectionUtils.get(Arrays.asList("1", "2").iterator(), 1)); + void testGetIterator3() { + assertEquals("1", CollectionUtils.get(Collections.singleton("1").iterator(), 0)); + assertEquals("2", CollectionUtils.get(Arrays.asList("1", "2").iterator(), 1)); } - @Test(expected = IndexOutOfBoundsException.class) - public void testGetCollection1() { - CollectionUtils.get(Collections.emptySet(), 0); + @Test + void testGetCollection1() { + assertThrows(IndexOutOfBoundsException.class, () -> { + CollectionUtils.get(Collections.emptySet(), 0); + }); } - @Test(expected = IndexOutOfBoundsException.class) - public void testGetCollection2() { - CollectionUtils.get(Collections.emptySet(), -1); + @Test + void testGetCollection2() { + assertThrows(IndexOutOfBoundsException.class, () -> { + CollectionUtils.get(Collections.emptySet(), -1); + }); } @Test - public void testGetCollection3() { - Assert.assertEquals("1", CollectionUtils.get(Collections.singleton("1"), 0)); - Assert.assertEquals("2", CollectionUtils.get(CollectionUtils.set("1", "2"), 1)); + void testGetCollection3() { + assertEquals("1", CollectionUtils.get(Collections.singleton("1"), 0)); + assertEquals("2", CollectionUtils.get(CollectionUtils.set("1", "2"), 1)); } - @Test(expected = IndexOutOfBoundsException.class) - public void testGetEnumeration1() { - CollectionUtils.get(asEnumeration(Collections.emptyIterator()), 0); + @Test + void testGetEnumeration1() { + assertThrows(IndexOutOfBoundsException.class, () -> { + CollectionUtils.get(asEnumeration(Collections.emptyIterator()), 0); + }); } - @Test(expected = IndexOutOfBoundsException.class) - public void testGetEnumeration2() { - CollectionUtils.get(asEnumeration(Collections.emptyIterator()), -1); + @Test + void testGetEnumeration2() { + assertThrows(IndexOutOfBoundsException.class, () -> { + CollectionUtils.get(asEnumeration(Collections.emptyIterator()), -1); + }); } @Test - public void testGetEnumeration3() { + void testGetEnumeration3() { Vector vector = new Vector<>(); vector.add("1"); vector.add("2"); - Assert.assertEquals("1", CollectionUtils.get(vector.elements(), 0)); - Assert.assertEquals("2", CollectionUtils.get(vector.elements(), 1)); + assertEquals("1", CollectionUtils.get(vector.elements(), 0)); + assertEquals("2", CollectionUtils.get(vector.elements(), 1)); } - @Test(expected = IllegalArgumentException.class) - public void testGet1() { - CollectionUtils.get(null, 0); + @Test + void testGet1() { + assertThrows(IllegalArgumentException.class, () -> { + CollectionUtils.get(null, 0); + }); } - @Test(expected = IllegalArgumentException.class) - public void testGet2() { - CollectionUtils.get("string", 0); + @Test + void testGet2() { + assertThrows(IllegalArgumentException.class, () -> { + CollectionUtils.get("string", 0); + }); } @Test - public void testSize() { + void testSize() { // collection - Assert.assertEquals(0, CollectionUtils.size(Collections.emptyList())); - Assert.assertEquals(1, CollectionUtils.size(Collections.singletonList(""))); - Assert.assertEquals(10, CollectionUtils.size(IntStream.range(0, 10).boxed().collect(Collectors.toList()))); + assertEquals(0, CollectionUtils.size(Collections.emptyList())); + assertEquals(1, CollectionUtils.size(Collections.singletonList(""))); + assertEquals(10, CollectionUtils.size(IntStream.range(0, 10).boxed().collect(Collectors.toList()))); // map Map map = new HashMap<>(); map.put("key1", "value1"); - Assert.assertEquals(1, CollectionUtils.size(map)); + assertEquals(1, CollectionUtils.size(map)); map.put("key2", "value2"); - Assert.assertEquals(2, CollectionUtils.size(map)); + assertEquals(2, CollectionUtils.size(map)); map.put("key3", "value3"); - Assert.assertEquals(3, CollectionUtils.size(map)); + assertEquals(3, CollectionUtils.size(map)); // array - Assert.assertEquals(1, CollectionUtils.size(new Object[] {"1"})); - Assert.assertEquals(2, CollectionUtils.size(new Object[] {"1", "2"})); - Assert.assertEquals(6, CollectionUtils.size(new Object[] {"1", "2", "3", "4", "5", "6"})); - Assert.assertEquals(1000, CollectionUtils.size(IntStream.range(0, 1000).boxed().toArray())); + assertEquals(1, CollectionUtils.size(new Object[] {"1"})); + assertEquals(2, CollectionUtils.size(new Object[] {"1", "2"})); + assertEquals(6, CollectionUtils.size(new Object[] {"1", "2", "3", "4", "5", "6"})); + assertEquals(1000, CollectionUtils.size(IntStream.range(0, 1000).boxed().toArray())); // primitive array - Assert.assertEquals(1, CollectionUtils.size(new int[] {1})); - Assert.assertEquals(2, CollectionUtils.size(new int[] {1, 2})); - Assert.assertEquals(6, CollectionUtils.size(new int[] {1, 2, 3, 4, 5, 6})); - Assert.assertEquals(1000, CollectionUtils.size(IntStream.range(0, 1000).toArray())); + assertEquals(1, CollectionUtils.size(new int[] {1})); + assertEquals(2, CollectionUtils.size(new int[] {1, 2})); + assertEquals(6, CollectionUtils.size(new int[] {1, 2, 3, 4, 5, 6})); + assertEquals(1000, CollectionUtils.size(IntStream.range(0, 1000).toArray())); // iterator - Assert.assertEquals(1, CollectionUtils.size(Collections.singleton("1").iterator())); - Assert.assertEquals(2, CollectionUtils.size(Arrays.asList("1", "2").iterator())); + assertEquals(1, CollectionUtils.size(Collections.singleton("1").iterator())); + assertEquals(2, CollectionUtils.size(Arrays.asList("1", "2").iterator())); // enumeration - Assert.assertEquals(0, CollectionUtils.size(asEnumeration(Collections.emptyIterator()))); - Assert.assertEquals(1, CollectionUtils.size(asEnumeration(Collections.singleton("").iterator()))); + assertEquals(0, CollectionUtils.size(asEnumeration(Collections.emptyIterator()))); + assertEquals(1, CollectionUtils.size(asEnumeration(Collections.singleton("").iterator()))); } - @Test(expected = IllegalArgumentException.class) - public void testSize1() { - CollectionUtils.size(null); + @Test + void testSize1() { + assertThrows(IllegalArgumentException.class, () -> { + CollectionUtils.size(null); + }); } - @Test(expected = IllegalArgumentException.class) - public void testSize2() { - CollectionUtils.size("string"); + @Test + void testSize2() { + assertThrows(IllegalArgumentException.class, () -> { + CollectionUtils.size("string"); + }); } @Test - public void testSizeIsEmpty() { + void testSizeIsEmpty() { // collection - Assert.assertTrue(CollectionUtils.sizeIsEmpty(Collections.emptyList())); - Assert.assertFalse(CollectionUtils.sizeIsEmpty(Collections.singletonList(""))); + assertTrue(CollectionUtils.sizeIsEmpty(Collections.emptyList())); + assertFalse(CollectionUtils.sizeIsEmpty(Collections.singletonList(""))); // map Map map = new HashMap<>(); map.put("key1", "value1"); map.put("key2", "value2"); - Assert.assertTrue(CollectionUtils.sizeIsEmpty(Collections.emptyMap())); - Assert.assertFalse(CollectionUtils.sizeIsEmpty(map)); + assertTrue(CollectionUtils.sizeIsEmpty(Collections.emptyMap())); + assertFalse(CollectionUtils.sizeIsEmpty(map)); // array - Assert.assertTrue(CollectionUtils.sizeIsEmpty(new Object[] {})); - Assert.assertFalse(CollectionUtils.sizeIsEmpty(new Object[] {"1", "2"})); + assertTrue(CollectionUtils.sizeIsEmpty(new Object[] {})); + assertFalse(CollectionUtils.sizeIsEmpty(new Object[] {"1", "2"})); // primitive array - Assert.assertTrue(CollectionUtils.sizeIsEmpty(new int[] {})); - Assert.assertFalse(CollectionUtils.sizeIsEmpty(new int[] {1, 2})); + assertTrue(CollectionUtils.sizeIsEmpty(new int[] {})); + assertFalse(CollectionUtils.sizeIsEmpty(new int[] {1, 2})); // iterator - Assert.assertTrue(CollectionUtils.sizeIsEmpty(Collections.emptyIterator())); - Assert.assertFalse(CollectionUtils.sizeIsEmpty(Arrays.asList("1", "2").iterator())); + assertTrue(CollectionUtils.sizeIsEmpty(Collections.emptyIterator())); + assertFalse(CollectionUtils.sizeIsEmpty(Arrays.asList("1", "2").iterator())); // enumeration - Assert.assertTrue(CollectionUtils.sizeIsEmpty(asEnumeration(Collections.emptyIterator()))); - Assert.assertFalse(CollectionUtils.sizeIsEmpty(asEnumeration(Collections.singleton("").iterator()))); + assertTrue(CollectionUtils.sizeIsEmpty(asEnumeration(Collections.emptyIterator()))); + assertFalse(CollectionUtils.sizeIsEmpty(asEnumeration(Collections.singleton("").iterator()))); } - @Test(expected = IllegalArgumentException.class) - public void testSizeIsEmpty1() { - CollectionUtils.sizeIsEmpty(null); + @Test + void testSizeIsEmpty1() { + assertThrows(IllegalArgumentException.class, () -> { + CollectionUtils.sizeIsEmpty(null); + }); } - @Test(expected = IllegalArgumentException.class) - public void testSizeIsEmpty2() { - CollectionUtils.sizeIsEmpty("string"); + @Test + void testSizeIsEmpty2() { + assertThrows(IllegalArgumentException.class, () -> { + CollectionUtils.sizeIsEmpty("string"); + }); } @Test - public void testContains() { - Assert.assertTrue(CollectionUtils.contains(Collections.singletonList("target"), "target")); - Assert.assertFalse(CollectionUtils.contains(Collections.emptyList(), "target")); + void testContains() { + assertTrue(CollectionUtils.contains(Collections.singletonList("target"), "target")); + assertFalse(CollectionUtils.contains(Collections.emptyList(), "target")); } @Test - public void testIsEmpty() { - Assert.assertFalse(CollectionUtils.isEmpty(Collections.singletonList("target"))); - Assert.assertTrue(CollectionUtils.isEmpty(Collections.emptyList())); - Assert.assertTrue(CollectionUtils.isEmpty(null)); + void testIsEmpty() { + assertFalse(CollectionUtils.isEmpty(Collections.singletonList("target"))); + assertTrue(CollectionUtils.isEmpty(Collections.emptyList())); + assertTrue(CollectionUtils.isEmpty(null)); } @Test - public void testIsNotEmpty() { - Assert.assertTrue(CollectionUtils.isNotEmpty(Collections.singletonList("target"))); - Assert.assertFalse(CollectionUtils.isNotEmpty(Collections.emptyList())); - Assert.assertFalse(CollectionUtils.isNotEmpty(null)); + void testIsNotEmpty() { + assertTrue(CollectionUtils.isNotEmpty(Collections.singletonList("target"))); + assertFalse(CollectionUtils.isNotEmpty(Collections.emptyList())); + assertFalse(CollectionUtils.isNotEmpty(null)); } @Test - public void testGetOrDefault() { - Assert.assertEquals("default", CollectionUtils.getOrDefault(Collections.emptyList(), 1, "default")); - Assert.assertEquals("element", - CollectionUtils.getOrDefault(Collections.singletonList("element"), 0, "default")); + void testGetOrDefault() { + assertEquals("default", CollectionUtils.getOrDefault(Collections.emptyList(), 1, "default")); + assertEquals("element", CollectionUtils.getOrDefault(Collections.singletonList("element"), 0, "default")); } @Test - public void testList() { - Assert.assertEquals(Arrays.asList(null, null, null), CollectionUtils.list(null, null, null)); - Assert.assertEquals(Arrays.asList("", "a", "b"), CollectionUtils.list("", "a", "b")); - Assert.assertEquals(new ArrayList(), CollectionUtils.list()); + void testList() { + assertEquals(Arrays.asList(null, null, null), CollectionUtils.list(null, null, null)); + assertEquals(Arrays.asList("", "a", "b"), CollectionUtils.list("", "a", "b")); + assertEquals(new ArrayList(), CollectionUtils.list()); } - @Test(expected = IllegalArgumentException.class) - public void testListNullPointerException() { - CollectionUtils.list(null); + @Test + void testListNullPointerException() { + assertThrows(IllegalArgumentException.class, () -> { + CollectionUtils.list(null); + }); } private Enumeration asEnumeration(final Iterator iterator) { @@ -325,71 +370,79 @@ public T nextElement() { } @Test - public void testSet() { + void testSet() { Set set = new HashSet<>(); set.add(null); - Assert.assertEquals(set, CollectionUtils.set(null, null, null)); - Assert.assertEquals(new LinkedHashSet(Arrays.asList("", "a", "b")), CollectionUtils.set("", "a", "b")); - Assert.assertEquals(new HashSet(), CollectionUtils.set()); + assertEquals(set, CollectionUtils.set(null, null, null)); + assertEquals(new LinkedHashSet(Arrays.asList("", "a", "b")), CollectionUtils.set("", "a", "b")); + assertEquals(new HashSet(), CollectionUtils.set()); } - @Test(expected = IllegalArgumentException.class) - public void testSetNullPointerException() { - CollectionUtils.set(null); + @Test + void testSetNullPointerException() { + assertThrows(IllegalArgumentException.class, () -> { + CollectionUtils.set(null); + }); } - @Test(expected = IllegalArgumentException.class) - public void testGetOnlyElementIllegalArgumentException() { - List list = Arrays.asList(1, 2, 3, 4, 5, 6); - CollectionUtils.getOnlyElement(list); + @Test + void testGetOnlyElementIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> { + List list = Arrays.asList(1, 2, 3, 4, 5, 6); + CollectionUtils.getOnlyElement(list); + }); } - @Test(expected = IllegalArgumentException.class) - public void testGetOnlyElementIllegalArgumentException2() { - CollectionUtils.getOnlyElement(null); + @Test + void testGetOnlyElementIllegalArgumentException2() { + assertThrows(IllegalArgumentException.class, () -> { + CollectionUtils.getOnlyElement(null); + }); } - @Test(expected = NoSuchElementException.class) - public void testGetOnlyElementNoSuchElementException() { - List list = new ArrayList<>(); - CollectionUtils.getOnlyElement(list); + @Test + void testGetOnlyElementNoSuchElementException() { + assertThrows(NoSuchElementException.class, () -> { + List list = new ArrayList<>(); + CollectionUtils.getOnlyElement(list); + }); } @Test - public void testGetOnly() { + void testGetOnly() { List list = Arrays.asList(1); int element = CollectionUtils.getOnlyElement(list); - Assert.assertEquals(1, element); + assertEquals(1, element); } @Test - public void testIsListEqualForNull() { - Assert.assertTrue(CollectionUtils.isListEqual(null, null)); - Assert.assertFalse(CollectionUtils.isListEqual(Collections.emptyList(), null)); - Assert.assertFalse(CollectionUtils.isListEqual(null, Collections.emptyList())); + void testIsListEqualForNull() { + assertTrue(CollectionUtils.isListEqual(null, null)); + assertFalse(CollectionUtils.isListEqual(Collections.emptyList(), null)); + assertFalse(CollectionUtils.isListEqual(null, Collections.emptyList())); } @Test - public void testIsListEqualForEquals() { + void testIsListEqualForEquals() { List list1 = Arrays.asList("1", "2", "3"); List list2 = Arrays.asList("1", "2", "3"); - Assert.assertTrue(CollectionUtils.isListEqual(list1, list1)); - Assert.assertTrue(CollectionUtils.isListEqual(list1, list2)); - Assert.assertTrue(CollectionUtils.isListEqual(list2, list1)); + assertTrue(CollectionUtils.isListEqual(list1, list1)); + assertTrue(CollectionUtils.isListEqual(list1, list2)); + assertTrue(CollectionUtils.isListEqual(list2, list1)); } @Test - public void testIsListEqualForNotEquals() { + void testIsListEqualForNotEquals() { List list1 = Arrays.asList("1", "2", "3"); List list2 = Arrays.asList("1", "2", "3", "4"); List list3 = Arrays.asList("1", "2", "3", "5"); - Assert.assertFalse(CollectionUtils.isListEqual(list1, list2)); - Assert.assertFalse(CollectionUtils.isListEqual(list2, list3)); + assertFalse(CollectionUtils.isListEqual(list1, list2)); + assertFalse(CollectionUtils.isListEqual(list2, list3)); } @Test - public void testIsMapEmpty() { - Assert.assertTrue(CollectionUtils.isMapEmpty(null)); - Assert.assertTrue(CollectionUtils.isMapEmpty(Collections.emptyMap())); + void testIsMapEmpty() { + assertTrue(CollectionUtils.isMapEmpty(null)); + assertTrue(CollectionUtils.isMapEmpty(Collections.emptyMap())); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/ConcurrentHashSetTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/ConcurrentHashSetTest.java index 752390de823..663a4b9b225 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/ConcurrentHashSetTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/ConcurrentHashSetTest.java @@ -16,55 +16,60 @@ package com.alibaba.nacos.common.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import java.util.ConcurrentModificationException; import java.util.HashSet; import java.util.Random; import java.util.Set; import java.util.concurrent.TimeUnit; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * ConcurrentHashSet Test. + * * @ClassName: ConcurrentHashSetTest * @Author: ChenHao26 * @Date: 2022/8/22 11:21 */ -public class ConcurrentHashSetTest { +class ConcurrentHashSetTest { @Test - public void testBasicOps() { + void testBasicOps() { Set set = new ConcurrentHashSet<>(); // addition - Assert.assertTrue(set.add(0)); - Assert.assertTrue(set.add(1)); - Assert.assertTrue(set.contains(0)); - Assert.assertTrue(set.contains(1)); - Assert.assertFalse(set.contains(-1)); - Assert.assertEquals(2, set.size()); + assertTrue(set.add(0)); + assertTrue(set.add(1)); + assertTrue(set.contains(0)); + assertTrue(set.contains(1)); + assertFalse(set.contains(-1)); + assertEquals(2, set.size()); // iter for (int i : set) { - Assert.assertTrue(i == 0 || i == 1); + assertTrue(i == 0 || i == 1); } // removal - Assert.assertTrue(set.remove(0)); - Assert.assertFalse(set.remove(0)); - Assert.assertFalse(set.contains(0)); - Assert.assertTrue(set.contains(1)); - Assert.assertEquals(1, set.size()); - + assertTrue(set.remove(0)); + assertFalse(set.remove(0)); + assertFalse(set.contains(0)); + assertTrue(set.contains(1)); + assertEquals(1, set.size()); + // clear - Assert.assertFalse(set.isEmpty()); + assertFalse(set.isEmpty()); set.clear(); - Assert.assertEquals(0, set.size()); - Assert.assertTrue(set.isEmpty()); + assertEquals(0, set.size()); + assertTrue(set.isEmpty()); } @Test - public void testMultiThread() throws Exception { + void testMultiThread() throws Exception { int count = 5; SetMultiThreadChecker hashSetChecker = new SetMultiThreadChecker(new HashSet<>()); hashSetChecker.start(); @@ -75,8 +80,8 @@ public void testMultiThread() throws Exception { } count--; } - Assert.assertTrue(hashSetChecker.hasConcurrentError()); - + assertTrue(hashSetChecker.hasConcurrentError()); + count = 5; SetMultiThreadChecker concurrentSetChecker = new SetMultiThreadChecker(new ConcurrentHashSet<>()); concurrentSetChecker.start(); @@ -87,17 +92,17 @@ public void testMultiThread() throws Exception { } count--; } - Assert.assertFalse(concurrentSetChecker.hasConcurrentError()); + assertFalse(concurrentSetChecker.hasConcurrentError()); } static class SetMultiThreadChecker { - + private final AddDataThread addThread; private final DeleteDataThread deleteThread; - + private final IteratorThread iteratorThread; - + public SetMultiThreadChecker(Set setToCheck) { for (int i = 0; i < 1000; i++) { setToCheck.add(i); @@ -120,7 +125,7 @@ public boolean hasConcurrentError() { public boolean isRunning() { return addThread.isRunning() || deleteThread.isRunning() || iteratorThread.isRunning(); } - + public void stop() { addThread.stop(); deleteThread.stop(); @@ -130,17 +135,17 @@ public void stop() { } abstract static class ConcurrentCheckThread implements Runnable { - + protected final Set hashSet; - + protected boolean concurrentError = false; protected boolean finish = false; - + public ConcurrentCheckThread(Set hashSet) { this.hashSet = hashSet; } - + public boolean hasConcurrentError() { return concurrentError; } @@ -148,11 +153,11 @@ public boolean hasConcurrentError() { public void stop() { finish = true; } - + public boolean isRunning() { return !finish; } - + @Override public void run() { try { @@ -165,17 +170,17 @@ public void run() { finish = true; } } - + protected abstract void process(); } //add data thread static class AddDataThread extends ConcurrentCheckThread implements Runnable { - + public AddDataThread(Set hashSet) { super(hashSet); } - + @Override protected void process() { int random = new Random().nextInt(1000); @@ -186,11 +191,11 @@ protected void process() { // delete data thread static class DeleteDataThread extends ConcurrentCheckThread implements Runnable { - + public DeleteDataThread(Set hashSet) { super(hashSet); } - + @Override protected void process() { int random = new Random().nextInt(1000); @@ -200,11 +205,11 @@ protected void process() { } static class IteratorThread extends ConcurrentCheckThread implements Runnable { - + public IteratorThread(Set hashSet) { super(hashSet); } - + @Override public void run() { System.out.println("start -- hashSet.size() : " + hashSet.size()); @@ -223,7 +228,7 @@ public void run() { System.out.println("finished at " + f); System.out.println("end -- hashSet.size() : " + hashSet.size()); } - + @Override protected void process() { } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/ConnLabelsUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/ConnLabelsUtilsTest.java index 5bfe3256516..2f945da1853 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/ConnLabelsUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/ConnLabelsUtilsTest.java @@ -16,13 +16,14 @@ package com.alibaba.nacos.common.utils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Map; import java.util.Properties; -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.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * description. @@ -30,10 +31,10 @@ * @author rong * @date 2024-03-01 15:10 */ -public class ConnLabelsUtilsTest { +class ConnLabelsUtilsTest { @Test - public void testParsePropertyValue2Map() { + void testParsePropertyValue2Map() { Properties properties = new Properties(); String property = "property"; String rawValue = "k1 = v1, k2 = v2"; @@ -50,7 +51,7 @@ public void testParsePropertyValue2Map() { Map m1 = ConnLabelsUtils.parsePropertyValue2Map(properties, property1); assertEquals(1, m1.size()); assertEquals("v11", m1.get("k11")); - assertEquals(null, m1.get("kk2")); + assertNull(m1.get("kk2")); m = ConnLabelsUtils.mergeMapByOrder(m, m1); assertEquals(3, m.size()); diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/ConvertUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/ConvertUtilsTest.java index 9239c5079bb..708408f11a2 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/ConvertUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/ConvertUtilsTest.java @@ -16,306 +16,310 @@ package com.alibaba.nacos.common.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; +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; + /** * Unit test of ConvertUtils. * * @author sunjifeng */ -public class ConvertUtilsTest { +class ConvertUtilsTest { @Test - public void testToInt() { + void testToInt() { // ConvertUtils.toInt(String) - Assert.assertEquals(0, ConvertUtils.toInt("0")); - Assert.assertEquals(-1, ConvertUtils.toInt("-1")); - Assert.assertEquals(10, ConvertUtils.toInt("10")); - Assert.assertEquals(Integer.MAX_VALUE, ConvertUtils.toInt(String.valueOf(Integer.MAX_VALUE))); - Assert.assertEquals(Integer.MIN_VALUE, ConvertUtils.toInt(String.valueOf(Integer.MIN_VALUE))); - Assert.assertEquals(0, ConvertUtils.toInt("notIntValue")); + assertEquals(0, ConvertUtils.toInt("0")); + assertEquals(-1, ConvertUtils.toInt("-1")); + assertEquals(10, ConvertUtils.toInt("10")); + assertEquals(Integer.MAX_VALUE, ConvertUtils.toInt(String.valueOf(Integer.MAX_VALUE))); + assertEquals(Integer.MIN_VALUE, ConvertUtils.toInt(String.valueOf(Integer.MIN_VALUE))); + assertEquals(0, ConvertUtils.toInt("notIntValue")); // ConvertUtils.toInt(String, Integer) - Assert.assertEquals(0, ConvertUtils.toInt("0", 100)); - Assert.assertEquals(100, ConvertUtils.toInt(null, 100)); - Assert.assertEquals(100, ConvertUtils.toInt("null", 100)); - Assert.assertEquals(100, ConvertUtils.toInt("notIntValue", 100)); + assertEquals(0, ConvertUtils.toInt("0", 100)); + assertEquals(100, ConvertUtils.toInt(null, 100)); + assertEquals(100, ConvertUtils.toInt("null", 100)); + assertEquals(100, ConvertUtils.toInt("notIntValue", 100)); } @Test - public void testToLong() { + void testToLong() { // ConvertUtils.toLong(Object) - Assert.assertEquals(0L, ConvertUtils.toLong(new ArrayList<>())); - Assert.assertEquals(10L, ConvertUtils.toLong((Object) 10L)); + assertEquals(0L, ConvertUtils.toLong(new ArrayList<>())); + assertEquals(10L, ConvertUtils.toLong((Object) 10L)); // ConvertUtils.toLong(String) - Assert.assertEquals(0L, ConvertUtils.toLong("0")); - Assert.assertEquals(-1L, ConvertUtils.toLong("-1")); - Assert.assertEquals(10L, ConvertUtils.toLong("10")); - Assert.assertEquals(Long.MAX_VALUE, ConvertUtils.toLong(String.valueOf(Long.MAX_VALUE))); - Assert.assertEquals(Long.MIN_VALUE, ConvertUtils.toLong(String.valueOf(Long.MIN_VALUE))); - Assert.assertEquals(0L, ConvertUtils.toLong("notIntValue")); + assertEquals(0L, ConvertUtils.toLong("0")); + assertEquals(-1L, ConvertUtils.toLong("-1")); + assertEquals(10L, ConvertUtils.toLong("10")); + assertEquals(Long.MAX_VALUE, ConvertUtils.toLong(String.valueOf(Long.MAX_VALUE))); + assertEquals(Long.MIN_VALUE, ConvertUtils.toLong(String.valueOf(Long.MIN_VALUE))); + assertEquals(0L, ConvertUtils.toLong("notIntValue")); // ConvertUtils.toLong(String, Integer) - Assert.assertEquals(0L, ConvertUtils.toLong("0", 100L)); - Assert.assertEquals(100L, ConvertUtils.toLong(null, 100L)); - Assert.assertEquals(100L, ConvertUtils.toLong("null", 100L)); - Assert.assertEquals(100L, ConvertUtils.toLong("notIntValue", 100L)); + assertEquals(0L, ConvertUtils.toLong("0", 100L)); + assertEquals(100L, ConvertUtils.toLong(null, 100L)); + assertEquals(100L, ConvertUtils.toLong("null", 100L)); + assertEquals(100L, ConvertUtils.toLong("notIntValue", 100L)); } @Test - public void testToBoolean() { + void testToBoolean() { // ConvertUtils.toBoolean(String) - Assert.assertTrue(ConvertUtils.toBoolean("true")); - Assert.assertTrue(ConvertUtils.toBoolean("True")); - Assert.assertTrue(ConvertUtils.toBoolean("TRUE")); - Assert.assertFalse(ConvertUtils.toBoolean("false")); - Assert.assertFalse(ConvertUtils.toBoolean("False")); - Assert.assertFalse(ConvertUtils.toBoolean("FALSE")); - Assert.assertFalse(ConvertUtils.toBoolean(null)); - Assert.assertFalse(ConvertUtils.toBoolean("notBoolean")); + assertTrue(ConvertUtils.toBoolean("true")); + assertTrue(ConvertUtils.toBoolean("True")); + assertTrue(ConvertUtils.toBoolean("TRUE")); + assertFalse(ConvertUtils.toBoolean("false")); + assertFalse(ConvertUtils.toBoolean("False")); + assertFalse(ConvertUtils.toBoolean("FALSE")); + assertFalse(ConvertUtils.toBoolean(null)); + assertFalse(ConvertUtils.toBoolean("notBoolean")); // ConvertUtils.toBoolean(String, boolean) - Assert.assertFalse(ConvertUtils.toBoolean("", false)); - Assert.assertFalse(ConvertUtils.toBoolean(null, false)); - Assert.assertFalse(ConvertUtils.toBoolean("notBoolean", false)); - Assert.assertTrue(ConvertUtils.toBoolean("true", false)); + assertFalse(ConvertUtils.toBoolean("", false)); + assertFalse(ConvertUtils.toBoolean(null, false)); + assertFalse(ConvertUtils.toBoolean("notBoolean", false)); + assertTrue(ConvertUtils.toBoolean("true", false)); } @Test - public void testToBooleanObject() { - Assert.assertTrue(ConvertUtils.toBooleanObject("T")); - Assert.assertTrue(ConvertUtils.toBooleanObject("t")); - Assert.assertTrue(ConvertUtils.toBooleanObject("Y")); - Assert.assertTrue(ConvertUtils.toBooleanObject("y")); - Assert.assertFalse(ConvertUtils.toBooleanObject("f")); - Assert.assertFalse(ConvertUtils.toBooleanObject("F")); - Assert.assertFalse(ConvertUtils.toBooleanObject("n")); - Assert.assertFalse(ConvertUtils.toBooleanObject("N")); - Assert.assertNull(ConvertUtils.toBooleanObject("a")); + void testToBooleanObject() { + assertTrue(ConvertUtils.toBooleanObject("T")); + assertTrue(ConvertUtils.toBooleanObject("t")); + assertTrue(ConvertUtils.toBooleanObject("Y")); + assertTrue(ConvertUtils.toBooleanObject("y")); + assertFalse(ConvertUtils.toBooleanObject("f")); + assertFalse(ConvertUtils.toBooleanObject("F")); + assertFalse(ConvertUtils.toBooleanObject("n")); + assertFalse(ConvertUtils.toBooleanObject("N")); + assertNull(ConvertUtils.toBooleanObject("a")); - Assert.assertTrue(ConvertUtils.toBooleanObject("on")); - Assert.assertTrue(ConvertUtils.toBooleanObject("oN")); - Assert.assertTrue(ConvertUtils.toBooleanObject("On")); - Assert.assertTrue(ConvertUtils.toBooleanObject("ON")); - Assert.assertFalse(ConvertUtils.toBooleanObject("No")); - Assert.assertFalse(ConvertUtils.toBooleanObject("NO")); - Assert.assertNull(ConvertUtils.toBooleanObject("an")); - Assert.assertNull(ConvertUtils.toBooleanObject("aN")); - Assert.assertNull(ConvertUtils.toBooleanObject("oa")); - Assert.assertNull(ConvertUtils.toBooleanObject("Oa")); - Assert.assertNull(ConvertUtils.toBooleanObject("Na")); - Assert.assertNull(ConvertUtils.toBooleanObject("na")); - Assert.assertNull(ConvertUtils.toBooleanObject("aO")); - Assert.assertNull(ConvertUtils.toBooleanObject("ao")); + assertTrue(ConvertUtils.toBooleanObject("on")); + assertTrue(ConvertUtils.toBooleanObject("oN")); + assertTrue(ConvertUtils.toBooleanObject("On")); + assertTrue(ConvertUtils.toBooleanObject("ON")); + assertFalse(ConvertUtils.toBooleanObject("No")); + assertFalse(ConvertUtils.toBooleanObject("NO")); + assertNull(ConvertUtils.toBooleanObject("an")); + assertNull(ConvertUtils.toBooleanObject("aN")); + assertNull(ConvertUtils.toBooleanObject("oa")); + assertNull(ConvertUtils.toBooleanObject("Oa")); + assertNull(ConvertUtils.toBooleanObject("Na")); + assertNull(ConvertUtils.toBooleanObject("na")); + assertNull(ConvertUtils.toBooleanObject("aO")); + assertNull(ConvertUtils.toBooleanObject("ao")); - Assert.assertFalse(ConvertUtils.toBooleanObject("off")); - Assert.assertFalse(ConvertUtils.toBooleanObject("ofF")); - Assert.assertFalse(ConvertUtils.toBooleanObject("oFf")); - Assert.assertFalse(ConvertUtils.toBooleanObject("oFF")); - Assert.assertFalse(ConvertUtils.toBooleanObject("Off")); - Assert.assertFalse(ConvertUtils.toBooleanObject("OfF")); - Assert.assertFalse(ConvertUtils.toBooleanObject("OFf")); - Assert.assertFalse(ConvertUtils.toBooleanObject("OFF")); - Assert.assertTrue(ConvertUtils.toBooleanObject("yes")); - Assert.assertTrue(ConvertUtils.toBooleanObject("yeS")); - Assert.assertTrue(ConvertUtils.toBooleanObject("yEs")); - Assert.assertTrue(ConvertUtils.toBooleanObject("yES")); - Assert.assertTrue(ConvertUtils.toBooleanObject("Yes")); - Assert.assertTrue(ConvertUtils.toBooleanObject("YeS")); - Assert.assertTrue(ConvertUtils.toBooleanObject("YEs")); - Assert.assertTrue(ConvertUtils.toBooleanObject("YES")); - Assert.assertNull(ConvertUtils.toBooleanObject("ono")); - Assert.assertNull(ConvertUtils.toBooleanObject("aes")); - Assert.assertNull(ConvertUtils.toBooleanObject("aeS")); - Assert.assertNull(ConvertUtils.toBooleanObject("aEs")); - Assert.assertNull(ConvertUtils.toBooleanObject("aES")); - Assert.assertNull(ConvertUtils.toBooleanObject("yas")); - Assert.assertNull(ConvertUtils.toBooleanObject("yaS")); - Assert.assertNull(ConvertUtils.toBooleanObject("Yas")); - Assert.assertNull(ConvertUtils.toBooleanObject("YaS")); - Assert.assertNull(ConvertUtils.toBooleanObject("yea")); - Assert.assertNull(ConvertUtils.toBooleanObject("yEa")); - Assert.assertNull(ConvertUtils.toBooleanObject("Yea")); - Assert.assertNull(ConvertUtils.toBooleanObject("YEa")); - Assert.assertNull(ConvertUtils.toBooleanObject("aff")); - Assert.assertNull(ConvertUtils.toBooleanObject("afF")); - Assert.assertNull(ConvertUtils.toBooleanObject("aFf")); - Assert.assertNull(ConvertUtils.toBooleanObject("aFF")); - Assert.assertNull(ConvertUtils.toBooleanObject("oaf")); - Assert.assertNull(ConvertUtils.toBooleanObject("oaF")); - Assert.assertNull(ConvertUtils.toBooleanObject("Oaf")); - Assert.assertNull(ConvertUtils.toBooleanObject("OaF")); - Assert.assertNull(ConvertUtils.toBooleanObject("Ofa")); - Assert.assertNull(ConvertUtils.toBooleanObject("ofa")); - Assert.assertNull(ConvertUtils.toBooleanObject("OFa")); - Assert.assertNull(ConvertUtils.toBooleanObject("oFa")); + assertFalse(ConvertUtils.toBooleanObject("off")); + assertFalse(ConvertUtils.toBooleanObject("ofF")); + assertFalse(ConvertUtils.toBooleanObject("oFf")); + assertFalse(ConvertUtils.toBooleanObject("oFF")); + assertFalse(ConvertUtils.toBooleanObject("Off")); + assertFalse(ConvertUtils.toBooleanObject("OfF")); + assertFalse(ConvertUtils.toBooleanObject("OFf")); + assertFalse(ConvertUtils.toBooleanObject("OFF")); + assertTrue(ConvertUtils.toBooleanObject("yes")); + assertTrue(ConvertUtils.toBooleanObject("yeS")); + assertTrue(ConvertUtils.toBooleanObject("yEs")); + assertTrue(ConvertUtils.toBooleanObject("yES")); + assertTrue(ConvertUtils.toBooleanObject("Yes")); + assertTrue(ConvertUtils.toBooleanObject("YeS")); + assertTrue(ConvertUtils.toBooleanObject("YEs")); + assertTrue(ConvertUtils.toBooleanObject("YES")); + assertNull(ConvertUtils.toBooleanObject("ono")); + assertNull(ConvertUtils.toBooleanObject("aes")); + assertNull(ConvertUtils.toBooleanObject("aeS")); + assertNull(ConvertUtils.toBooleanObject("aEs")); + assertNull(ConvertUtils.toBooleanObject("aES")); + assertNull(ConvertUtils.toBooleanObject("yas")); + assertNull(ConvertUtils.toBooleanObject("yaS")); + assertNull(ConvertUtils.toBooleanObject("Yas")); + assertNull(ConvertUtils.toBooleanObject("YaS")); + assertNull(ConvertUtils.toBooleanObject("yea")); + assertNull(ConvertUtils.toBooleanObject("yEa")); + assertNull(ConvertUtils.toBooleanObject("Yea")); + assertNull(ConvertUtils.toBooleanObject("YEa")); + assertNull(ConvertUtils.toBooleanObject("aff")); + assertNull(ConvertUtils.toBooleanObject("afF")); + assertNull(ConvertUtils.toBooleanObject("aFf")); + assertNull(ConvertUtils.toBooleanObject("aFF")); + assertNull(ConvertUtils.toBooleanObject("oaf")); + assertNull(ConvertUtils.toBooleanObject("oaF")); + assertNull(ConvertUtils.toBooleanObject("Oaf")); + assertNull(ConvertUtils.toBooleanObject("OaF")); + assertNull(ConvertUtils.toBooleanObject("Ofa")); + assertNull(ConvertUtils.toBooleanObject("ofa")); + assertNull(ConvertUtils.toBooleanObject("OFa")); + assertNull(ConvertUtils.toBooleanObject("oFa")); - Assert.assertTrue(ConvertUtils.toBooleanObject("true")); - Assert.assertTrue(ConvertUtils.toBooleanObject("truE")); - Assert.assertTrue(ConvertUtils.toBooleanObject("trUe")); - Assert.assertTrue(ConvertUtils.toBooleanObject("trUE")); - Assert.assertTrue(ConvertUtils.toBooleanObject("tRue")); - Assert.assertTrue(ConvertUtils.toBooleanObject("tRuE")); - Assert.assertTrue(ConvertUtils.toBooleanObject("tRUe")); - Assert.assertTrue(ConvertUtils.toBooleanObject("tRUE")); - Assert.assertTrue(ConvertUtils.toBooleanObject("True")); - Assert.assertTrue(ConvertUtils.toBooleanObject("TruE")); - Assert.assertTrue(ConvertUtils.toBooleanObject("TrUe")); - Assert.assertTrue(ConvertUtils.toBooleanObject("TrUE")); - Assert.assertTrue(ConvertUtils.toBooleanObject("TRue")); - Assert.assertTrue(ConvertUtils.toBooleanObject("TRuE")); - Assert.assertTrue(ConvertUtils.toBooleanObject("TRUe")); - Assert.assertTrue(ConvertUtils.toBooleanObject("TRUE")); - Assert.assertNull(ConvertUtils.toBooleanObject("Xrue")); - Assert.assertNull(ConvertUtils.toBooleanObject("XruE")); - Assert.assertNull(ConvertUtils.toBooleanObject("XrUe")); - Assert.assertNull(ConvertUtils.toBooleanObject("XrUE")); - Assert.assertNull(ConvertUtils.toBooleanObject("XRue")); - Assert.assertNull(ConvertUtils.toBooleanObject("XRuE")); - Assert.assertNull(ConvertUtils.toBooleanObject("XRUe")); - Assert.assertNull(ConvertUtils.toBooleanObject("XRUE")); - Assert.assertNull(ConvertUtils.toBooleanObject("tXue")); - Assert.assertNull(ConvertUtils.toBooleanObject("tXuE")); - Assert.assertNull(ConvertUtils.toBooleanObject("tXUe")); - Assert.assertNull(ConvertUtils.toBooleanObject("tXUE")); - Assert.assertNull(ConvertUtils.toBooleanObject("TXue")); - Assert.assertNull(ConvertUtils.toBooleanObject("TXuE")); - Assert.assertNull(ConvertUtils.toBooleanObject("TXUe")); - Assert.assertNull(ConvertUtils.toBooleanObject("TXUE")); - Assert.assertNull(ConvertUtils.toBooleanObject("trXe")); - Assert.assertNull(ConvertUtils.toBooleanObject("trXE")); - Assert.assertNull(ConvertUtils.toBooleanObject("tRXe")); - Assert.assertNull(ConvertUtils.toBooleanObject("tRXE")); - Assert.assertNull(ConvertUtils.toBooleanObject("TrXe")); - Assert.assertNull(ConvertUtils.toBooleanObject("TrXE")); - Assert.assertNull(ConvertUtils.toBooleanObject("TRXe")); - Assert.assertNull(ConvertUtils.toBooleanObject("TRXE")); - Assert.assertNull(ConvertUtils.toBooleanObject("truX")); - Assert.assertNull(ConvertUtils.toBooleanObject("trUX")); - Assert.assertNull(ConvertUtils.toBooleanObject("tRuX")); - Assert.assertNull(ConvertUtils.toBooleanObject("tRUX")); - Assert.assertNull(ConvertUtils.toBooleanObject("TruX")); - Assert.assertNull(ConvertUtils.toBooleanObject("TrUX")); - Assert.assertNull(ConvertUtils.toBooleanObject("TRuX")); - Assert.assertNull(ConvertUtils.toBooleanObject("TRUX")); + assertTrue(ConvertUtils.toBooleanObject("true")); + assertTrue(ConvertUtils.toBooleanObject("truE")); + assertTrue(ConvertUtils.toBooleanObject("trUe")); + assertTrue(ConvertUtils.toBooleanObject("trUE")); + assertTrue(ConvertUtils.toBooleanObject("tRue")); + assertTrue(ConvertUtils.toBooleanObject("tRuE")); + assertTrue(ConvertUtils.toBooleanObject("tRUe")); + assertTrue(ConvertUtils.toBooleanObject("tRUE")); + assertTrue(ConvertUtils.toBooleanObject("True")); + assertTrue(ConvertUtils.toBooleanObject("TruE")); + assertTrue(ConvertUtils.toBooleanObject("TrUe")); + assertTrue(ConvertUtils.toBooleanObject("TrUE")); + assertTrue(ConvertUtils.toBooleanObject("TRue")); + assertTrue(ConvertUtils.toBooleanObject("TRuE")); + assertTrue(ConvertUtils.toBooleanObject("TRUe")); + assertTrue(ConvertUtils.toBooleanObject("TRUE")); + assertNull(ConvertUtils.toBooleanObject("Xrue")); + assertNull(ConvertUtils.toBooleanObject("XruE")); + assertNull(ConvertUtils.toBooleanObject("XrUe")); + assertNull(ConvertUtils.toBooleanObject("XrUE")); + assertNull(ConvertUtils.toBooleanObject("XRue")); + assertNull(ConvertUtils.toBooleanObject("XRuE")); + assertNull(ConvertUtils.toBooleanObject("XRUe")); + assertNull(ConvertUtils.toBooleanObject("XRUE")); + assertNull(ConvertUtils.toBooleanObject("tXue")); + assertNull(ConvertUtils.toBooleanObject("tXuE")); + assertNull(ConvertUtils.toBooleanObject("tXUe")); + assertNull(ConvertUtils.toBooleanObject("tXUE")); + assertNull(ConvertUtils.toBooleanObject("TXue")); + assertNull(ConvertUtils.toBooleanObject("TXuE")); + assertNull(ConvertUtils.toBooleanObject("TXUe")); + assertNull(ConvertUtils.toBooleanObject("TXUE")); + assertNull(ConvertUtils.toBooleanObject("trXe")); + assertNull(ConvertUtils.toBooleanObject("trXE")); + assertNull(ConvertUtils.toBooleanObject("tRXe")); + assertNull(ConvertUtils.toBooleanObject("tRXE")); + assertNull(ConvertUtils.toBooleanObject("TrXe")); + assertNull(ConvertUtils.toBooleanObject("TrXE")); + assertNull(ConvertUtils.toBooleanObject("TRXe")); + assertNull(ConvertUtils.toBooleanObject("TRXE")); + assertNull(ConvertUtils.toBooleanObject("truX")); + assertNull(ConvertUtils.toBooleanObject("trUX")); + assertNull(ConvertUtils.toBooleanObject("tRuX")); + assertNull(ConvertUtils.toBooleanObject("tRUX")); + assertNull(ConvertUtils.toBooleanObject("TruX")); + assertNull(ConvertUtils.toBooleanObject("TrUX")); + assertNull(ConvertUtils.toBooleanObject("TRuX")); + assertNull(ConvertUtils.toBooleanObject("TRUX")); - Assert.assertFalse(ConvertUtils.toBooleanObject("false")); - Assert.assertFalse(ConvertUtils.toBooleanObject("falsE")); - Assert.assertFalse(ConvertUtils.toBooleanObject("falSe")); - Assert.assertFalse(ConvertUtils.toBooleanObject("falSE")); - Assert.assertFalse(ConvertUtils.toBooleanObject("faLse")); - Assert.assertFalse(ConvertUtils.toBooleanObject("faLsE")); - Assert.assertFalse(ConvertUtils.toBooleanObject("faLSe")); - Assert.assertFalse(ConvertUtils.toBooleanObject("faLSE")); - Assert.assertFalse(ConvertUtils.toBooleanObject("fAlse")); - Assert.assertFalse(ConvertUtils.toBooleanObject("fAlsE")); - Assert.assertFalse(ConvertUtils.toBooleanObject("fAlSe")); - Assert.assertFalse(ConvertUtils.toBooleanObject("fAlSE")); - Assert.assertFalse(ConvertUtils.toBooleanObject("fALse")); - Assert.assertFalse(ConvertUtils.toBooleanObject("fALsE")); - Assert.assertFalse(ConvertUtils.toBooleanObject("fALSe")); - Assert.assertFalse(ConvertUtils.toBooleanObject("fALSE")); - Assert.assertFalse(ConvertUtils.toBooleanObject("False")); - Assert.assertFalse(ConvertUtils.toBooleanObject("FalsE")); - Assert.assertFalse(ConvertUtils.toBooleanObject("FalSe")); - Assert.assertFalse(ConvertUtils.toBooleanObject("FalSE")); - Assert.assertFalse(ConvertUtils.toBooleanObject("FaLse")); - Assert.assertFalse(ConvertUtils.toBooleanObject("FaLsE")); - Assert.assertFalse(ConvertUtils.toBooleanObject("FaLSe")); - Assert.assertFalse(ConvertUtils.toBooleanObject("FaLSE")); - Assert.assertFalse(ConvertUtils.toBooleanObject("FAlse")); - Assert.assertFalse(ConvertUtils.toBooleanObject("FAlsE")); - Assert.assertFalse(ConvertUtils.toBooleanObject("FAlSe")); - Assert.assertFalse(ConvertUtils.toBooleanObject("FAlSE")); - Assert.assertFalse(ConvertUtils.toBooleanObject("FALse")); - Assert.assertFalse(ConvertUtils.toBooleanObject("FALsE")); - Assert.assertFalse(ConvertUtils.toBooleanObject("FALSe")); - Assert.assertFalse(ConvertUtils.toBooleanObject("FALSE")); - Assert.assertNull(ConvertUtils.toBooleanObject("Xalse")); - Assert.assertNull(ConvertUtils.toBooleanObject("XalsE")); - Assert.assertNull(ConvertUtils.toBooleanObject("XalSe")); - Assert.assertNull(ConvertUtils.toBooleanObject("XalSE")); - Assert.assertNull(ConvertUtils.toBooleanObject("XaLse")); - Assert.assertNull(ConvertUtils.toBooleanObject("XaLsE")); - Assert.assertNull(ConvertUtils.toBooleanObject("XaLSe")); - Assert.assertNull(ConvertUtils.toBooleanObject("XaLSE")); - Assert.assertNull(ConvertUtils.toBooleanObject("XAlse")); - Assert.assertNull(ConvertUtils.toBooleanObject("XAlsE")); - Assert.assertNull(ConvertUtils.toBooleanObject("XAlSe")); - Assert.assertNull(ConvertUtils.toBooleanObject("XAlSE")); - Assert.assertNull(ConvertUtils.toBooleanObject("XALse")); - Assert.assertNull(ConvertUtils.toBooleanObject("XALsE")); - Assert.assertNull(ConvertUtils.toBooleanObject("XALSe")); - Assert.assertNull(ConvertUtils.toBooleanObject("XALSE")); - Assert.assertNull(ConvertUtils.toBooleanObject("fXlse")); - Assert.assertNull(ConvertUtils.toBooleanObject("fXlsE")); - Assert.assertNull(ConvertUtils.toBooleanObject("fXlSe")); - Assert.assertNull(ConvertUtils.toBooleanObject("fXlSE")); - Assert.assertNull(ConvertUtils.toBooleanObject("fXLse")); - Assert.assertNull(ConvertUtils.toBooleanObject("fXLsE")); - Assert.assertNull(ConvertUtils.toBooleanObject("fXLSe")); - Assert.assertNull(ConvertUtils.toBooleanObject("fXLSE")); - Assert.assertNull(ConvertUtils.toBooleanObject("FXlse")); - Assert.assertNull(ConvertUtils.toBooleanObject("FXlsE")); - Assert.assertNull(ConvertUtils.toBooleanObject("FXlSe")); - Assert.assertNull(ConvertUtils.toBooleanObject("FXlSE")); - Assert.assertNull(ConvertUtils.toBooleanObject("FXLse")); - Assert.assertNull(ConvertUtils.toBooleanObject("FXLsE")); - Assert.assertNull(ConvertUtils.toBooleanObject("FXLSe")); - Assert.assertNull(ConvertUtils.toBooleanObject("FXLSE")); - Assert.assertNull(ConvertUtils.toBooleanObject("faXse")); - Assert.assertNull(ConvertUtils.toBooleanObject("faXsE")); - Assert.assertNull(ConvertUtils.toBooleanObject("faXSe")); - Assert.assertNull(ConvertUtils.toBooleanObject("faXSE")); - Assert.assertNull(ConvertUtils.toBooleanObject("fAXse")); - Assert.assertNull(ConvertUtils.toBooleanObject("fAXsE")); - Assert.assertNull(ConvertUtils.toBooleanObject("fAXSe")); - Assert.assertNull(ConvertUtils.toBooleanObject("fAXSE")); - Assert.assertNull(ConvertUtils.toBooleanObject("FaXse")); - Assert.assertNull(ConvertUtils.toBooleanObject("FaXsE")); - Assert.assertNull(ConvertUtils.toBooleanObject("FaXSe")); - Assert.assertNull(ConvertUtils.toBooleanObject("FaXSE")); - Assert.assertNull(ConvertUtils.toBooleanObject("FAXse")); - Assert.assertNull(ConvertUtils.toBooleanObject("FAXsE")); - Assert.assertNull(ConvertUtils.toBooleanObject("FAXSe")); - Assert.assertNull(ConvertUtils.toBooleanObject("FAXSE")); - Assert.assertNull(ConvertUtils.toBooleanObject("falXe")); - Assert.assertNull(ConvertUtils.toBooleanObject("falXE")); - Assert.assertNull(ConvertUtils.toBooleanObject("faLXe")); - Assert.assertNull(ConvertUtils.toBooleanObject("faLXE")); - Assert.assertNull(ConvertUtils.toBooleanObject("fAlXe")); - Assert.assertNull(ConvertUtils.toBooleanObject("fAlXE")); - Assert.assertNull(ConvertUtils.toBooleanObject("fALXe")); - Assert.assertNull(ConvertUtils.toBooleanObject("fALXE")); - Assert.assertNull(ConvertUtils.toBooleanObject("FalXe")); - Assert.assertNull(ConvertUtils.toBooleanObject("FalXE")); - Assert.assertNull(ConvertUtils.toBooleanObject("FaLXe")); - Assert.assertNull(ConvertUtils.toBooleanObject("FaLXE")); - Assert.assertNull(ConvertUtils.toBooleanObject("FAlXe")); - Assert.assertNull(ConvertUtils.toBooleanObject("FAlXE")); - Assert.assertNull(ConvertUtils.toBooleanObject("FALXe")); - Assert.assertNull(ConvertUtils.toBooleanObject("FALXE")); - Assert.assertNull(ConvertUtils.toBooleanObject("falsX")); - Assert.assertNull(ConvertUtils.toBooleanObject("falSX")); - Assert.assertNull(ConvertUtils.toBooleanObject("faLsX")); - Assert.assertNull(ConvertUtils.toBooleanObject("faLSX")); - Assert.assertNull(ConvertUtils.toBooleanObject("fAlsX")); - Assert.assertNull(ConvertUtils.toBooleanObject("fAlSX")); - Assert.assertNull(ConvertUtils.toBooleanObject("fALsX")); - Assert.assertNull(ConvertUtils.toBooleanObject("fALSX")); - Assert.assertNull(ConvertUtils.toBooleanObject("FalsX")); - Assert.assertNull(ConvertUtils.toBooleanObject("FalSX")); - Assert.assertNull(ConvertUtils.toBooleanObject("FaLsX")); - Assert.assertNull(ConvertUtils.toBooleanObject("FaLSX")); - Assert.assertNull(ConvertUtils.toBooleanObject("FAlsX")); - Assert.assertNull(ConvertUtils.toBooleanObject("FAlSX")); - Assert.assertNull(ConvertUtils.toBooleanObject("FALsX")); - Assert.assertNull(ConvertUtils.toBooleanObject("FALSX")); + assertFalse(ConvertUtils.toBooleanObject("false")); + assertFalse(ConvertUtils.toBooleanObject("falsE")); + assertFalse(ConvertUtils.toBooleanObject("falSe")); + assertFalse(ConvertUtils.toBooleanObject("falSE")); + assertFalse(ConvertUtils.toBooleanObject("faLse")); + assertFalse(ConvertUtils.toBooleanObject("faLsE")); + assertFalse(ConvertUtils.toBooleanObject("faLSe")); + assertFalse(ConvertUtils.toBooleanObject("faLSE")); + assertFalse(ConvertUtils.toBooleanObject("fAlse")); + assertFalse(ConvertUtils.toBooleanObject("fAlsE")); + assertFalse(ConvertUtils.toBooleanObject("fAlSe")); + assertFalse(ConvertUtils.toBooleanObject("fAlSE")); + assertFalse(ConvertUtils.toBooleanObject("fALse")); + assertFalse(ConvertUtils.toBooleanObject("fALsE")); + assertFalse(ConvertUtils.toBooleanObject("fALSe")); + assertFalse(ConvertUtils.toBooleanObject("fALSE")); + assertFalse(ConvertUtils.toBooleanObject("False")); + assertFalse(ConvertUtils.toBooleanObject("FalsE")); + assertFalse(ConvertUtils.toBooleanObject("FalSe")); + assertFalse(ConvertUtils.toBooleanObject("FalSE")); + assertFalse(ConvertUtils.toBooleanObject("FaLse")); + assertFalse(ConvertUtils.toBooleanObject("FaLsE")); + assertFalse(ConvertUtils.toBooleanObject("FaLSe")); + assertFalse(ConvertUtils.toBooleanObject("FaLSE")); + assertFalse(ConvertUtils.toBooleanObject("FAlse")); + assertFalse(ConvertUtils.toBooleanObject("FAlsE")); + assertFalse(ConvertUtils.toBooleanObject("FAlSe")); + assertFalse(ConvertUtils.toBooleanObject("FAlSE")); + assertFalse(ConvertUtils.toBooleanObject("FALse")); + assertFalse(ConvertUtils.toBooleanObject("FALsE")); + assertFalse(ConvertUtils.toBooleanObject("FALSe")); + assertFalse(ConvertUtils.toBooleanObject("FALSE")); + assertNull(ConvertUtils.toBooleanObject("Xalse")); + assertNull(ConvertUtils.toBooleanObject("XalsE")); + assertNull(ConvertUtils.toBooleanObject("XalSe")); + assertNull(ConvertUtils.toBooleanObject("XalSE")); + assertNull(ConvertUtils.toBooleanObject("XaLse")); + assertNull(ConvertUtils.toBooleanObject("XaLsE")); + assertNull(ConvertUtils.toBooleanObject("XaLSe")); + assertNull(ConvertUtils.toBooleanObject("XaLSE")); + assertNull(ConvertUtils.toBooleanObject("XAlse")); + assertNull(ConvertUtils.toBooleanObject("XAlsE")); + assertNull(ConvertUtils.toBooleanObject("XAlSe")); + assertNull(ConvertUtils.toBooleanObject("XAlSE")); + assertNull(ConvertUtils.toBooleanObject("XALse")); + assertNull(ConvertUtils.toBooleanObject("XALsE")); + assertNull(ConvertUtils.toBooleanObject("XALSe")); + assertNull(ConvertUtils.toBooleanObject("XALSE")); + assertNull(ConvertUtils.toBooleanObject("fXlse")); + assertNull(ConvertUtils.toBooleanObject("fXlsE")); + assertNull(ConvertUtils.toBooleanObject("fXlSe")); + assertNull(ConvertUtils.toBooleanObject("fXlSE")); + assertNull(ConvertUtils.toBooleanObject("fXLse")); + assertNull(ConvertUtils.toBooleanObject("fXLsE")); + assertNull(ConvertUtils.toBooleanObject("fXLSe")); + assertNull(ConvertUtils.toBooleanObject("fXLSE")); + assertNull(ConvertUtils.toBooleanObject("FXlse")); + assertNull(ConvertUtils.toBooleanObject("FXlsE")); + assertNull(ConvertUtils.toBooleanObject("FXlSe")); + assertNull(ConvertUtils.toBooleanObject("FXlSE")); + assertNull(ConvertUtils.toBooleanObject("FXLse")); + assertNull(ConvertUtils.toBooleanObject("FXLsE")); + assertNull(ConvertUtils.toBooleanObject("FXLSe")); + assertNull(ConvertUtils.toBooleanObject("FXLSE")); + assertNull(ConvertUtils.toBooleanObject("faXse")); + assertNull(ConvertUtils.toBooleanObject("faXsE")); + assertNull(ConvertUtils.toBooleanObject("faXSe")); + assertNull(ConvertUtils.toBooleanObject("faXSE")); + assertNull(ConvertUtils.toBooleanObject("fAXse")); + assertNull(ConvertUtils.toBooleanObject("fAXsE")); + assertNull(ConvertUtils.toBooleanObject("fAXSe")); + assertNull(ConvertUtils.toBooleanObject("fAXSE")); + assertNull(ConvertUtils.toBooleanObject("FaXse")); + assertNull(ConvertUtils.toBooleanObject("FaXsE")); + assertNull(ConvertUtils.toBooleanObject("FaXSe")); + assertNull(ConvertUtils.toBooleanObject("FaXSE")); + assertNull(ConvertUtils.toBooleanObject("FAXse")); + assertNull(ConvertUtils.toBooleanObject("FAXsE")); + assertNull(ConvertUtils.toBooleanObject("FAXSe")); + assertNull(ConvertUtils.toBooleanObject("FAXSE")); + assertNull(ConvertUtils.toBooleanObject("falXe")); + assertNull(ConvertUtils.toBooleanObject("falXE")); + assertNull(ConvertUtils.toBooleanObject("faLXe")); + assertNull(ConvertUtils.toBooleanObject("faLXE")); + assertNull(ConvertUtils.toBooleanObject("fAlXe")); + assertNull(ConvertUtils.toBooleanObject("fAlXE")); + assertNull(ConvertUtils.toBooleanObject("fALXe")); + assertNull(ConvertUtils.toBooleanObject("fALXE")); + assertNull(ConvertUtils.toBooleanObject("FalXe")); + assertNull(ConvertUtils.toBooleanObject("FalXE")); + assertNull(ConvertUtils.toBooleanObject("FaLXe")); + assertNull(ConvertUtils.toBooleanObject("FaLXE")); + assertNull(ConvertUtils.toBooleanObject("FAlXe")); + assertNull(ConvertUtils.toBooleanObject("FAlXE")); + assertNull(ConvertUtils.toBooleanObject("FALXe")); + assertNull(ConvertUtils.toBooleanObject("FALXE")); + assertNull(ConvertUtils.toBooleanObject("falsX")); + assertNull(ConvertUtils.toBooleanObject("falSX")); + assertNull(ConvertUtils.toBooleanObject("faLsX")); + assertNull(ConvertUtils.toBooleanObject("faLSX")); + assertNull(ConvertUtils.toBooleanObject("fAlsX")); + assertNull(ConvertUtils.toBooleanObject("fAlSX")); + assertNull(ConvertUtils.toBooleanObject("fALsX")); + assertNull(ConvertUtils.toBooleanObject("fALSX")); + assertNull(ConvertUtils.toBooleanObject("FalsX")); + assertNull(ConvertUtils.toBooleanObject("FalSX")); + assertNull(ConvertUtils.toBooleanObject("FaLsX")); + assertNull(ConvertUtils.toBooleanObject("FaLSX")); + assertNull(ConvertUtils.toBooleanObject("FAlsX")); + assertNull(ConvertUtils.toBooleanObject("FAlSX")); + assertNull(ConvertUtils.toBooleanObject("FALsX")); + assertNull(ConvertUtils.toBooleanObject("FALSX")); - Assert.assertNull(ConvertUtils.toBooleanObject(null)); + assertNull(ConvertUtils.toBooleanObject(null)); } } \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/DateFormatUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/DateFormatUtilsTest.java index 70a956b5c42..5b622be1687 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/DateFormatUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/DateFormatUtilsTest.java @@ -16,21 +16,24 @@ package com.alibaba.nacos.common.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + /** * DateFormatUtils test. + * * @author zzq */ -public class DateFormatUtilsTest { +class DateFormatUtilsTest { @Test - public void testformat() { + void testformat() { final Calendar c = Calendar.getInstance(TimeZone.getDefault()); c.set(2021, Calendar.JANUARY, 1, 12, 0, 0); c.setTimeZone(TimeZone.getDefault()); @@ -43,16 +46,20 @@ public void testformat() { buffer.append(month); buffer.append(day); buffer.append(hour); - Assert.assertEquals(buffer.toString(), DateFormatUtils.format(c.getTime(), "yyyyMdH")); + assertEquals(buffer.toString(), DateFormatUtils.format(c.getTime(), "yyyyMdH")); } - @Test(expected = NullPointerException.class) - public void testForNullPointerExceptionWithDate() { - DateFormatUtils.format(new Date(), null); + @Test + void testForNullPointerExceptionWithDate() { + assertThrows(NullPointerException.class, () -> { + DateFormatUtils.format(new Date(), null); + }); } - @Test(expected = NullPointerException.class) - public void testForNullPointerExceptionWithPattern() { - DateFormatUtils.format(null, "yyyyMdH"); + @Test + void testForNullPointerExceptionWithPattern() { + assertThrows(NullPointerException.class, () -> { + DateFormatUtils.format(null, "yyyyMdH"); + }); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/ExceptionUtilTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/ExceptionUtilTest.java index b221bc43dc6..029c7e3946d 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/ExceptionUtilTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/ExceptionUtilTest.java @@ -17,42 +17,42 @@ package com.alibaba.nacos.common.utils; import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -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 ExceptionUtilTest { +class ExceptionUtilTest { NacosRuntimeException nacosRuntimeException; - @Before - public void setUp() { + @BeforeEach + void setUp() { RuntimeException caused = new RuntimeException("I'm caused exception."); nacosRuntimeException = new NacosRuntimeException(500, "Test", caused); } @Test - public void testGetAllExceptionMsg() { + void testGetAllExceptionMsg() { String msg = ExceptionUtil.getAllExceptionMsg(nacosRuntimeException); assertEquals("caused: errCode: 500, errMsg: Test ;caused: I'm caused exception.;", msg); } @Test - public void testGetCause() { + void testGetCause() { assertEquals("I'm caused exception.", ExceptionUtil.getCause(nacosRuntimeException).getMessage()); NacosRuntimeException nreWithoutCaused = new NacosRuntimeException(500); assertEquals(nreWithoutCaused, ExceptionUtil.getCause(nreWithoutCaused)); } @Test - public void testGetStackTrace() { + void testGetStackTrace() { assertEquals("", ExceptionUtil.getStackTrace(null)); String stackTrace = ExceptionUtil.getStackTrace(nacosRuntimeException); - assertTrue(stackTrace.contains( - "com.alibaba.nacos.api.exception.runtime.NacosRuntimeException: errCode: 500, errMsg: Test")); + assertTrue( + stackTrace.contains("com.alibaba.nacos.api.exception.runtime.NacosRuntimeException: errCode: 500, errMsg: Test")); assertTrue(stackTrace.contains("at")); assertTrue(stackTrace.contains("Caused by: java.lang.RuntimeException: I'm caused exception.")); } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/InetAddressValidatorTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/InetAddressValidatorTest.java index b85b89a89b0..3b614b3844f 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/InetAddressValidatorTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/InetAddressValidatorTest.java @@ -16,46 +16,49 @@ package com.alibaba.nacos.common.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; /** * InetAddressValidator Test. + * * @ClassName: InetAddressValidatorTest * @Author: ChenHao26 * @Date: 2022/8/22 13:07 */ -public class InetAddressValidatorTest { +class InetAddressValidatorTest { @Test - public void isIPv6Address() { - Assert.assertTrue(InetAddressValidator.isIPv6Address("2000:0000:0000:0000:0001:2345:6789:abcd")); - Assert.assertTrue(InetAddressValidator.isIPv6Address("2001:DB8:0:0:8:800:200C:417A")); - Assert.assertTrue(InetAddressValidator.isIPv6Address("2001:DB8::8:800:200C:417A")); - Assert.assertFalse(InetAddressValidator.isIPv6Address("2001:DB8::8:800:200C141aA")); + void isIPv6Address() { + assertTrue(InetAddressValidator.isIPv6Address("2000:0000:0000:0000:0001:2345:6789:abcd")); + assertTrue(InetAddressValidator.isIPv6Address("2001:DB8:0:0:8:800:200C:417A")); + assertTrue(InetAddressValidator.isIPv6Address("2001:DB8::8:800:200C:417A")); + assertFalse(InetAddressValidator.isIPv6Address("2001:DB8::8:800:200C141aA")); } @Test - public void isIPv6MixedAddress() { - Assert.assertTrue(InetAddressValidator.isIPv6MixedAddress("1:0:0:0:0:0:172.12.55.18")); - Assert.assertTrue(InetAddressValidator.isIPv6MixedAddress("::172.12.55.18")); - Assert.assertFalse(InetAddressValidator.isIPv6MixedAddress("2001:DB8::8:800:200C141aA")); + void isIPv6MixedAddress() { + assertTrue(InetAddressValidator.isIPv6MixedAddress("1:0:0:0:0:0:172.12.55.18")); + assertTrue(InetAddressValidator.isIPv6MixedAddress("::172.12.55.18")); + assertFalse(InetAddressValidator.isIPv6MixedAddress("2001:DB8::8:800:200C141aA")); } @Test - public void isIPv6IPv4MappedAddress() { - Assert.assertFalse(InetAddressValidator.isIPv6IPv4MappedAddress(":ffff:1.1.1.1")); - Assert.assertTrue(InetAddressValidator.isIPv6IPv4MappedAddress("::FFFF:192.168.1.2")); + void isIPv6IPv4MappedAddress() { + assertFalse(InetAddressValidator.isIPv6IPv4MappedAddress(":ffff:1.1.1.1")); + assertTrue(InetAddressValidator.isIPv6IPv4MappedAddress("::FFFF:192.168.1.2")); } @Test - public void isIPv4Address() { - Assert.assertTrue(InetAddressValidator.isIPv4Address("192.168.1.2")); + void isIPv4Address() { + assertTrue(InetAddressValidator.isIPv4Address("192.168.1.2")); } @Test - public void isLinkLocalIPv6WithZoneIndex() { - Assert.assertTrue(InetAddressValidator.isLinkLocalIPv6WithZoneIndex("fe80::1%lo0")); - Assert.assertFalse(InetAddressValidator.isLinkLocalIPv6WithZoneIndex("2000:0000:0000:0000:0001:2345:6789:abcd")); + void isLinkLocalIPv6WithZoneIndex() { + assertTrue(InetAddressValidator.isLinkLocalIPv6WithZoneIndex("fe80::1%lo0")); + assertFalse(InetAddressValidator.isLinkLocalIPv6WithZoneIndex("2000:0000:0000:0000:0001:2345:6789:abcd")); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/InternetAddressUtilTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/InternetAddressUtilTest.java index 8dd89895f89..c631898e49e 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/InternetAddressUtilTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/InternetAddressUtilTest.java @@ -16,12 +16,17 @@ package com.alibaba.nacos.common.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.lang.reflect.Modifier; +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; + /** * test IpUtil. * @@ -31,70 +36,90 @@ @SuppressWarnings("checkstyle:AbbreviationAsWordInName") public class InternetAddressUtilTest { + /** + * checkSplitIpPortStr. 2020/9/4 14:12 + * + * @param addr addr + * @param isEx isEx + * @param equalsStrs equalsStrs + */ + public static void checkSplitIPPortStr(String addr, boolean isEx, String... equalsStrs) { + try { + String[] array = InternetAddressUtil.splitIPPortStr(addr); + assertEquals(array.length, equalsStrs.length); + for (int i = 0; i < array.length; i++) { + assertEquals(array[i], equalsStrs[i]); + } + } catch (Exception ex) { + if (!isEx) { + // No exception is expected here, but an exception has occurred + fail("Unexpected exception"); + } + } + } + @Test - public void testIsIPv4() { - Assert.assertTrue(InternetAddressUtil.isIPv4("127.0.0.1")); - Assert.assertFalse(InternetAddressUtil.isIPv4("[::1]")); - Assert.assertFalse(InternetAddressUtil.isIPv4("asdfasf")); - Assert.assertFalse(InternetAddressUtil.isIPv4("ffgertert")); - Assert.assertFalse(InternetAddressUtil.isIPv4("127.100.19")); + void testIsIPv4() { + assertTrue(InternetAddressUtil.isIPv4("127.0.0.1")); + assertFalse(InternetAddressUtil.isIPv4("[::1]")); + assertFalse(InternetAddressUtil.isIPv4("asdfasf")); + assertFalse(InternetAddressUtil.isIPv4("ffgertert")); + assertFalse(InternetAddressUtil.isIPv4("127.100.19")); } @Test - public void testIsIPv6() { - Assert.assertTrue(InternetAddressUtil.isIPv6("[::1]")); - Assert.assertFalse(InternetAddressUtil.isIPv6("127.0.0.1")); - Assert.assertFalse(InternetAddressUtil.isIPv6("er34234")); + void testIsIPv6() { + assertTrue(InternetAddressUtil.isIPv6("[::1]")); + assertFalse(InternetAddressUtil.isIPv6("127.0.0.1")); + assertFalse(InternetAddressUtil.isIPv6("er34234")); } @Test - public void testIsIP() { - Assert.assertTrue(InternetAddressUtil.isIP("[::1]")); - Assert.assertTrue(InternetAddressUtil.isIP("127.0.0.1")); - Assert.assertFalse(InternetAddressUtil.isIP("er34234")); - Assert.assertFalse(InternetAddressUtil.isIP("127.100.19")); + void testIsIP() { + assertTrue(InternetAddressUtil.isIP("[::1]")); + assertTrue(InternetAddressUtil.isIP("127.0.0.1")); + assertFalse(InternetAddressUtil.isIP("er34234")); + assertFalse(InternetAddressUtil.isIP("127.100.19")); } @Test - public void testGetIPFromString() { - Assert.assertEquals("[::1]", - InternetAddressUtil.getIPFromString("http://[::1]:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3")); - Assert.assertEquals("[::1]", InternetAddressUtil.getIPFromString( + void testGetIPFromString() { + assertEquals("[::1]", InternetAddressUtil.getIPFromString("http://[::1]:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3")); + assertEquals("[::1]", InternetAddressUtil.getIPFromString( "jdbc:mysql://[::1]:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000" + "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC")); - Assert.assertEquals("127.0.0.1", + assertEquals("127.0.0.1", InternetAddressUtil.getIPFromString("http://127.0.0.1:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3")); - Assert.assertEquals("127.0.0.1", InternetAddressUtil.getIPFromString( + assertEquals("127.0.0.1", InternetAddressUtil.getIPFromString( "jdbc:mysql://127.0.0.1:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000" + "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC")); - Assert.assertEquals("", InternetAddressUtil.getIPFromString("http://[::1:666")); + assertEquals("", InternetAddressUtil.getIPFromString("http://[::1:666")); - Assert.assertEquals("", - InternetAddressUtil.getIPFromString("http://[dddd]:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3")); - Assert.assertEquals("", InternetAddressUtil.getIPFromString( + assertEquals("", InternetAddressUtil.getIPFromString("http://[dddd]:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3")); + assertEquals("", InternetAddressUtil.getIPFromString( "jdbc:mysql://[127.0.0.1]:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000" + "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC")); - Assert.assertEquals("", InternetAddressUtil.getIPFromString( + assertEquals("", InternetAddressUtil.getIPFromString( "jdbc:mysql://666.288.333.444:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000" + "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC")); - Assert.assertEquals("", InternetAddressUtil.getIPFromString( + assertEquals("", InternetAddressUtil.getIPFromString( "jdbc:mysql://292.168.1.1:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000" + "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC")); - Assert.assertEquals("", InternetAddressUtil.getIPFromString( + assertEquals("", InternetAddressUtil.getIPFromString( "jdbc:mysql://29.168.1.288:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000" + "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC")); - Assert.assertEquals("", InternetAddressUtil.getIPFromString( + assertEquals("", InternetAddressUtil.getIPFromString( "jdbc:mysql://29.168.288.28:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000" + "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC")); - Assert.assertEquals("", InternetAddressUtil.getIPFromString( + assertEquals("", InternetAddressUtil.getIPFromString( "jdbc:mysql://29.288.28.28:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000" + "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC")); - Assert.assertEquals("", InternetAddressUtil.getIPFromString("")); - Assert.assertEquals("", InternetAddressUtil.getIPFromString(null)); + assertEquals("", InternetAddressUtil.getIPFromString("")); + assertEquals("", InternetAddressUtil.getIPFromString(null)); } @Test - public void testSplitIpPort() { + void testSplitIpPort() { checkSplitIPPortStr("[::1]:88", false, "[::1]", "88"); checkSplitIPPortStr("[::1]", false, "[::1]"); checkSplitIPPortStr("127.0.0.1:88", false, "127.0.0.1", "88"); @@ -121,48 +146,48 @@ public void testSplitIpPort() { } @Test - public void testCheckIPs() { - Assert.assertEquals("ok", InternetAddressUtil.checkIPs("127.0.0.1")); - Assert.assertEquals("ok", InternetAddressUtil.checkIPs()); - Assert.assertEquals("ok", InternetAddressUtil.checkIPs()); - Assert.assertEquals("ok", InternetAddressUtil.checkIPs(null)); + void testCheckIPs() { + assertEquals("ok", InternetAddressUtil.checkIPs("127.0.0.1")); + assertEquals("ok", InternetAddressUtil.checkIPs()); + assertEquals("ok", InternetAddressUtil.checkIPs()); + assertEquals("ok", InternetAddressUtil.checkIPs(null)); - Assert.assertEquals("illegal ip: 127.100.19", InternetAddressUtil.checkIPs("127.100.19", "127.0.0.1")); + assertEquals("illegal ip: 127.100.19", InternetAddressUtil.checkIPs("127.100.19", "127.0.0.1")); } @Test - public void testIsDomain() { - Assert.assertTrue(InternetAddressUtil.isDomain("localhost")); - Assert.assertTrue(InternetAddressUtil.isDomain("github.com")); - Assert.assertTrue(InternetAddressUtil.isDomain("prefix.infix.suffix")); - Assert.assertTrue(InternetAddressUtil.isDomain("p-hub.com")); + void testIsDomain() { + assertTrue(InternetAddressUtil.isDomain("localhost")); + assertTrue(InternetAddressUtil.isDomain("github.com")); + assertTrue(InternetAddressUtil.isDomain("prefix.infix.suffix")); + assertTrue(InternetAddressUtil.isDomain("p-hub.com")); - Assert.assertFalse(InternetAddressUtil.isDomain("")); - Assert.assertFalse(InternetAddressUtil.isDomain(null)); + assertFalse(InternetAddressUtil.isDomain("")); + assertFalse(InternetAddressUtil.isDomain(null)); } @Test - public void testRemoveBrackets() { - Assert.assertEquals(InternetAddressUtil.removeBrackets("[2001:DB8:0:0:1::1]"), "2001:DB8:0:0:1::1"); - Assert.assertEquals(InternetAddressUtil.removeBrackets("[2077[]]]"), "2077"); - Assert.assertEquals(InternetAddressUtil.removeBrackets(""), ""); - Assert.assertEquals(InternetAddressUtil.removeBrackets(null), ""); + void testRemoveBrackets() { + assertEquals("2001:DB8:0:0:1::1", InternetAddressUtil.removeBrackets("[2001:DB8:0:0:1::1]")); + assertEquals("2077", InternetAddressUtil.removeBrackets("[2077[]]]")); + assertEquals("", InternetAddressUtil.removeBrackets("")); + assertEquals("", InternetAddressUtil.removeBrackets(null)); } @Test - public void testCheckOk() { - Assert.assertTrue(InternetAddressUtil.checkOK("ok")); - Assert.assertFalse(InternetAddressUtil.checkOK("ojbk")); + void testCheckOk() { + assertTrue(InternetAddressUtil.checkOK("ok")); + assertFalse(InternetAddressUtil.checkOK("ojbk")); } @Test - public void testContainsPort() { - Assert.assertTrue(InternetAddressUtil.containsPort("127.0.0.1:80")); - Assert.assertFalse(InternetAddressUtil.containsPort("127.0.0.1:80:80")); + void testContainsPort() { + assertTrue(InternetAddressUtil.containsPort("127.0.0.1:80")); + assertFalse(InternetAddressUtil.containsPort("127.0.0.1:80:80")); } @Test - public void testLocalHostIP() throws NoSuchFieldException, IllegalAccessException { + void testLocalHostIP() throws NoSuchFieldException, IllegalAccessException { Field field = InternetAddressUtil.class.getField("PREFER_IPV6_ADDRESSES"); field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); @@ -170,43 +195,23 @@ public void testLocalHostIP() throws NoSuchFieldException, IllegalAccessExceptio modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(null, false); - Assert.assertEquals("127.0.0.1", InternetAddressUtil.localHostIP()); + assertEquals("127.0.0.1", InternetAddressUtil.localHostIP()); field.set(null, true); - Assert.assertEquals("[::1]", InternetAddressUtil.localHostIP()); + assertEquals("[::1]", InternetAddressUtil.localHostIP()); } @Test - public void testIpToInt() { - Assert.assertEquals(2130706433, InternetAddressUtil.ipToInt("127.0.0.1")); - Assert.assertEquals(-1062731775, InternetAddressUtil.ipToInt("192.168.0.1")); + void testIpToInt() { + assertEquals(2130706433, InternetAddressUtil.ipToInt("127.0.0.1")); + assertEquals(-1062731775, InternetAddressUtil.ipToInt("192.168.0.1")); } - @Test(expected = IllegalArgumentException.class) - public void testIllegalIpToInt() { - InternetAddressUtil.ipToInt("127.0.0.256"); - } - - /** - * checkSplitIpPortStr. 2020/9/4 14:12 - * - * @param addr addr - * @param isEx isEx - * @param equalsStrs equalsStrs - */ - public static void checkSplitIPPortStr(String addr, boolean isEx, String... equalsStrs) { - try { - String[] array = InternetAddressUtil.splitIPPortStr(addr); - Assert.assertEquals(array.length, equalsStrs.length); - for (int i = 0; i < array.length; i++) { - Assert.assertEquals(array[i], equalsStrs[i]); - } - } catch (Exception ex) { - if (!isEx) { - // No exception is expected here, but an exception has occurred - Assert.fail("Unexpected exception"); - } - } + @Test + void testIllegalIpToInt() { + assertThrows(IllegalArgumentException.class, () -> { + InternetAddressUtil.ipToInt("127.0.0.256"); + }); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/IoUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/IoUtilsTest.java index 667c4d008e1..dc195dc00fb 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/IoUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/IoUtilsTest.java @@ -17,8 +17,7 @@ package com.alibaba.nacos.common.utils; import org.apache.commons.io.Charsets; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import sun.security.action.GetPropertyAction; import java.io.BufferedReader; @@ -33,6 +32,12 @@ import java.security.AccessController; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -42,35 +47,35 @@ * * @author karsonto */ -public class IoUtilsTest { +class IoUtilsTest { @Test - public void testTryDecompressForNotGzip() throws Exception { + void testTryDecompressForNotGzip() throws Exception { byte[] testCase = "123".getBytes(Charsets.toCharset("UTF-8")); - Assert.assertEquals(testCase, IoUtils.tryDecompress(testCase)); + assertEquals(testCase, IoUtils.tryDecompress(testCase)); } @Test - public void testTryDecompressForGzip() throws Exception { + void testTryDecompressForGzip() throws Exception { byte[] testCase = IoUtils.tryCompress("123", "UTF-8"); - Assert.assertEquals("123", new String(IoUtils.tryDecompress(testCase), StandardCharsets.UTF_8)); + assertEquals("123", new String(IoUtils.tryDecompress(testCase), StandardCharsets.UTF_8)); } @Test - public void testTryCompressWithEmptyString() { - Assert.assertEquals(0, IoUtils.tryCompress("", "UTF-8").length); - Assert.assertEquals(0, IoUtils.tryCompress(null, "UTF-8").length); + void testTryCompressWithEmptyString() { + assertEquals(0, IoUtils.tryCompress("", "UTF-8").length); + assertEquals(0, IoUtils.tryCompress(null, "UTF-8").length); } @Test - public void testWriteStringToFile() throws IOException { + void testWriteStringToFile() throws IOException { File file = null; try { file = File.createTempFile("test_writeStringToFile", ".txt"); IoUtils.writeStringToFile(file, "123", "UTF-8"); List actual = IoUtils.readLines(new FileReader(file)); - Assert.assertEquals(1, actual.size()); - Assert.assertEquals("123", actual.get(0)); + assertEquals(1, actual.size()); + assertEquals("123", actual.get(0)); } finally { if (null != file) { file.deleteOnExit(); @@ -79,30 +84,30 @@ public void testWriteStringToFile() throws IOException { } @Test - public void testToStringWithNull() throws IOException { - Assert.assertEquals("", IoUtils.toString(null, "UTF-8")); + void testToStringWithNull() throws IOException { + assertEquals("", IoUtils.toString(null, "UTF-8")); } @Test - public void testToStringWithReader() throws IOException { + void testToStringWithReader() throws IOException { String testCase = "123"; - Assert.assertEquals(testCase, + assertEquals(testCase, IoUtils.toString(new ByteArrayInputStream(testCase.getBytes(Charsets.toCharset("UTF-8"))), "UTF-8")); } @Test - public void testDeleteForNullFile() throws IOException { + void testDeleteForNullFile() throws IOException { IoUtils.delete(null); } @Test - public void testDeleteSuccess() throws IOException { + void testDeleteSuccess() throws IOException { File file = null; try { file = File.createTempFile("test_deleteForFile", ".txt"); - Assert.assertTrue(file.exists()); + assertTrue(file.exists()); IoUtils.delete(file); - Assert.assertFalse(file.exists()); + assertFalse(file.exists()); } finally { if (null != file) { file.deleteOnExit(); @@ -110,26 +115,28 @@ public void testDeleteSuccess() throws IOException { } } - @Test(expected = IOException.class) - public void testDeleteFileFailure() throws IOException { - File file = mock(File.class); - when(file.exists()).thenReturn(true); - when(file.delete()).thenReturn(false); - IoUtils.delete(file); + @Test + void testDeleteFileFailure() throws IOException { + assertThrows(IOException.class, () -> { + File file = mock(File.class); + when(file.exists()).thenReturn(true); + when(file.delete()).thenReturn(false); + IoUtils.delete(file); + }); } @Test - public void testDeleteForDirectory() throws IOException { + void testDeleteForDirectory() throws IOException { File file = null; try { String tmpDir = AccessController.doPrivileged(new GetPropertyAction("java.io.tmpdir")); File tmpDirFile = new File(tmpDir, "IoUtilsTest"); tmpDirFile.mkdirs(); file = File.createTempFile("test_deleteForDirectory", ".txt", tmpDirFile); - Assert.assertTrue(file.exists()); + assertTrue(file.exists()); IoUtils.delete(file.getParentFile()); - Assert.assertTrue(tmpDirFile.exists()); - Assert.assertFalse(file.exists()); + assertTrue(tmpDirFile.exists()); + assertFalse(file.exists()); } finally { if (null != file) { file.getParentFile().deleteOnExit(); @@ -138,88 +145,96 @@ public void testDeleteForDirectory() throws IOException { } } - @Test(expected = IllegalArgumentException.class) - public void testCleanDirectoryForNonExistingDirectory() throws IOException { - File nonexistentDir = new File("non_exist"); - IoUtils.cleanDirectory(nonexistentDir); + @Test + void testCleanDirectoryForNonExistingDirectory() throws IOException { + assertThrows(IllegalArgumentException.class, () -> { + File nonexistentDir = new File("non_exist"); + IoUtils.cleanDirectory(nonexistentDir); + }); } - @Test(expected = IllegalArgumentException.class) - public void testCleanDirectoryForFile() throws IOException { - File mockFile = mock(File.class); - when(mockFile.exists()).thenReturn(true); - IoUtils.cleanDirectory(mockFile); + @Test + void testCleanDirectoryForFile() throws IOException { + assertThrows(IllegalArgumentException.class, () -> { + File mockFile = mock(File.class); + when(mockFile.exists()).thenReturn(true); + IoUtils.cleanDirectory(mockFile); + }); } - @Test(expected = IOException.class) - public void testCleanDirectoryWithEmptyDirectory() throws IOException { - File mockFile = mock(File.class); - when(mockFile.exists()).thenReturn(true); - when(mockFile.isDirectory()).thenReturn(true); - IoUtils.cleanDirectory(mockFile); + @Test + void testCleanDirectoryWithEmptyDirectory() throws IOException { + assertThrows(IOException.class, () -> { + File mockFile = mock(File.class); + when(mockFile.exists()).thenReturn(true); + when(mockFile.isDirectory()).thenReturn(true); + IoUtils.cleanDirectory(mockFile); + }); } - @Test(expected = IOException.class) - public void testCleanDirectory() throws IOException { - File mockFile = mock(File.class); - when(mockFile.exists()).thenReturn(true); - when(mockFile.isDirectory()).thenReturn(true); - File mockSubFile = mock(File.class); - when(mockSubFile.exists()).thenReturn(true); - when(mockFile.listFiles()).thenReturn(new File[] {mockSubFile}); - IoUtils.cleanDirectory(mockFile); + @Test + void testCleanDirectory() throws IOException { + assertThrows(IOException.class, () -> { + File mockFile = mock(File.class); + when(mockFile.exists()).thenReturn(true); + when(mockFile.isDirectory()).thenReturn(true); + File mockSubFile = mock(File.class); + when(mockSubFile.exists()).thenReturn(true); + when(mockFile.listFiles()).thenReturn(new File[] {mockSubFile}); + IoUtils.cleanDirectory(mockFile); + }); } @Test - public void testIsGzipStreamWithNull() { - Assert.assertFalse(IoUtils.isGzipStream(null)); + void testIsGzipStreamWithNull() { + assertFalse(IoUtils.isGzipStream(null)); } @Test - public void testIsGzipStreamWithEmpty() { - Assert.assertFalse(IoUtils.isGzipStream(new byte[0])); + void testIsGzipStreamWithEmpty() { + assertFalse(IoUtils.isGzipStream(new byte[0])); } - @Test() - public void testCloseQuietly() throws IOException { + @Test + void testCloseQuietly() throws IOException { BufferedReader br = new BufferedReader( new InputStreamReader(new ByteArrayInputStream("111".getBytes(Charsets.toCharset("UTF-8"))))); - Assert.assertEquals("111", br.readLine()); + assertEquals("111", br.readLine()); IoUtils.closeQuietly(br); try { br.readLine(); } catch (IOException e) { - Assert.assertNotNull(e); + assertNotNull(e); return; } - Assert.fail(); + fail(); } - @Test() - public void testCloseQuietly2() throws IOException { + @Test + void testCloseQuietly2() throws IOException { BufferedReader br = new BufferedReader( new InputStreamReader(new ByteArrayInputStream("123".getBytes(Charsets.toCharset("UTF-8"))))); - Assert.assertEquals("123", br.readLine()); + assertEquals("123", br.readLine()); BufferedReader br2 = new BufferedReader( new InputStreamReader(new ByteArrayInputStream("456".getBytes(Charsets.toCharset("UTF-8"))))); - Assert.assertEquals("456", br2.readLine()); + assertEquals("456", br2.readLine()); IoUtils.closeQuietly(br, br2); try { br.readLine(); } catch (IOException e) { - Assert.assertNotNull(e); + assertNotNull(e); } try { br2.readLine(); } catch (IOException e) { - Assert.assertNotNull(e); + assertNotNull(e); return; } - Assert.fail(); + fail(); } @Test - public void testCloseQuietlyForHttpConnection() throws IOException { + void testCloseQuietlyForHttpConnection() throws IOException { HttpURLConnection conn = mock(HttpURLConnection.class); InputStream inputStream = mock(InputStream.class); when(conn.getInputStream()).thenReturn(inputStream); diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/JacksonUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/JacksonUtilsTest.java index 5c593be1695..9e08c062edf 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/JacksonUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/JacksonUtilsTest.java @@ -29,8 +29,7 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.InputStream; @@ -45,154 +44,161 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; -public class JacksonUtilsTest { +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +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 JacksonUtilsTest { @Test - public void testToJson1() { - Assert.assertEquals("null", JacksonUtils.toJson(null)); - Assert.assertEquals("\"string\"", JacksonUtils.toJson("string")); - Assert.assertEquals("30", JacksonUtils.toJson(new BigDecimal(30))); - Assert.assertEquals("{\"key\":\"value\"}", JacksonUtils.toJson(Collections.singletonMap("key", "value"))); - Assert.assertEquals("[{\"key\":\"value\"}]", + void testToJson1() { + assertEquals("null", JacksonUtils.toJson(null)); + assertEquals("\"string\"", JacksonUtils.toJson("string")); + assertEquals("30", JacksonUtils.toJson(new BigDecimal(30))); + assertEquals("{\"key\":\"value\"}", JacksonUtils.toJson(Collections.singletonMap("key", "value"))); + assertEquals("[{\"key\":\"value\"}]", JacksonUtils.toJson(Collections.singletonList(Collections.singletonMap("key", "value")))); - Assert.assertEquals("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}", - JacksonUtils.toJson(new TestOfAtomicObject())); - Assert.assertEquals("{\"date\":1626192000000}", JacksonUtils.toJson(new TestOfDate())); + assertEquals("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}", JacksonUtils.toJson(new TestOfAtomicObject())); + assertEquals("{\"date\":1626192000000}", JacksonUtils.toJson(new TestOfDate())); // only public - Assert.assertEquals("{\"publicAccessModifier\":\"public\"}", JacksonUtils.toJson(new TestOfAccessModifier())); + assertEquals("{\"publicAccessModifier\":\"public\"}", JacksonUtils.toJson(new TestOfAccessModifier())); // getter is also recognized - Assert.assertEquals("{\"value\":\"value\",\"key\":\"key\"}", JacksonUtils.toJson(new TestOfGetter())); + assertEquals("{\"value\":\"value\",\"key\":\"key\"}", JacksonUtils.toJson(new TestOfGetter())); // annotation available - Assert.assertEquals( + assertEquals( "{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\",\"subField\":\"subField\"," + "\"camelCase\":\"value\"}", JacksonUtils.toJson(new TestOfAnnotationSub())); } - @Test(expected = NacosSerializationException.class) - public void testToJson2() { - // object without field will throw exceptions - JacksonUtils.toJson(new Object()); + @Test + void testToJson2() { + assertThrows(NacosSerializationException.class, () -> { + // object without field will throw exceptions + JacksonUtils.toJson(new Object()); + }); } @Test - public void testToJsonBytes1() { - Assert.assertArrayEquals("null".getBytes(), JacksonUtils.toJsonBytes(null)); - Assert.assertArrayEquals("\"string\"".getBytes(), JacksonUtils.toJsonBytes("string")); - Assert.assertArrayEquals("30".getBytes(), JacksonUtils.toJsonBytes(new BigDecimal(30))); - Assert.assertArrayEquals("{\"key\":\"value\"}".getBytes(), - JacksonUtils.toJsonBytes(Collections.singletonMap("key", "value"))); - Assert.assertArrayEquals("[{\"key\":\"value\"}]".getBytes(), + void testToJsonBytes1() { + assertArrayEquals("null".getBytes(), JacksonUtils.toJsonBytes(null)); + assertArrayEquals("\"string\"".getBytes(), JacksonUtils.toJsonBytes("string")); + assertArrayEquals("30".getBytes(), JacksonUtils.toJsonBytes(new BigDecimal(30))); + assertArrayEquals("{\"key\":\"value\"}".getBytes(), JacksonUtils.toJsonBytes(Collections.singletonMap("key", "value"))); + assertArrayEquals("[{\"key\":\"value\"}]".getBytes(), JacksonUtils.toJsonBytes(Collections.singletonList(Collections.singletonMap("key", "value")))); - Assert.assertArrayEquals("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes(), + assertArrayEquals("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes(), JacksonUtils.toJsonBytes(new TestOfAtomicObject())); - Assert.assertArrayEquals("{\"date\":1626192000000}".getBytes(), JacksonUtils.toJsonBytes(new TestOfDate())); + assertArrayEquals("{\"date\":1626192000000}".getBytes(), JacksonUtils.toJsonBytes(new TestOfDate())); // only public - Assert.assertArrayEquals("{\"publicAccessModifier\":\"public\"}".getBytes(), + assertArrayEquals("{\"publicAccessModifier\":\"public\"}".getBytes(), JacksonUtils.toJsonBytes(new TestOfAccessModifier())); // getter is also recognized - Assert.assertArrayEquals("{\"value\":\"value\",\"key\":\"key\"}".getBytes(), - JacksonUtils.toJsonBytes(new TestOfGetter())); + assertArrayEquals("{\"value\":\"value\",\"key\":\"key\"}".getBytes(), JacksonUtils.toJsonBytes(new TestOfGetter())); // annotation available - Assert.assertArrayEquals( + assertArrayEquals( ("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\",\"subField\":\"subField\"," + "\"camelCase\":\"value\"}").getBytes(), JacksonUtils.toJsonBytes(new TestOfAnnotationSub())); } - @Test(expected = NacosSerializationException.class) - public void testToJsonBytes2() { - // object without field will throw exceptions - JacksonUtils.toJsonBytes(new Object()); + @Test + void testToJsonBytes2() { + assertThrows(NacosSerializationException.class, () -> { + // object without field will throw exceptions + JacksonUtils.toJsonBytes(new Object()); + }); } /** * JacksonUtils.toObj(byte[], Class) */ @Test - public void testToObject1() { - Assert.assertNull(JacksonUtils.toObj("null".getBytes(), Object.class)); - Assert.assertEquals("string", JacksonUtils.toObj("\"string\"".getBytes(), String.class)); - Assert.assertEquals(new BigDecimal(30), JacksonUtils.toObj("30".getBytes(), BigDecimal.class)); - Assert.assertEquals(Collections.singletonMap("key", "value"), - JacksonUtils.toObj("{\"key\":\"value\"}".getBytes(), Map.class)); - Assert.assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")), + void testToObject1() { + assertNull(JacksonUtils.toObj("null".getBytes(), Object.class)); + assertEquals("string", JacksonUtils.toObj("\"string\"".getBytes(), String.class)); + assertEquals(new BigDecimal(30), JacksonUtils.toObj("30".getBytes(), BigDecimal.class)); + assertEquals(Collections.singletonMap("key", "value"), JacksonUtils.toObj("{\"key\":\"value\"}".getBytes(), Map.class)); + assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")), JacksonUtils.toObj("[{\"key\":\"value\"}]".getBytes(), List.class)); - Assert.assertEquals(new TestOfAtomicObject(), JacksonUtils - .toObj("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes(), TestOfAtomicObject.class)); - Assert.assertEquals(new TestOfDate(), - JacksonUtils.toObj("{\"date\":1626192000000}".getBytes(), TestOfDate.class)); - Assert.assertEquals(new TestOfAccessModifier(), + assertEquals(new TestOfAtomicObject(), + JacksonUtils.toObj("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes(), TestOfAtomicObject.class)); + assertEquals(new TestOfDate(), JacksonUtils.toObj("{\"date\":1626192000000}".getBytes(), TestOfDate.class)); + assertEquals(new TestOfAccessModifier(), JacksonUtils.toObj("{\"publicAccessModifier\":\"public\"}".getBytes(), TestOfAccessModifier.class)); - Assert.assertEquals(new TestOfGetter(), + assertEquals(new TestOfGetter(), JacksonUtils.toObj("{\"value\":\"value\",\"key\":\"key\"}".getBytes(), TestOfGetter.class)); - Assert.assertEquals(new TestOfAnnotationSub(), JacksonUtils - .toObj(("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\"," + assertEquals(new TestOfAnnotationSub(), JacksonUtils.toObj( + ("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\"," + "\"subField\":\"subField\",\"camelCase\":\"value\"}").getBytes(), TestOfAnnotation.class)); } /** * JacksonUtils.toObj(byte[], Class) */ - @Test(expected = Exception.class) - public void testToObject2() { - JacksonUtils.toObj(("{not_A}Json:String}").getBytes(), TestOfAnnotationSub.class); + @Test + void testToObject2() { + assertThrows(Exception.class, () -> { + JacksonUtils.toObj(("{not_A}Json:String}").getBytes(), TestOfAnnotationSub.class); + }); } /** * JacksonUtils.toObj(byte[], Type) */ @Test - public void testToObject3() { - Assert.assertEquals(Collections.singletonMap("key", "value"), JacksonUtils - .toObj("{\"key\":\"value\"}".getBytes(), - TypeUtils.parameterize(Map.class, String.class, String.class))); - Assert.assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")), JacksonUtils - .toObj("[{\"key\":\"value\"}]".getBytes(), TypeUtils - .parameterize(List.class, TypeUtils.parameterize(Map.class, String.class, String.class)))); + void testToObject3() { + assertEquals(Collections.singletonMap("key", "value"), JacksonUtils.toObj("{\"key\":\"value\"}".getBytes(), + TypeUtils.parameterize(Map.class, String.class, String.class))); + assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")), + JacksonUtils.toObj("[{\"key\":\"value\"}]".getBytes(), + TypeUtils.parameterize(List.class, TypeUtils.parameterize(Map.class, String.class, String.class)))); } /** * JacksonUtils.toObj(byte[], Type) */ - @Test(expected = Exception.class) - public void testToObject4() { - JacksonUtils - .toObj("{not_A}Json:String}".getBytes(), TypeUtils.parameterize(Map.class, String.class, String.class)); + @Test + void testToObject4() { + assertThrows(Exception.class, () -> { + JacksonUtils.toObj("{not_A}Json:String}".getBytes(), TypeUtils.parameterize(Map.class, String.class, String.class)); + }); } /** * JacksonUtils.toObj(byte[], Type) */ - @Test(expected = Exception.class) - public void testToObject5() { - JacksonUtils.toObj("{\"key\":\"value\"}".getBytes(), Object.class.getGenericSuperclass()); + @Test + void testToObject5() { + assertThrows(Exception.class, () -> { + JacksonUtils.toObj("{\"key\":\"value\"}".getBytes(), Object.class.getGenericSuperclass()); + }); } /** * JacksonUtils.toObj(InputStream, Class) */ @Test - public void testToObject6() { - Assert.assertNull(JacksonUtils.toObj(new ByteArrayInputStream("null".getBytes()), Object.class)); - Assert.assertEquals("string", - JacksonUtils.toObj(new ByteArrayInputStream("\"string\"".getBytes()), String.class)); - Assert.assertEquals(new BigDecimal(30), - JacksonUtils.toObj(new ByteArrayInputStream("30".getBytes()), BigDecimal.class)); - Assert.assertEquals(Collections.singletonMap("key", "value"), + void testToObject6() { + assertNull(JacksonUtils.toObj(new ByteArrayInputStream("null".getBytes()), Object.class)); + assertEquals("string", JacksonUtils.toObj(new ByteArrayInputStream("\"string\"".getBytes()), String.class)); + assertEquals(new BigDecimal(30), JacksonUtils.toObj(new ByteArrayInputStream("30".getBytes()), BigDecimal.class)); + assertEquals(Collections.singletonMap("key", "value"), JacksonUtils.toObj(new ByteArrayInputStream("{\"key\":\"value\"}".getBytes()), Map.class)); - Assert.assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")), + assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")), JacksonUtils.toObj(new ByteArrayInputStream("[{\"key\":\"value\"}]".getBytes()), List.class)); - Assert.assertEquals(new TestOfAtomicObject(), JacksonUtils - .toObj(new ByteArrayInputStream("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes()), + assertEquals(new TestOfAtomicObject(), + JacksonUtils.toObj(new ByteArrayInputStream("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes()), TestOfAtomicObject.class)); - Assert.assertEquals(new TestOfDate(), + assertEquals(new TestOfDate(), JacksonUtils.toObj(new ByteArrayInputStream("{\"date\":1626192000000}".getBytes()), TestOfDate.class)); - Assert.assertEquals(new TestOfAccessModifier(), JacksonUtils - .toObj(new ByteArrayInputStream("{\"publicAccessModifier\":\"public\"}".getBytes()), + assertEquals(new TestOfAccessModifier(), + JacksonUtils.toObj(new ByteArrayInputStream("{\"publicAccessModifier\":\"public\"}".getBytes()), TestOfAccessModifier.class)); - Assert.assertEquals(new TestOfGetter(), JacksonUtils - .toObj(new ByteArrayInputStream("{\"value\":\"value\",\"key\":\"key\"}".getBytes()), + assertEquals(new TestOfGetter(), + JacksonUtils.toObj(new ByteArrayInputStream("{\"value\":\"value\",\"key\":\"key\"}".getBytes()), TestOfGetter.class)); - Assert.assertEquals(new TestOfAnnotationSub(), JacksonUtils.toObj((new ByteArrayInputStream( + assertEquals(new TestOfAnnotationSub(), JacksonUtils.toObj((new ByteArrayInputStream( ("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\"," + "\"date\":\"2021-07-14\",\"subField\":\"subField\",\"camelCase\":\"value\"}").getBytes())), TestOfAnnotation.class)); @@ -201,62 +207,66 @@ public void testToObject6() { /** * JacksonUtils.toObj(InputStream, Class) */ - @Test(expected = Exception.class) - public void testToObject7() { - JacksonUtils.toObj((ByteArrayInputStream) null, BigDecimal.class); + @Test + void testToObject7() { + assertThrows(Exception.class, () -> { + JacksonUtils.toObj((ByteArrayInputStream) null, BigDecimal.class); + }); } /** * JacksonUtils.toObj(InputStream, Class) */ - @Test(expected = Exception.class) - public void testToObject8() { - JacksonUtils.toObj(new ByteArrayInputStream("{not_A}Json:String}".getBytes()), Object.class); + @Test + void testToObject8() { + assertThrows(Exception.class, () -> { + JacksonUtils.toObj(new ByteArrayInputStream("{not_A}Json:String}".getBytes()), Object.class); + }); } /** * JacksonUtils.toObj(byte[], TypeReference) */ @Test - public void testToObject9() { - Assert.assertNull(JacksonUtils.toObj("null".getBytes(), new TypeReference() { + void testToObject9() { + assertNull(JacksonUtils.toObj("null".getBytes(), new TypeReference() { })); - Assert.assertEquals("string", JacksonUtils.toObj("\"string\"".getBytes(), new TypeReference() { + assertEquals("string", JacksonUtils.toObj("\"string\"".getBytes(), new TypeReference() { })); - Assert.assertEquals(new BigDecimal(30), JacksonUtils.toObj("30".getBytes(), new TypeReference() { + assertEquals(new BigDecimal(30), JacksonUtils.toObj("30".getBytes(), new TypeReference() { })); - Assert.assertEquals(Collections.singletonMap("key", "value"), + assertEquals(Collections.singletonMap("key", "value"), JacksonUtils.toObj("{\"key\":\"value\"}".getBytes(), new TypeReference>() { })); - Assert.assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")), + assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")), JacksonUtils.toObj("[{\"key\":\"value\"}]".getBytes(), new TypeReference>>() { })); - Assert.assertEquals(new TestOfAtomicObject(), JacksonUtils - .toObj("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes(), - new TypeReference() { - })); - Assert.assertEquals(new TestOfDate(), - JacksonUtils.toObj("{\"date\":1626192000000}".getBytes(), new TypeReference() { + assertEquals(new TestOfAtomicObject(), JacksonUtils.toObj("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}".getBytes(), + new TypeReference() { })); - Assert.assertEquals(new TestOfAccessModifier(), JacksonUtils - .toObj("{\"publicAccessModifier\":\"public\"}".getBytes(), new TypeReference() { + assertEquals(new TestOfDate(), JacksonUtils.toObj("{\"date\":1626192000000}".getBytes(), new TypeReference() { + })); + assertEquals(new TestOfAccessModifier(), + JacksonUtils.toObj("{\"publicAccessModifier\":\"public\"}".getBytes(), new TypeReference() { + })); + assertEquals(new TestOfGetter(), + JacksonUtils.toObj("{\"value\":\"value\",\"key\":\"key\"}".getBytes(), new TypeReference() { })); - Assert.assertEquals(new TestOfGetter(), JacksonUtils - .toObj("{\"value\":\"value\",\"key\":\"key\"}".getBytes(), new TypeReference() { + assertEquals(new TestOfAnnotationSub(), JacksonUtils.toObj( + ("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\"," + + "\"subField\":\"subField\",\"camelCase\":\"value\"}").getBytes(), + new TypeReference() { })); - Assert.assertEquals(new TestOfAnnotationSub(), JacksonUtils - .toObj(("{\"@type\":\"JacksonUtilsTest$TestOfAnnotationSub\",\"date\":\"2021-07-14\"," - + "\"subField\":\"subField\",\"camelCase\":\"value\"}").getBytes(), - new TypeReference() { - })); } /** * JacksonUtils.toObj(byte[], TypeReference) */ - @Test(expected = Exception.class) - public void testToObject10() { - JacksonUtils.toObj("{not_A}Json:String}".getBytes(), new TypeReference() { + @Test + void testToObject10() { + assertThrows(Exception.class, () -> { + JacksonUtils.toObj("{not_A}Json:String}".getBytes(), new TypeReference() { + }); }); } @@ -264,106 +274,113 @@ public void testToObject10() { * JacksonUtils.toObj(InputStream, Type) */ @Test - public void testToObject11() { - Assert.assertEquals(Collections.singletonMap("key", "value"), JacksonUtils - .toObj(new ByteArrayInputStream("{\"key\":\"value\"}".getBytes()), + void testToObject11() { + assertEquals(Collections.singletonMap("key", "value"), + JacksonUtils.toObj(new ByteArrayInputStream("{\"key\":\"value\"}".getBytes()), TypeUtils.parameterize(Map.class, String.class, String.class))); - Assert.assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")), JacksonUtils - .toObj(new ByteArrayInputStream("[{\"key\":\"value\"}]".getBytes()), TypeUtils - .parameterize(List.class, TypeUtils.parameterize(Map.class, String.class, String.class)))); + assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")), + JacksonUtils.toObj(new ByteArrayInputStream("[{\"key\":\"value\"}]".getBytes()), + TypeUtils.parameterize(List.class, TypeUtils.parameterize(Map.class, String.class, String.class)))); } /** * JacksonUtils.toObj(InputStream, Type) */ - @Test(expected = Exception.class) - public void testToObject12() { - JacksonUtils.toObj(new ByteArrayInputStream("{not_A}Json:String}".getBytes()), - TypeUtils.parameterize(Map.class, String.class, String.class)); + @Test + void testToObject12() { + assertThrows(Exception.class, () -> { + JacksonUtils.toObj(new ByteArrayInputStream("{not_A}Json:String}".getBytes()), + TypeUtils.parameterize(Map.class, String.class, String.class)); + }); } /** * JacksonUtils.toObj(InputStream, Type) */ - @Test(expected = Exception.class) - public void testToObject13() { - JacksonUtils - .toObj(new ByteArrayInputStream("{\"key\":\"value\"}".getBytes()), Object.class.getGenericSuperclass()); + @Test + void testToObject13() { + assertThrows(Exception.class, () -> { + JacksonUtils.toObj(new ByteArrayInputStream("{\"key\":\"value\"}".getBytes()), Object.class.getGenericSuperclass()); + }); } /** * JacksonUtils.toObj(InputStream, Type) */ - @Test(expected = Exception.class) - public void testToObject14() { - JacksonUtils.toObj((InputStream) null, Object.class.getGenericSuperclass()); + @Test + void testToObject14() { + assertThrows(Exception.class, () -> { + JacksonUtils.toObj((InputStream) null, Object.class.getGenericSuperclass()); + }); } /** * JacksonUtils.toObj(String) */ @Test - public void testToObject15() { - Assert.assertEquals("null", JacksonUtils.toObj("null").asText()); - Assert.assertEquals("string", JacksonUtils.toObj("\"string\"").asText()); - Assert.assertEquals(30, JacksonUtils.toObj("30").asInt()); - Assert.assertEquals("value", JacksonUtils.toObj("{\"key\":\"value\"}").get("key").asText()); - Assert.assertEquals("value", JacksonUtils.toObj("[{\"key\":\"value\"}]").get(0).get("key").asText()); + void testToObject15() { + assertEquals("null", JacksonUtils.toObj("null").asText()); + assertEquals("string", JacksonUtils.toObj("\"string\"").asText()); + assertEquals(30, JacksonUtils.toObj("30").asInt()); + assertEquals("value", JacksonUtils.toObj("{\"key\":\"value\"}").get("key").asText()); + assertEquals("value", JacksonUtils.toObj("[{\"key\":\"value\"}]").get(0).get("key").asText()); JsonNode jsonNode = JacksonUtils.toObj("{\"aLong\":0,\"aInteger\":1,\"aBoolean\":false}"); - Assert.assertEquals(0L, jsonNode.get("aLong").asLong()); - Assert.assertEquals(1, jsonNode.get("aInteger").asInt()); + assertEquals(0L, jsonNode.get("aLong").asLong()); + assertEquals(1, jsonNode.get("aInteger").asInt()); } /** * JacksonUtils.toObj(String) */ - @Test(expected = Exception.class) - public void testToObject16() { - JacksonUtils.toObj("{not_A}Json:String}"); + @Test + void testToObject16() { + assertThrows(Exception.class, () -> { + JacksonUtils.toObj("{not_A}Json:String}"); + }); } @Test - public void testRegisterSubtype() { + void testRegisterSubtype() { JacksonUtils.registerSubtype(TestOfChild.class, "JacksonUtilsTest$TestOfChild"); - Assert.assertEquals(new TestOfChild(), JacksonUtils - .toObj("{\"@type\":\"JacksonUtilsTest$TestOfChild\",\"parentField\":\"parentValue\"," - + "\"childField\":\"childValue\"}", TestOfParent.class)); + assertEquals(new TestOfChild(), JacksonUtils.toObj( + "{\"@type\":\"JacksonUtilsTest$TestOfChild\",\"parentField\":\"parentValue\"," + "\"childField\":\"childValue\"}", + TestOfParent.class)); } @Test - public void testCreateEmptyJsonNode() { - Assert.assertEquals("", JacksonUtils.createEmptyJsonNode().asText()); - Assert.assertTrue(JacksonUtils.createEmptyJsonNode().isEmpty()); + void testCreateEmptyJsonNode() { + assertEquals("", JacksonUtils.createEmptyJsonNode().asText()); + assertTrue(JacksonUtils.createEmptyJsonNode().isEmpty()); } @Test - public void testCreateEmptyArrayNode() { - Assert.assertEquals("", JacksonUtils.createEmptyJsonNode().asText()); - Assert.assertEquals(0, JacksonUtils.createEmptyArrayNode().size()); - Assert.assertTrue(JacksonUtils.createEmptyArrayNode().isEmpty()); + void testCreateEmptyArrayNode() { + assertEquals("", JacksonUtils.createEmptyJsonNode().asText()); + assertEquals(0, JacksonUtils.createEmptyArrayNode().size()); + assertTrue(JacksonUtils.createEmptyArrayNode().isEmpty()); } @Test - public void testTransferToJsonNode() { + void testTransferToJsonNode() { JsonNode jsonNode1 = JacksonUtils.transferToJsonNode(Collections.singletonMap("key", "value")); - Assert.assertEquals("value", jsonNode1.get("key").asText()); + assertEquals("value", jsonNode1.get("key").asText()); JsonNode jsonNode2 = JacksonUtils.transferToJsonNode(new TestOfAtomicObject()); - Assert.assertEquals("0", jsonNode2.get("aLong").asText()); - Assert.assertEquals("1", jsonNode2.get("aInteger").asText()); - Assert.assertEquals("false", jsonNode2.get("aBoolean").asText()); + assertEquals("0", jsonNode2.get("aLong").asText()); + assertEquals("1", jsonNode2.get("aInteger").asText()); + assertEquals("false", jsonNode2.get("aBoolean").asText()); } @Test - public void testConstructJavaType() { - Assert.assertEquals("java.lang.String", JacksonUtils.constructJavaType(String.class).getRawClass().getName()); - Assert.assertTrue(JacksonUtils.constructJavaType(String.class).isFinal()); + void testConstructJavaType() { + assertEquals("java.lang.String", JacksonUtils.constructJavaType(String.class).getRawClass().getName()); + assertTrue(JacksonUtils.constructJavaType(String.class).isFinal()); } @Test - public void testToJsonBytes() { + void testToJsonBytes() { Map map = new LinkedHashMap(); map.put("string", "你好,中国!"); map.put("integer", 999); @@ -372,8 +389,8 @@ public void testToJsonBytes() { byte[] bytes = JacksonUtils.toJsonBytes(restResult); String jsonFromBytes = ByteUtils.toString(bytes); - Assert.assertTrue(jsonFromBytes.contains("\"code\":0")); - Assert.assertTrue(jsonFromBytes.contains("\"data\":{\"string\":\"你好,中国!\",\"integer\":999}")); + assertTrue(jsonFromBytes.contains("\"code\":0")); + assertTrue(jsonFromBytes.contains("\"data\":{\"string\":\"你好,中国!\",\"integer\":999}")); // old `toJsonBytes` method implementation: // public static byte[] toJsonBytes(Object obj) { // try { @@ -385,41 +402,46 @@ public void testToJsonBytes() { // here is a verification to compare with the old implementation byte[] bytesFromOldImplementation = ByteUtils.toBytes(JacksonUtils.toJson(restResult)); - String jsonFromBytesOldImplementation = new String(bytesFromOldImplementation, - Charset.forName(Constants.ENCODE)); - Assert.assertTrue(jsonFromBytesOldImplementation.contains("\"code\":0")); - Assert.assertTrue(jsonFromBytesOldImplementation.contains("\"data\":{\"string\":\"你好,中国!\",\"integer\":999}")); + String jsonFromBytesOldImplementation = new String(bytesFromOldImplementation, Charset.forName(Constants.ENCODE)); + assertTrue(jsonFromBytesOldImplementation.contains("\"code\":0")); + assertTrue(jsonFromBytesOldImplementation.contains("\"data\":{\"string\":\"你好,中国!\",\"integer\":999}")); } @Test - public void testToObjFromBytes() { + void testToObjFromBytes() { String json = "{\"code\":0,\"data\":{\"string\":\"你好,中国!\",\"integer\":999}}"; RestResult> restResult = JacksonUtils.toObj(json, RestResult.class); - Assert.assertEquals(0, restResult.getCode()); - Assert.assertEquals("你好,中国!", restResult.getData().get("string")); - Assert.assertEquals(999, restResult.getData().get("integer")); + assertEquals(0, restResult.getCode()); + assertEquals("你好,中国!", restResult.getData().get("string")); + assertEquals(999, restResult.getData().get("integer")); restResult = JacksonUtils.toObj(json, new TypeReference>>() { }); - Assert.assertEquals(0, restResult.getCode()); - Assert.assertEquals("你好,中国!", restResult.getData().get("string")); - Assert.assertEquals(999, restResult.getData().get("integer")); + assertEquals(0, restResult.getCode()); + assertEquals("你好,中国!", restResult.getData().get("string")); + assertEquals(999, restResult.getData().get("integer")); } - @Test(expected = NacosDeserializationException.class) - public void tesToObjForClassWithException() { - JacksonUtils.toObj("aaa", JsonNode.class); + @Test + void tesToObjForClassWithException() { + assertThrows(NacosDeserializationException.class, () -> { + JacksonUtils.toObj("aaa", JsonNode.class); + }); } - @Test(expected = NacosDeserializationException.class) - public void tesToObjForTypeWithException() { - JacksonUtils.toObj("aaa", TypeUtils.parameterize(JsonNode.class)); + @Test + void tesToObjForTypeWithException() { + assertThrows(NacosDeserializationException.class, () -> { + JacksonUtils.toObj("aaa", TypeUtils.parameterize(JsonNode.class)); + }); } - @Test(expected = NacosDeserializationException.class) - public void tesToObjForTypeTypeReferenceWithException() { - JacksonUtils.toObj("aaa", new TypeReference() { + @Test + void tesToObjForTypeTypeReferenceWithException() { + assertThrows(NacosDeserializationException.class, () -> { + JacksonUtils.toObj("aaa", new TypeReference() { + }); }); } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/LoggerUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/LoggerUtilsTest.java index a7836ec617c..d4abde0ecf6 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/LoggerUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/LoggerUtilsTest.java @@ -16,14 +16,14 @@ package com.alibaba.nacos.common.utils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.slf4j.Logger; -public class LoggerUtilsTest { +class LoggerUtilsTest { @Test - public void testPrintIfDebugEnabled() { + void testPrintIfDebugEnabled() { Logger logger = Mockito.mock(Logger.class); Mockito.when(logger.isDebugEnabled()).thenReturn(true); LoggerUtils.printIfDebugEnabled(logger, "test", "arg1", "arg2", "arg3"); @@ -31,7 +31,7 @@ public void testPrintIfDebugEnabled() { } @Test - public void testPrintIfInfoEnabled() { + void testPrintIfInfoEnabled() { Logger logger = Mockito.mock(Logger.class); Mockito.when(logger.isInfoEnabled()).thenReturn(true); LoggerUtils.printIfInfoEnabled(logger, "test", "arg1", "arg2", "arg3"); @@ -39,7 +39,7 @@ public void testPrintIfInfoEnabled() { } @Test - public void testPrintIfTraceEnabled() { + void testPrintIfTraceEnabled() { Logger logger = Mockito.mock(Logger.class); Mockito.when(logger.isTraceEnabled()).thenReturn(true); LoggerUtils.printIfTraceEnabled(logger, "test", "arg1", "arg2", "arg3"); @@ -47,7 +47,7 @@ public void testPrintIfTraceEnabled() { } @Test - public void testPrintIfWarnEnabled() { + void testPrintIfWarnEnabled() { Logger logger = Mockito.mock(Logger.class); Mockito.when(logger.isWarnEnabled()).thenReturn(true); LoggerUtils.printIfWarnEnabled(logger, "test", "arg1", "arg2", "arg3"); @@ -55,7 +55,7 @@ public void testPrintIfWarnEnabled() { } @Test - public void testPrintIfErrorEnabled() { + void testPrintIfErrorEnabled() { Logger logger = Mockito.mock(Logger.class); Mockito.when(logger.isErrorEnabled()).thenReturn(true); LoggerUtils.printIfErrorEnabled(logger, "test", "arg1", "arg2", "arg3"); diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/MD5UtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/MD5UtilsTest.java index 0384d97ba12..9315992ea3b 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/MD5UtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/MD5UtilsTest.java @@ -17,29 +17,29 @@ package com.alibaba.nacos.common.utils; import com.alibaba.nacos.api.common.Constants; +import org.junit.jupiter.api.Test; import java.security.NoSuchAlgorithmException; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class MD5UtilsTest { +class MD5UtilsTest { @Test - public void testMd5Hex() throws NoSuchAlgorithmException { - Assert.assertEquals("d41d8cd98f00b204e9800998ecf8427e", MD5Utils.md5Hex("", Constants.ENCODE)); - Assert.assertEquals("acbd18db4cc2f85cedef654fccc4a4d8", MD5Utils.md5Hex("foo", Constants.ENCODE)); - Assert.assertEquals("02f463eb799797e2a978fb1a2ae2991e", MD5Utils.md5Hex( + void testMd5Hex() throws NoSuchAlgorithmException { + assertEquals("d41d8cd98f00b204e9800998ecf8427e", MD5Utils.md5Hex("", Constants.ENCODE)); + assertEquals("acbd18db4cc2f85cedef654fccc4a4d8", MD5Utils.md5Hex("foo", Constants.ENCODE)); + assertEquals("02f463eb799797e2a978fb1a2ae2991e", MD5Utils.md5Hex( "38c5ee9532f037a20b93d0f804cf111fca4003e451d09a692d9dea8032308d9c64eda9047fcd5e850284a49b1a0cfb2ecd45", Constants.ENCODE)); - Assert.assertEquals("d41d8cd98f00b204e9800998ecf8427e", MD5Utils.md5Hex(new byte[0])); - Assert.assertEquals("5289df737df57326fcdd22597afb1fac", MD5Utils.md5Hex(new byte[] {1, 2, 3})); + assertEquals("d41d8cd98f00b204e9800998ecf8427e", MD5Utils.md5Hex(new byte[0])); + assertEquals("5289df737df57326fcdd22597afb1fac", MD5Utils.md5Hex(new byte[] {1, 2, 3})); } @Test - public void testEncodeHexString() { - Assert.assertEquals("", MD5Utils.encodeHexString(new byte[0])); - Assert.assertEquals("010203", MD5Utils.encodeHexString(new byte[] {1, 2, 3})); + void testEncodeHexString() { + assertEquals("", MD5Utils.encodeHexString(new byte[0])); + assertEquals("010203", MD5Utils.encodeHexString(new byte[] {1, 2, 3})); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/MapUtilTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/MapUtilTest.java index 0374d4594b0..5c66dee7b25 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/MapUtilTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/MapUtilTest.java @@ -16,7 +16,7 @@ package com.alibaba.nacos.common.utils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.Collections; @@ -27,15 +27,15 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiFunction; -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; import static org.mockito.Mockito.when; -public class MapUtilTest { +class MapUtilTest { @Test - public void testIsEmptyAndNotEmptyMap() { + void testIsEmptyAndNotEmptyMap() { Map map = null; assertTrue(MapUtil.isEmpty(map)); assertFalse(MapUtil.isNotEmpty(map)); @@ -48,7 +48,7 @@ public void testIsEmptyAndNotEmptyMap() { } @Test - public void testIsEmptyOrEmptyDictionary() { + void testIsEmptyOrEmptyDictionary() { Dictionary dictionary = null; assertTrue(MapUtil.isEmpty(dictionary)); assertFalse(MapUtil.isNotEmpty(dictionary)); @@ -61,7 +61,7 @@ public void testIsEmptyOrEmptyDictionary() { } @Test - public void testPutIfValNoNull() { + void testPutIfValNoNull() { Map map = new HashMap<>(); MapUtil.putIfValNoNull(map, "key-1", null); assertTrue(map.isEmpty()); @@ -70,7 +70,7 @@ public void testPutIfValNoNull() { } @Test - public void testPutIfValNoEmptyMap() { + void testPutIfValNoEmptyMap() { Map map = new HashMap<>(); MapUtil.putIfValNoEmpty(map, "key-str", null); @@ -113,7 +113,7 @@ public void testPutIfValNoEmptyMap() { } @Test - public void testComputeIfAbsent() { + void testComputeIfAbsent() { Map target = new HashMap<>(); String key = "key"; String param1 = "param1"; @@ -136,7 +136,7 @@ public void testComputeIfAbsent() { } @Test - public void testRemoveKey() { + void testRemoveKey() { Map map = new HashMap<>(); map.put("A", 1); map.put("B", 2); diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/NamespaceUtilTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/NamespaceUtilTest.java index ff399a7119b..25f5325eea1 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/NamespaceUtilTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/NamespaceUtilTest.java @@ -16,9 +16,10 @@ package com.alibaba.nacos.common.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; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * test NamespaceUtil. @@ -26,33 +27,33 @@ * @author klw(213539 @ qq.com) * @date 2020/10/13 9:46 */ -public class NamespaceUtilTest { +class NamespaceUtilTest { - @After - public void tearDown() { + @AfterEach + void tearDown() { NamespaceUtil.setNamespaceDefaultId(""); } @Test - public void testProcessTenantParameter() { + void testProcessTenantParameter() { String strPublic = "public"; - String strNull = "null"; String strEmpty = ""; + assertEquals(strEmpty, NamespaceUtil.processNamespaceParameter(strPublic)); + String strNull = "null"; + assertEquals(strEmpty, NamespaceUtil.processNamespaceParameter(strNull)); + assertEquals(strEmpty, NamespaceUtil.processNamespaceParameter(strEmpty)); + assertEquals(strEmpty, NamespaceUtil.processNamespaceParameter(null)); String strAbc = "abc"; + assertEquals(strAbc, NamespaceUtil.processNamespaceParameter(strAbc)); String strdef123 = "def123"; + assertEquals(strdef123, NamespaceUtil.processNamespaceParameter(strdef123)); String strAbcHasSpace = " abc "; - Assert.assertEquals(strEmpty, NamespaceUtil.processNamespaceParameter(strPublic)); - Assert.assertEquals(strEmpty, NamespaceUtil.processNamespaceParameter(strNull)); - Assert.assertEquals(strEmpty, NamespaceUtil.processNamespaceParameter(strEmpty)); - Assert.assertEquals(strEmpty, NamespaceUtil.processNamespaceParameter(null)); - Assert.assertEquals(strAbc, NamespaceUtil.processNamespaceParameter(strAbc)); - Assert.assertEquals(strdef123, NamespaceUtil.processNamespaceParameter(strdef123)); - Assert.assertEquals(strAbc, NamespaceUtil.processNamespaceParameter(strAbcHasSpace)); + assertEquals(strAbc, NamespaceUtil.processNamespaceParameter(strAbcHasSpace)); } @Test - public void testSetNamespaceDefaultId() { + void testSetNamespaceDefaultId() { NamespaceUtil.setNamespaceDefaultId("Deprecated"); - Assert.assertEquals("Deprecated", NamespaceUtil.getNamespaceDefaultId()); + assertEquals("Deprecated", NamespaceUtil.getNamespaceDefaultId()); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/NumberUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/NumberUtilsTest.java index 8016e0b47d1..bea74efc8f8 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/NumberUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/NumberUtilsTest.java @@ -16,78 +16,82 @@ package com.alibaba.nacos.common.utils; -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.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Number utils. + * * @author zzq */ -public class NumberUtilsTest { +class NumberUtilsTest { @Test - public void testToInt() { - Assert.assertEquals(0, NumberUtils.toInt(null)); - Assert.assertEquals(0, NumberUtils.toInt(StringUtils.EMPTY)); - Assert.assertEquals(1, NumberUtils.toInt("1")); + void testToInt() { + assertEquals(0, NumberUtils.toInt(null)); + assertEquals(0, NumberUtils.toInt(StringUtils.EMPTY)); + assertEquals(1, NumberUtils.toInt("1")); } @Test - public void testTestToInt() { - Assert.assertEquals(1, NumberUtils.toInt(null, 1)); - Assert.assertEquals(1, NumberUtils.toInt("", 1)); - Assert.assertEquals(1, NumberUtils.toInt("1", 0)); + void testTestToInt() { + assertEquals(1, NumberUtils.toInt(null, 1)); + assertEquals(1, NumberUtils.toInt("", 1)); + assertEquals(1, NumberUtils.toInt("1", 0)); } @Test - public void testToLong() { - Assert.assertEquals(1L, NumberUtils.toLong(null, 1L)); - Assert.assertEquals(1L, NumberUtils.toLong("", 1L)); - Assert.assertEquals(1L, NumberUtils.toLong("1", 0L)); + void testToLong() { + assertEquals(1L, NumberUtils.toLong(null, 1L)); + assertEquals(1L, NumberUtils.toLong("", 1L)); + assertEquals(1L, NumberUtils.toLong("1", 0L)); } @Test - public void testToDouble() { - Assert.assertEquals(1.1d, NumberUtils.toDouble(null, 1.1d), 0); - Assert.assertEquals(1.1d, NumberUtils.toDouble("", 1.1d), 0); - Assert.assertEquals(1.5d, NumberUtils.toDouble("1.5", 0.0d), 0); + void testToDouble() { + assertEquals(1.1d, NumberUtils.toDouble(null, 1.1d), 0); + assertEquals(1.1d, NumberUtils.toDouble("", 1.1d), 0); + assertEquals(1.5d, NumberUtils.toDouble("1.5", 0.0d), 0); } @Test - public void testIsDigits() { - Assert.assertFalse(NumberUtils.isDigits(null)); - Assert.assertFalse(NumberUtils.isDigits("")); - Assert.assertTrue(NumberUtils.isDigits("12345")); - Assert.assertFalse(NumberUtils.isDigits("1234.5")); - Assert.assertFalse(NumberUtils.isDigits("1ab")); - Assert.assertFalse(NumberUtils.isDigits("abc")); + void testIsDigits() { + assertFalse(NumberUtils.isDigits(null)); + assertFalse(NumberUtils.isDigits("")); + assertTrue(NumberUtils.isDigits("12345")); + assertFalse(NumberUtils.isDigits("1234.5")); + assertFalse(NumberUtils.isDigits("1ab")); + assertFalse(NumberUtils.isDigits("abc")); } @Test - public void testToFloatString() { - Assert.assertEquals(NumberUtils.toFloat("-1.2345"), -1.2345f, 0); - Assert.assertEquals(1.2345f, NumberUtils.toFloat("1.2345"), 0); - Assert.assertEquals(0.0f, NumberUtils.toFloat("abc"), 0); - - Assert.assertEquals(NumberUtils.toFloat("-001.2345"), -1.2345f, 0); - Assert.assertEquals(1.2345f, NumberUtils.toFloat("+001.2345"), 0); - Assert.assertEquals(1.2345f, NumberUtils.toFloat("001.2345"), 0); - Assert.assertEquals(0f, NumberUtils.toFloat("000.00"), 0); - - Assert.assertEquals(NumberUtils.toFloat(Float.MAX_VALUE + ""), Float.MAX_VALUE, 0); - Assert.assertEquals(NumberUtils.toFloat(Float.MIN_VALUE + ""), Float.MIN_VALUE, 0); - Assert.assertEquals(0.0f, NumberUtils.toFloat(""), 0); - Assert.assertEquals(0.0f, NumberUtils.toFloat(null), 0); + void testToFloatString() { + assertEquals(NumberUtils.toFloat("-1.2345"), -1.2345f, 0); + assertEquals(1.2345f, NumberUtils.toFloat("1.2345"), 0); + assertEquals(0.0f, NumberUtils.toFloat("abc"), 0); + + assertEquals(NumberUtils.toFloat("-001.2345"), -1.2345f, 0); + assertEquals(1.2345f, NumberUtils.toFloat("+001.2345"), 0); + assertEquals(1.2345f, NumberUtils.toFloat("001.2345"), 0); + assertEquals(0f, NumberUtils.toFloat("000.00"), 0); + + assertEquals(Float.MAX_VALUE, NumberUtils.toFloat(Float.MAX_VALUE + ""), 0); + assertEquals(Float.MIN_VALUE, NumberUtils.toFloat(Float.MIN_VALUE + ""), 0); + assertEquals(0.0f, NumberUtils.toFloat(""), 0); + assertEquals(0.0f, NumberUtils.toFloat(null), 0); } @Test - public void testToFloatStringString() { - Assert.assertEquals(1.2345f, NumberUtils.toFloat("1.2345", 5.1f), 0); - Assert.assertEquals(5.0f, NumberUtils.toFloat("a", 5.0f), 0); + void testToFloatStringString() { + assertEquals(1.2345f, NumberUtils.toFloat("1.2345", 5.1f), 0); + assertEquals(5.0f, NumberUtils.toFloat("a", 5.0f), 0); // LANG-1060 - Assert.assertEquals(5.0f, NumberUtils.toFloat("-001Z.2345", 5.0f), 0); - Assert.assertEquals(5.0f, NumberUtils.toFloat("+001AB.2345", 5.0f), 0); - Assert.assertEquals(5.0f, NumberUtils.toFloat("001Z.2345", 5.0f), 0); + assertEquals(5.0f, NumberUtils.toFloat("-001Z.2345", 5.0f), 0); + assertEquals(5.0f, NumberUtils.toFloat("+001AB.2345", 5.0f), 0); + assertEquals(5.0f, NumberUtils.toFloat("001Z.2345", 5.0f), 0); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/ObservableTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/ObservableTest.java index 0142fff7546..a2361518055 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/ObservableTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/ObservableTest.java @@ -16,46 +16,46 @@ package com.alibaba.nacos.common.utils; -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 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; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; -@RunWith(MockitoJUnitRunner.class) -public class ObservableTest { +@ExtendWith(MockitoExtension.class) +class ObservableTest { @Mock private Observer observer; private Observable observable; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { observable = new Observable(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { } @Test - public void testAddObserver() { + void testAddObserver() { observable.addObserver(observer); assertEquals(1, observable.countObservers()); verify(observer).update(observable); } @Test - public void testDeleteObserver() { + void testDeleteObserver() { observable.addObserver(observer); assertEquals(1, observable.countObservers()); observable.deleteObserver(observer); @@ -63,7 +63,7 @@ public void testDeleteObserver() { } @Test - public void testNotifyObservers() { + void testNotifyObservers() { observable.addObserver(observer); reset(observer); observable.notifyObservers(); @@ -77,7 +77,7 @@ public void testNotifyObservers() { } @Test - public void testDeleteObservers() { + void testDeleteObservers() { observable.addObserver(observer); observable.deleteObservers(); assertEquals(1, observable.countObservers()); diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/PairTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/PairTest.java index 511bdfc80b9..ae21b142224 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/PairTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/PairTest.java @@ -16,14 +16,14 @@ package com.alibaba.nacos.common.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; -public class PairTest { +class PairTest { @Test - public void testPair() { + void testPair() { Pair pair = Pair.with("a", "b"); assertEquals("a", pair.getFirst()); assertEquals("b", pair.getSecond()); diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/PreconditionsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/PreconditionsTest.java index 7f735320167..01c62db3357 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/PreconditionsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/PreconditionsTest.java @@ -16,14 +16,17 @@ package com.alibaba.nacos.common.utils; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; /** * {@code Preconditions} unit test. + * * @author zzq * @date 2021/7/29 */ -public final class PreconditionsTest { +final class PreconditionsTest { private static final String FORMAT = "I ate %s pies."; @@ -32,47 +35,61 @@ public final class PreconditionsTest { private static final String ERRORMSG = "A message"; @Test - public void testCheckArgument2Args1true() { + void testCheckArgument2Args1true() { Preconditions.checkArgument(true, ERRORMSG); } - @Test(expected = IllegalArgumentException.class) - public void testCheckArgument2Args1false() { - Preconditions.checkArgument(false, ERRORMSG); + @Test + void testCheckArgument2Args1false() { + assertThrows(IllegalArgumentException.class, () -> { + Preconditions.checkArgument(false, ERRORMSG); + }); } - @Test(expected = IllegalArgumentException.class) - public void testCheckArgument2Args1true2null() { - Preconditions.checkArgument(true, null); + @Test + void testCheckArgument2Args1true2null() { + assertThrows(IllegalArgumentException.class, () -> { + Preconditions.checkArgument(true, null); + }); } - @Test(expected = IllegalArgumentException.class) - public void testCheckArgument2Args1false2null() { - Preconditions.checkArgument(false, null); + @Test + void testCheckArgument2Args1false2null() { + assertThrows(IllegalArgumentException.class, () -> { + Preconditions.checkArgument(false, null); + }); } @Test - public void testCheckArgument3Args1true() { + void testCheckArgument3Args1true() { Preconditions.checkArgument(true, ERRORMSG, ARG); } - @Test(expected = IllegalArgumentException.class) - public void testCheckArgument3Args1false() { - Preconditions.checkArgument(false, ERRORMSG, ARG); + @Test + void testCheckArgument3Args1false() { + assertThrows(IllegalArgumentException.class, () -> { + Preconditions.checkArgument(false, ERRORMSG, ARG); + }); } - @Test(expected = IllegalArgumentException.class) - public void testCheckArgument3Args1true2null() { - Preconditions.checkArgument(true, null, ARG); + @Test + void testCheckArgument3Args1true2null() { + assertThrows(IllegalArgumentException.class, () -> { + Preconditions.checkArgument(true, null, ARG); + }); } - @Test(expected = IllegalArgumentException.class) - public void testCheckArgument3Args1false2null() { - Preconditions.checkArgument(false, null, ARG); + @Test + void testCheckArgument3Args1false2null() { + assertThrows(IllegalArgumentException.class, () -> { + Preconditions.checkArgument(false, null, ARG); + }); } - @Test(expected = IllegalArgumentException.class) - public void testCheckArgument3Args1false3null() { - Preconditions.checkArgument(false, ERRORMSG, null); + @Test + void testCheckArgument3Args1false3null() { + assertThrows(IllegalArgumentException.class, () -> { + Preconditions.checkArgument(false, ERRORMSG, null); + }); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/PropertyUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/PropertyUtilsTest.java index 0e2b43a5835..fdde9608435 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/PropertyUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/PropertyUtilsTest.java @@ -16,33 +16,36 @@ package com.alibaba.nacos.common.utils; -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; /** * PropertyUtils Test. + * * @ClassName: PropertyUtilsTest * @Author: ChenHao26 * @Date: 2022/8/22 13:28 */ -public class PropertyUtilsTest { +class PropertyUtilsTest { @Test - public void getProperty() { + void getProperty() { System.setProperty("nacos.test", "google"); String property = PropertyUtils.getProperty("nacos.test", "xx"); - Assert.assertEquals(property, "google"); + assertEquals("google", property); } @Test - public void getPropertyWithDefaultValue() { + void getPropertyWithDefaultValue() { String property = PropertyUtils.getProperty("nacos.test", "xx", "test001"); - Assert.assertEquals(property, "test001"); + assertEquals("test001", property); } @Test - public void getProcessorsCount() { + void getProcessorsCount() { int processorsCount = PropertyUtils.getProcessorsCount(); - Assert.assertNotNull(processorsCount); + assertNotNull(processorsCount); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/RandomUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/RandomUtilsTest.java index 8ba35941e2f..58443a2d36b 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/RandomUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/RandomUtilsTest.java @@ -16,47 +16,54 @@ package com.alibaba.nacos.common.utils; -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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * test RandomUtils. * * @author zzq */ -public class RandomUtilsTest { +class RandomUtilsTest { @Test - public void testNextLong() { + void testNextLong() { final long result = RandomUtils.nextLong(1L, 199L); - Assert.assertTrue(result >= 1L && result < 199L); + assertTrue(result >= 1L && result < 199L); } @Test - public void testNextLongWithSame() { + void testNextLongWithSame() { final long result = RandomUtils.nextLong(1L, 1L); - Assert.assertEquals(1L, result); + assertEquals(1L, result); } - @Test(expected = IllegalArgumentException.class) - public void testNextLongWithIllegalArgumentException() { - RandomUtils.nextLong(999L, 199L); + @Test + void testNextLongWithIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> { + RandomUtils.nextLong(999L, 199L); + }); } - @Test(expected = IllegalArgumentException.class) - public void testNextLongWithIllegalArgumentException2() { - RandomUtils.nextLong(-10L, 199L); + @Test + void testNextLongWithIllegalArgumentException2() { + assertThrows(IllegalArgumentException.class, () -> { + RandomUtils.nextLong(-10L, 199L); + }); } @Test - public void testNextInt() { + void testNextInt() { final int result = RandomUtils.nextInt(1, 199); - Assert.assertTrue(result >= 1 && result < 199); + assertTrue(result >= 1 && result < 199); } @Test - public void testNextIntWithSame() { + void testNextIntWithSame() { final int result = RandomUtils.nextInt(1, 1); - Assert.assertEquals(1, result); + assertEquals(1, result); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/ReflectUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/ReflectUtilsTest.java index 327665121e8..7c2730c1b44 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/ReflectUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/ReflectUtilsTest.java @@ -16,9 +16,8 @@ package com.alibaba.nacos.common.utils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.lang.reflect.Field; @@ -28,108 +27,122 @@ import java.util.ArrayList; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * ReflectUtils unit test. * * @author karsonto * @date 2022/08/19 */ -public class ReflectUtilsTest { +class ReflectUtilsTest { List listStr; - @Before - public void before() { + @BeforeEach + void before() { listStr = new ArrayList<>(2); } @Test - public void testGetFieldValue() { + void testGetFieldValue() { Object elementData = ReflectUtils.getFieldValue(listStr, "elementData"); - Assert.assertTrue(elementData instanceof Object[]); - Assert.assertEquals(2, ((Object[]) elementData).length); + assertTrue(elementData instanceof Object[]); + assertEquals(2, ((Object[]) elementData).length); } - @Test(expected = RuntimeException.class) - public void testGetFieldValueWithoutField() { - ReflectUtils.getFieldValue(listStr, "elementDataxx"); + @Test + void testGetFieldValueWithoutField() { + assertThrows(RuntimeException.class, () -> { + ReflectUtils.getFieldValue(listStr, "elementDataxx"); + }); } @Test - public void testGetFieldValueWithDefault() { + void testGetFieldValueWithDefault() { Object elementData = ReflectUtils.getFieldValue(listStr, "elementDataxx", 3); - Assert.assertEquals(elementData, 3); + assertEquals(3, elementData); elementData = ReflectUtils.getFieldValue(listStr, "elementData", 3); - Assert.assertTrue(elementData instanceof Object[]); - Assert.assertEquals(2, ((Object[]) elementData).length); + assertTrue(elementData instanceof Object[]); + assertEquals(2, ((Object[]) elementData).length); } @Test - public void testGetField() throws NoSuchFieldException { + void testGetField() throws NoSuchFieldException { Field field = listStr.getClass().getDeclaredField("elementData"); field.setAccessible(true); Object elementData = ReflectUtils.getField(field, listStr); - Assert.assertTrue(elementData instanceof Object[]); + assertTrue(elementData instanceof Object[]); } - @Test(expected = IllegalStateException.class) - public void testGetFieldWithoutAccess() throws NoSuchFieldException { - Field field = listStr.getClass().getDeclaredField("elementData"); - ReflectUtils.getField(field, listStr); + @Test + void testGetFieldWithoutAccess() throws NoSuchFieldException { + assertThrows(IllegalStateException.class, () -> { + Field field = listStr.getClass().getDeclaredField("elementData"); + ReflectUtils.getField(field, listStr); + }); } @Test - public void testInvokeMethod() throws Exception { + void testInvokeMethod() throws Exception { Method method = listStr.getClass().getDeclaredMethod("grow", int.class); method.setAccessible(true); ReflectUtils.invokeMethod(method, listStr, 4); Object elementData = ReflectUtils.getFieldValue(listStr, "elementData"); - Assert.assertEquals(4, ((Object[]) elementData).length); + assertEquals(4, ((Object[]) elementData).length); } - @Test(expected = IllegalStateException.class) - public void testInvokeMethodWithoutAccess() throws Exception { - Method method = listStr.getClass().getDeclaredMethod("grow", int.class); - ReflectUtils.invokeMethod(method, listStr, 4); + @Test + void testInvokeMethodWithoutAccess() throws Exception { + assertThrows(IllegalStateException.class, () -> { + Method method = listStr.getClass().getDeclaredMethod("grow", int.class); + ReflectUtils.invokeMethod(method, listStr, 4); + }); } - @Test(expected = UndeclaredThrowableException.class) - public void testHandleReflectionException() { - try { - NoSuchMethodException exception = new NoSuchMethodException("test"); - ReflectUtils.handleReflectionException(exception); - } catch (Exception e) { - Assert.assertEquals("Method not found: test", e.getMessage()); - } - try { - IllegalAccessException exception = new IllegalAccessException("test"); - ReflectUtils.handleReflectionException(exception); - } catch (Exception e) { - Assert.assertEquals("Could not access method or field: test", e.getMessage()); - } - RuntimeException exception = new RuntimeException("test"); - try { - ReflectUtils.handleReflectionException(exception); - } catch (Exception e) { - Assert.assertEquals(exception, e); - } - try { - InvocationTargetException invocationTargetException = new InvocationTargetException(exception); - ReflectUtils.handleReflectionException(invocationTargetException); - } catch (Exception e) { - Assert.assertEquals(exception, e); - } - ReflectUtils.handleReflectionException(new IOException()); + @Test + void testHandleReflectionException() { + assertThrows(UndeclaredThrowableException.class, () -> { + try { + NoSuchMethodException exception = new NoSuchMethodException("test"); + ReflectUtils.handleReflectionException(exception); + } catch (Exception e) { + assertEquals("Method not found: test", e.getMessage()); + } + try { + IllegalAccessException exception = new IllegalAccessException("test"); + ReflectUtils.handleReflectionException(exception); + } catch (Exception e) { + assertEquals("Could not access method or field: test", e.getMessage()); + } + RuntimeException exception = new RuntimeException("test"); + try { + ReflectUtils.handleReflectionException(exception); + } catch (Exception e) { + assertEquals(exception, e); + } + try { + InvocationTargetException invocationTargetException = new InvocationTargetException(exception); + ReflectUtils.handleReflectionException(invocationTargetException); + } catch (Exception e) { + assertEquals(exception, e); + } + ReflectUtils.handleReflectionException(new IOException()); + }); } - @Test(expected = UndeclaredThrowableException.class) - public void testRethrowRuntimeException() { - ClassFormatError error = new ClassFormatError("test"); - try { - ReflectUtils.rethrowRuntimeException(error); - } catch (Error e) { - Assert.assertEquals(error, e); - } - ReflectUtils.rethrowRuntimeException(new IOException()); + @Test + void testRethrowRuntimeException() { + assertThrows(UndeclaredThrowableException.class, () -> { + ClassFormatError error = new ClassFormatError("test"); + try { + ReflectUtils.rethrowRuntimeException(error); + } catch (Error e) { + assertEquals(error, e); + } + ReflectUtils.rethrowRuntimeException(new IOException()); + }); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/ResourceUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/ResourceUtilsTest.java index d678532572b..834e43467a0 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/ResourceUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/ResourceUtilsTest.java @@ -16,7 +16,7 @@ package com.alibaba.nacos.common.utils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.FileNotFoundException; @@ -26,24 +26,27 @@ import java.net.URL; import java.util.Properties; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ResourceUtilsTest { +class ResourceUtilsTest { @Test - public void testGetResourceUrlForClasspath() throws IOException { + void testGetResourceUrlForClasspath() throws IOException { URL url = ResourceUtils.getResourceUrl("classpath:test-tls-cert.pem"); assertNotNull(url); } - @Test(expected = FileNotFoundException.class) - public void testGetResourceUrlForClasspathNotExists() throws IOException { - ResourceUtils.getResourceUrl("classpath:non-exist.pem"); + @Test + void testGetResourceUrlForClasspathNotExists() throws IOException { + assertThrows(FileNotFoundException.class, () -> { + ResourceUtils.getResourceUrl("classpath:non-exist.pem"); + }); } @Test - public void testGetResourceUrlForFile() throws IOException { + void testGetResourceUrlForFile() throws IOException { File file = File.createTempFile("test", ".txt"); try { URL url = ResourceUtils.getResourceUrl("file://" + file.getPath()); @@ -54,7 +57,7 @@ public void testGetResourceUrlForFile() throws IOException { } @Test - public void testGetResourceUrlForFileWithoutProtocol() throws IOException { + void testGetResourceUrlForFileWithoutProtocol() throws IOException { File file = File.createTempFile("test", ".txt"); try { URL url = ResourceUtils.getResourceUrl(file.getPath()); @@ -65,83 +68,84 @@ public void testGetResourceUrlForFileWithoutProtocol() throws IOException { } @Test - public void testGetResourceUrlFromLoader() throws IOException { + void testGetResourceUrlFromLoader() throws IOException { URL url = ResourceUtils.getResourceUrl(this.getClass().getClassLoader(), "test-tls-cert.pem"); assertNotNull(url); } @Test - public void testGetResourceUrlFromSystemLoader() throws IOException { + void testGetResourceUrlFromSystemLoader() throws IOException { URL url = ResourceUtils.getResourceUrl(null, "test-tls-cert.pem"); assertNotNull(url); } - @Test(expected = IOException.class) - public void testGetResourceUrlFromLoaderWithoutExist() throws IOException { - URL url = ResourceUtils.getResourceUrl(null, "non-exist"); - assertNotNull(url); + @Test + void testGetResourceUrlFromLoaderWithoutExist() throws IOException { + assertThrows(IOException.class, () -> { + URL url = ResourceUtils.getResourceUrl(null, "non-exist"); + assertNotNull(url); + }); } @Test - public void testGetResourceAsStreamForClasspath() throws IOException { + void testGetResourceAsStreamForClasspath() throws IOException { try (InputStream inputStream = ResourceUtils.getResourceAsStream("test-tls-cert.pem")) { assertNotNull(inputStream); } } @Test - public void testGetResourceAsStreamForClasspathFromSystem() throws IOException { + void testGetResourceAsStreamForClasspathFromSystem() throws IOException { try (InputStream inputStream = ResourceUtils.getResourceAsStream(null, "test-tls-cert.pem")) { assertNotNull(inputStream); } } - @Test(expected = IOException.class) - public void testGetResourceAsStreamForClasspathWithoutExist() throws IOException { - URL url = ResourceUtils.getResourceUrl("non-exist"); - ResourceUtils.getResourceAsStream(null, url.toString()); + @Test + void testGetResourceAsStreamForClasspathWithoutExist() throws IOException { + assertThrows(IOException.class, () -> { + URL url = ResourceUtils.getResourceUrl("non-exist"); + ResourceUtils.getResourceAsStream(null, url.toString()); + }); } @Test - public void testGetResourceAsPropertiesForClasspath() throws IOException { + void testGetResourceAsPropertiesForClasspath() throws IOException { Properties properties = ResourceUtils.getResourceAsProperties("resource_utils_test.properties"); assertNotNull(properties); assertTrue(properties.containsKey("a")); } @Test - public void testGetResourceAsReader() throws IOException { + void testGetResourceAsReader() throws IOException { try (Reader reader = ResourceUtils.getResourceAsReader("resource_utils_test.properties", "UTF-8")) { assertNotNull(reader); } } @Test - public void testGetResourceAsReaderWithLoader() throws IOException { - try (Reader reader = ResourceUtils - .getResourceAsReader(ResourceUtilsTest.class.getClassLoader(), "resource_utils_test.properties", - "UTF-8")) { + void testGetResourceAsReaderWithLoader() throws IOException { + try (Reader reader = ResourceUtils.getResourceAsReader(ResourceUtilsTest.class.getClassLoader(), + "resource_utils_test.properties", "UTF-8")) { assertNotNull(reader); } } @Test - public void testGetResourceAsFile() throws IOException { + void testGetResourceAsFile() throws IOException { File file = ResourceUtils.getResourceAsFile("classpath:resource_utils_test.properties"); assertNotNull(file); } @Test - public void testGetResourceAsFileByUrl() throws IOException { - File file = ResourceUtils - .getResourceAsFile(ResourceUtils.getResourceUrl("classpath:resource_utils_test.properties")); + void testGetResourceAsFileByUrl() throws IOException { + File file = ResourceUtils.getResourceAsFile(ResourceUtils.getResourceUrl("classpath:resource_utils_test.properties")); assertNotNull(file); } @Test - public void testGetResourceAsFileByLoader() throws IOException { - File file = ResourceUtils - .getResourceAsFile(ResourceUtils.class.getClassLoader(), "resource_utils_test.properties"); + void testGetResourceAsFileByLoader() throws IOException { + File file = ResourceUtils.getResourceAsFile(ResourceUtils.class.getClassLoader(), "resource_utils_test.properties"); assertNotNull(file); } } \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/StringUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/StringUtilsTest.java index 143c76e83f9..cbc69de3f2b 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/StringUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/StringUtilsTest.java @@ -16,228 +16,231 @@ package com.alibaba.nacos.common.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +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; + /** * String utils. * * @author zzq */ -public class StringUtilsTest { +class StringUtilsTest { @Test - public void testNewStringForUtf8() { + void testNewStringForUtf8() { String abc = "abc"; byte[] abcByte = abc.getBytes(); - Assert.assertEquals(abc, StringUtils.newStringForUtf8(abcByte)); + assertEquals(abc, StringUtils.newStringForUtf8(abcByte)); } @Test - public void isBlank() { - Assert.assertTrue(StringUtils.isBlank(null)); - Assert.assertTrue(StringUtils.isBlank("")); - Assert.assertTrue(StringUtils.isBlank(" ")); - Assert.assertFalse(StringUtils.isBlank("bob")); - Assert.assertFalse(StringUtils.isBlank(" bob ")); + void isBlank() { + assertTrue(StringUtils.isBlank(null)); + assertTrue(StringUtils.isBlank("")); + assertTrue(StringUtils.isBlank(" ")); + assertFalse(StringUtils.isBlank("bob")); + assertFalse(StringUtils.isBlank(" bob ")); } @Test - public void testIsNotBlank() { - Assert.assertFalse(StringUtils.isNotBlank(null)); - Assert.assertFalse(StringUtils.isNotBlank("")); - Assert.assertFalse(StringUtils.isNotBlank(" ")); - Assert.assertTrue(StringUtils.isNotBlank("bob")); - Assert.assertTrue(StringUtils.isNotBlank(" bob ")); + void testIsNotBlank() { + assertFalse(StringUtils.isNotBlank(null)); + assertFalse(StringUtils.isNotBlank("")); + assertFalse(StringUtils.isNotBlank(" ")); + assertTrue(StringUtils.isNotBlank("bob")); + assertTrue(StringUtils.isNotBlank(" bob ")); } @Test - public void testIsNotEmpty() { - Assert.assertFalse(StringUtils.isNotEmpty(null)); - Assert.assertFalse(StringUtils.isNotEmpty("")); - Assert.assertTrue(StringUtils.isNotEmpty(" ")); - Assert.assertTrue(StringUtils.isNotEmpty("bob")); - Assert.assertTrue(StringUtils.isNotEmpty(" bob ")); + void testIsNotEmpty() { + assertFalse(StringUtils.isNotEmpty(null)); + assertFalse(StringUtils.isNotEmpty("")); + assertTrue(StringUtils.isNotEmpty(" ")); + assertTrue(StringUtils.isNotEmpty("bob")); + assertTrue(StringUtils.isNotEmpty(" bob ")); } @Test - public void testIsEmpty() { - Assert.assertTrue(StringUtils.isEmpty(null)); - Assert.assertTrue(StringUtils.isEmpty("")); - Assert.assertFalse(StringUtils.isEmpty(" ")); - Assert.assertFalse(StringUtils.isEmpty("bob")); - Assert.assertFalse(StringUtils.isEmpty(" bob ")); + void testIsEmpty() { + assertTrue(StringUtils.isEmpty(null)); + assertTrue(StringUtils.isEmpty("")); + assertFalse(StringUtils.isEmpty(" ")); + assertFalse(StringUtils.isEmpty("bob")); + assertFalse(StringUtils.isEmpty(" bob ")); } @Test - public void testDefaultIfEmpty() { - Assert.assertEquals("NULL", StringUtils.defaultIfEmpty(null, "NULL")); - Assert.assertEquals("NULL", StringUtils.defaultIfEmpty("", "NULL")); - Assert.assertEquals(" ", StringUtils.defaultIfEmpty(" ", "NULL")); - Assert.assertEquals("bat", StringUtils.defaultIfEmpty("bat", "NULL")); - Assert.assertNull(StringUtils.defaultIfEmpty("", null)); + void testDefaultIfEmpty() { + assertEquals("NULL", StringUtils.defaultIfEmpty(null, "NULL")); + assertEquals("NULL", StringUtils.defaultIfEmpty("", "NULL")); + assertEquals(" ", StringUtils.defaultIfEmpty(" ", "NULL")); + assertEquals("bat", StringUtils.defaultIfEmpty("bat", "NULL")); + assertNull(StringUtils.defaultIfEmpty("", null)); } @Test - public void testDefaultIfBlank() { - Assert.assertEquals("NULL", StringUtils.defaultIfBlank(null, "NULL")); - Assert.assertEquals("NULL", StringUtils.defaultIfBlank("", "NULL")); - Assert.assertEquals("NULL", StringUtils.defaultIfBlank(" ", "NULL")); - Assert.assertEquals("bat", StringUtils.defaultIfBlank("bat", "NULL")); - Assert.assertNull(StringUtils.defaultIfBlank("", null)); + void testDefaultIfBlank() { + assertEquals("NULL", StringUtils.defaultIfBlank(null, "NULL")); + assertEquals("NULL", StringUtils.defaultIfBlank("", "NULL")); + assertEquals("NULL", StringUtils.defaultIfBlank(" ", "NULL")); + assertEquals("bat", StringUtils.defaultIfBlank("bat", "NULL")); + assertNull(StringUtils.defaultIfBlank("", null)); } @Test - public void testDefaultEmptyIfBlank() { - Assert.assertEquals("", StringUtils.defaultEmptyIfBlank(null)); - Assert.assertEquals("", StringUtils.defaultEmptyIfBlank("")); - Assert.assertEquals("", StringUtils.defaultEmptyIfBlank(" ")); - Assert.assertEquals("bat", StringUtils.defaultEmptyIfBlank("bat")); + void testDefaultEmptyIfBlank() { + assertEquals("", StringUtils.defaultEmptyIfBlank(null)); + assertEquals("", StringUtils.defaultEmptyIfBlank("")); + assertEquals("", StringUtils.defaultEmptyIfBlank(" ")); + assertEquals("bat", StringUtils.defaultEmptyIfBlank("bat")); } @Test - public void testEquals() { - Assert.assertTrue(StringUtils.equals(null, null)); - Assert.assertFalse(StringUtils.equals(null, "abc")); - Assert.assertFalse(StringUtils.equals("abc", null)); - Assert.assertTrue(StringUtils.equals("abc", "abc")); - Assert.assertFalse(StringUtils.equals("abc", "ABC")); + void testEquals() { + assertTrue(StringUtils.equals(null, null)); + assertFalse(StringUtils.equals(null, "abc")); + assertFalse(StringUtils.equals("abc", null)); + assertTrue(StringUtils.equals("abc", "abc")); + assertFalse(StringUtils.equals("abc", "ABC")); } @Test - public void trim() { - Assert.assertNull(StringUtils.trim(null)); - Assert.assertEquals(StringUtils.EMPTY, StringUtils.trim("")); - Assert.assertEquals(StringUtils.EMPTY, StringUtils.trim(" ")); - Assert.assertEquals("abc", StringUtils.trim("abc")); - Assert.assertEquals("abc", StringUtils.trim(" abc ")); + void trim() { + assertNull(StringUtils.trim(null)); + assertEquals(StringUtils.EMPTY, StringUtils.trim("")); + assertEquals(StringUtils.EMPTY, StringUtils.trim(" ")); + assertEquals("abc", StringUtils.trim("abc")); + assertEquals("abc", StringUtils.trim(" abc ")); } @Test - public void testSubstringBetween() { - Assert.assertNull(StringUtils.substringBetween(null, "a", "b")); - Assert.assertNull(StringUtils.substringBetween("a", null, "b")); - Assert.assertNull(StringUtils.substringBetween("a", "b", null)); - Assert.assertNull(StringUtils.substringBetween(StringUtils.EMPTY, StringUtils.EMPTY, "]")); - Assert.assertNull(StringUtils.substringBetween(StringUtils.EMPTY, "[", "]")); - Assert.assertEquals(StringUtils.EMPTY, - StringUtils.substringBetween("yabcz", StringUtils.EMPTY, StringUtils.EMPTY)); - Assert.assertEquals(StringUtils.EMPTY, - StringUtils.substringBetween(StringUtils.EMPTY, StringUtils.EMPTY, StringUtils.EMPTY)); - Assert.assertEquals("b", StringUtils.substringBetween("wx[b]yz", "[", "]")); - Assert.assertEquals("abc", StringUtils.substringBetween("yabcz", "y", "z")); - Assert.assertEquals("abc", StringUtils.substringBetween("yabczyabcz", "y", "z")); + void testSubstringBetween() { + assertNull(StringUtils.substringBetween(null, "a", "b")); + assertNull(StringUtils.substringBetween("a", null, "b")); + assertNull(StringUtils.substringBetween("a", "b", null)); + assertNull(StringUtils.substringBetween(StringUtils.EMPTY, StringUtils.EMPTY, "]")); + assertNull(StringUtils.substringBetween(StringUtils.EMPTY, "[", "]")); + assertEquals(StringUtils.EMPTY, StringUtils.substringBetween("yabcz", StringUtils.EMPTY, StringUtils.EMPTY)); + assertEquals(StringUtils.EMPTY, StringUtils.substringBetween(StringUtils.EMPTY, StringUtils.EMPTY, StringUtils.EMPTY)); + assertEquals("b", StringUtils.substringBetween("wx[b]yz", "[", "]")); + assertEquals("abc", StringUtils.substringBetween("yabcz", "y", "z")); + assertEquals("abc", StringUtils.substringBetween("yabczyabcz", "y", "z")); } @Test - public void testJoin() { + void testJoin() { ArrayList objects = new ArrayList<>(); objects.add(null); - Assert.assertNull(StringUtils.join(null, "a")); - Assert.assertEquals(StringUtils.EMPTY, StringUtils.join(Arrays.asList(), "a")); - Assert.assertEquals(StringUtils.EMPTY, StringUtils.join(objects, "a")); - Assert.assertEquals("a;b;c", StringUtils.join(Arrays.asList("a", "b", "c"), ";")); - Assert.assertEquals("abc", StringUtils.join(Arrays.asList("a", "b", "c"), null)); + assertNull(StringUtils.join(null, "a")); + assertEquals(StringUtils.EMPTY, StringUtils.join(Arrays.asList(), "a")); + assertEquals(StringUtils.EMPTY, StringUtils.join(objects, "a")); + assertEquals("a;b;c", StringUtils.join(Arrays.asList("a", "b", "c"), ";")); + assertEquals("abc", StringUtils.join(Arrays.asList("a", "b", "c"), null)); } @Test - public void testContainsIgnoreCase() { - Assert.assertFalse(StringUtils.containsIgnoreCase(null, "1")); - Assert.assertFalse(StringUtils.containsIgnoreCase("abc", null)); - Assert.assertTrue(StringUtils.containsIgnoreCase(StringUtils.EMPTY, StringUtils.EMPTY)); - Assert.assertTrue(StringUtils.containsIgnoreCase("abc", StringUtils.EMPTY)); - Assert.assertTrue(StringUtils.containsIgnoreCase("abc", "a")); - Assert.assertFalse(StringUtils.containsIgnoreCase("abc", "z")); - Assert.assertTrue(StringUtils.containsIgnoreCase("abc", "A")); - Assert.assertFalse(StringUtils.containsIgnoreCase("abc", "Z")); + void testContainsIgnoreCase() { + assertFalse(StringUtils.containsIgnoreCase(null, "1")); + assertFalse(StringUtils.containsIgnoreCase("abc", null)); + assertTrue(StringUtils.containsIgnoreCase(StringUtils.EMPTY, StringUtils.EMPTY)); + assertTrue(StringUtils.containsIgnoreCase("abc", StringUtils.EMPTY)); + assertTrue(StringUtils.containsIgnoreCase("abc", "a")); + assertFalse(StringUtils.containsIgnoreCase("abc", "z")); + assertTrue(StringUtils.containsIgnoreCase("abc", "A")); + assertFalse(StringUtils.containsIgnoreCase("abc", "Z")); } @Test - public void testContains() { - Assert.assertFalse(StringUtils.contains(null, "1")); - Assert.assertFalse(StringUtils.contains("abc", null)); - Assert.assertTrue(StringUtils.contains(StringUtils.EMPTY, StringUtils.EMPTY)); - Assert.assertTrue(StringUtils.contains("abc", StringUtils.EMPTY)); - Assert.assertTrue(StringUtils.contains("abc", "a")); - Assert.assertFalse(StringUtils.contains("abc", "z")); - Assert.assertFalse(StringUtils.contains("abc", "A")); - Assert.assertFalse(StringUtils.contains("abc", "Z")); + void testContains() { + assertFalse(StringUtils.contains(null, "1")); + assertFalse(StringUtils.contains("abc", null)); + assertTrue(StringUtils.contains(StringUtils.EMPTY, StringUtils.EMPTY)); + assertTrue(StringUtils.contains("abc", StringUtils.EMPTY)); + assertTrue(StringUtils.contains("abc", "a")); + assertFalse(StringUtils.contains("abc", "z")); + assertFalse(StringUtils.contains("abc", "A")); + assertFalse(StringUtils.contains("abc", "Z")); } @Test - public void testIsNoneBlank() { - Assert.assertFalse(StringUtils.isNoneBlank(null)); - Assert.assertFalse(StringUtils.isNoneBlank(null, "foo")); - Assert.assertFalse(StringUtils.isNoneBlank(null, null)); - Assert.assertFalse(StringUtils.isNoneBlank("", "bar")); - Assert.assertFalse(StringUtils.isNoneBlank("bob", "")); - Assert.assertFalse(StringUtils.isNoneBlank(" bob ", null)); - Assert.assertFalse(StringUtils.isNoneBlank(" ", "bar")); - Assert.assertTrue(StringUtils.isNoneBlank("foo", "bar")); + void testIsNoneBlank() { + assertFalse(StringUtils.isNoneBlank(null)); + assertFalse(StringUtils.isNoneBlank(null, "foo")); + assertFalse(StringUtils.isNoneBlank(null, null)); + assertFalse(StringUtils.isNoneBlank("", "bar")); + assertFalse(StringUtils.isNoneBlank("bob", "")); + assertFalse(StringUtils.isNoneBlank(" bob ", null)); + assertFalse(StringUtils.isNoneBlank(" ", "bar")); + assertTrue(StringUtils.isNoneBlank("foo", "bar")); } @Test - public void isAnyBlank() { - Assert.assertTrue(StringUtils.isAnyBlank(null)); - Assert.assertTrue(StringUtils.isAnyBlank(null, "foo")); - Assert.assertTrue(StringUtils.isAnyBlank(null, null)); - Assert.assertTrue(StringUtils.isAnyBlank("", "bar")); - Assert.assertTrue(StringUtils.isAnyBlank("bob", "")); - Assert.assertTrue(StringUtils.isAnyBlank(" bob ", null)); - Assert.assertTrue(StringUtils.isAnyBlank(" ", "bar")); - Assert.assertFalse(StringUtils.isAnyBlank("foo", "bar")); + void isAnyBlank() { + assertTrue(StringUtils.isAnyBlank(null)); + assertTrue(StringUtils.isAnyBlank(null, "foo")); + assertTrue(StringUtils.isAnyBlank(null, null)); + assertTrue(StringUtils.isAnyBlank("", "bar")); + assertTrue(StringUtils.isAnyBlank("bob", "")); + assertTrue(StringUtils.isAnyBlank(" bob ", null)); + assertTrue(StringUtils.isAnyBlank(" ", "bar")); + assertFalse(StringUtils.isAnyBlank("foo", "bar")); } @Test - public void testStartsWith() { - Assert.assertTrue(StringUtils.startsWith(null, null)); - Assert.assertFalse(StringUtils.startsWith(null, "abc")); - Assert.assertFalse(StringUtils.startsWith("abcdef", null)); - Assert.assertTrue(StringUtils.startsWith("abcdef", "abc")); - Assert.assertFalse(StringUtils.startsWith("ABCDEF", "abc")); - Assert.assertFalse(StringUtils.startsWith("ABC", "ABCDEF")); + void testStartsWith() { + assertTrue(StringUtils.startsWith(null, null)); + assertFalse(StringUtils.startsWith(null, "abc")); + assertFalse(StringUtils.startsWith("abcdef", null)); + assertTrue(StringUtils.startsWith("abcdef", "abc")); + assertFalse(StringUtils.startsWith("ABCDEF", "abc")); + assertFalse(StringUtils.startsWith("ABC", "ABCDEF")); } @Test - public void testStartsWithIgnoreCase() { - Assert.assertTrue(StringUtils.startsWithIgnoreCase(null, null)); - Assert.assertFalse(StringUtils.startsWithIgnoreCase(null, "abc")); - Assert.assertFalse(StringUtils.startsWithIgnoreCase("abcdef", null)); - Assert.assertTrue(StringUtils.startsWithIgnoreCase("abcdef", "abc")); - Assert.assertTrue(StringUtils.startsWithIgnoreCase("ABCDEF", "abc")); + void testStartsWithIgnoreCase() { + assertTrue(StringUtils.startsWithIgnoreCase(null, null)); + assertFalse(StringUtils.startsWithIgnoreCase(null, "abc")); + assertFalse(StringUtils.startsWithIgnoreCase("abcdef", null)); + assertTrue(StringUtils.startsWithIgnoreCase("abcdef", "abc")); + assertTrue(StringUtils.startsWithIgnoreCase("ABCDEF", "abc")); } @Test - public void testDeleteWhitespace() { - Assert.assertNull(StringUtils.deleteWhitespace(null)); - Assert.assertEquals(StringUtils.EMPTY, StringUtils.deleteWhitespace("")); - Assert.assertEquals("abc", StringUtils.deleteWhitespace("abc")); - Assert.assertEquals("abc", StringUtils.deleteWhitespace(" ab c ")); + void testDeleteWhitespace() { + assertNull(StringUtils.deleteWhitespace(null)); + assertEquals(StringUtils.EMPTY, StringUtils.deleteWhitespace("")); + assertEquals("abc", StringUtils.deleteWhitespace("abc")); + assertEquals("abc", StringUtils.deleteWhitespace(" ab c ")); } @Test - public void testEqualsIgnoreCase() { - Assert.assertTrue(StringUtils.equalsIgnoreCase(null, null)); - Assert.assertFalse(StringUtils.equalsIgnoreCase(null, "abc")); - Assert.assertFalse(StringUtils.equalsIgnoreCase("abc", null)); - Assert.assertTrue(StringUtils.equalsIgnoreCase("abc", "abc")); - Assert.assertTrue(StringUtils.equalsIgnoreCase("abc", "ABC")); + void testEqualsIgnoreCase() { + assertTrue(StringUtils.equalsIgnoreCase(null, null)); + assertFalse(StringUtils.equalsIgnoreCase(null, "abc")); + assertFalse(StringUtils.equalsIgnoreCase("abc", null)); + assertTrue(StringUtils.equalsIgnoreCase("abc", "abc")); + assertTrue(StringUtils.equalsIgnoreCase("abc", "ABC")); } @Test - public void testSplit() { - Assert.assertNull(StringUtils.split(null, ",")); - Assert.assertArrayEquals(new String[0], StringUtils.split("", ",")); - Assert.assertArrayEquals(new String[] {"ab", "cd", "ef"}, StringUtils.split("ab cd ef", null)); - Assert.assertArrayEquals(new String[] {"ab", "cd", "ef"}, StringUtils.split("ab cd ef", null)); - Assert.assertArrayEquals(new String[] {"ab", "cd", "ef"}, StringUtils.split("ab:cd:ef", ":")); + void testSplit() { + assertNull(StringUtils.split(null, ",")); + assertArrayEquals(new String[0], StringUtils.split("", ",")); + assertArrayEquals(new String[] {"ab", "cd", "ef"}, StringUtils.split("ab cd ef", null)); + assertArrayEquals(new String[] {"ab", "cd", "ef"}, StringUtils.split("ab cd ef", null)); + assertArrayEquals(new String[] {"ab", "cd", "ef"}, StringUtils.split("ab:cd:ef", ":")); } @Test - public void testTokenizeToStringArray() { + void testTokenizeToStringArray() { // Test case 1: Empty string String str1 = ""; String delimiters1 = ","; @@ -245,7 +248,7 @@ public void testTokenizeToStringArray() { boolean ignoreEmptyTokens1 = false; String[] expected1 = new String[0]; String[] result1 = StringUtils.tokenizeToStringArray(str1, delimiters1, trimTokens1, ignoreEmptyTokens1); - Assert.assertArrayEquals(expected1, result1); + assertArrayEquals(expected1, result1); // Test case 2: Null string String str2 = null; @@ -254,7 +257,7 @@ public void testTokenizeToStringArray() { boolean ignoreEmptyTokens2 = true; String[] expected2 = new String[0]; String[] result2 = StringUtils.tokenizeToStringArray(str2, delimiters2, trimTokens2, ignoreEmptyTokens2); - Assert.assertArrayEquals(expected2, result2); + assertArrayEquals(expected2, result2); // Test case 3: Single token String str3 = "Hello"; @@ -263,7 +266,7 @@ public void testTokenizeToStringArray() { boolean ignoreEmptyTokens3 = false; String[] expected3 = {"Hello"}; String[] result3 = StringUtils.tokenizeToStringArray(str3, delimiters3, trimTokens3, ignoreEmptyTokens3); - Assert.assertArrayEquals(expected3, result3); + assertArrayEquals(expected3, result3); // Test case 4: Multiple tokens with trimming String str4 = " Hello, World, "; @@ -272,7 +275,7 @@ public void testTokenizeToStringArray() { boolean ignoreEmptyTokens4 = false; String[] expected4 = {"Hello", "World", ""}; String[] result4 = StringUtils.tokenizeToStringArray(str4, delimiters4, trimTokens4, ignoreEmptyTokens4); - Assert.assertArrayEquals(expected4, result4); + assertArrayEquals(expected4, result4); // Test case 5: Multiple tokens with empty tokens ignored String str5 = " ,Hello, ,World, "; @@ -281,233 +284,233 @@ public void testTokenizeToStringArray() { boolean ignoreEmptyTokens5 = true; String[] expected5 = {"Hello", "World"}; String[] result5 = StringUtils.tokenizeToStringArray(str5, delimiters5, trimTokens5, ignoreEmptyTokens5); - Assert.assertArrayEquals(expected5, result5); + assertArrayEquals(expected5, result5); } @Test - public void testHasText() { + void testHasText() { // Test case 1: Empty string - Assert.assertFalse(StringUtils.hasText("")); + assertFalse(StringUtils.hasText("")); // Test case 2: String with whitespace only - Assert.assertFalse(StringUtils.hasText(" ")); + assertFalse(StringUtils.hasText(" ")); // Test case 3: Null string - Assert.assertFalse(StringUtils.hasText(null)); + assertFalse(StringUtils.hasText(null)); // Test case 4: String with non-whitespace characters - Assert.assertTrue(StringUtils.hasText("hello")); + assertTrue(StringUtils.hasText("hello")); // Test case 5: String with both text and whitespace - Assert.assertTrue(StringUtils.hasText(" hello ")); + assertTrue(StringUtils.hasText(" hello ")); } @Test - public void testCleanPath() { + void testCleanPath() { // Test case 1: path with no length String path1 = ""; String expected1 = ""; - Assert.assertEquals(expected1, StringUtils.cleanPath(path1)); + assertEquals(expected1, StringUtils.cleanPath(path1)); // Test case 2: normal path String path2 = "path/to/file"; String expected2 = "path/to/file"; - Assert.assertEquals(expected2, StringUtils.cleanPath(path2)); + assertEquals(expected2, StringUtils.cleanPath(path2)); // Test case 3: path with Windows folder separator String path3 = "path\\to\\文件"; String expected3 = "path/to/文件"; - Assert.assertEquals(expected3, StringUtils.cleanPath(path3)); + assertEquals(expected3, StringUtils.cleanPath(path3)); // Test case 4: path with dot String path4 = "path/.."; String expected4 = ""; - Assert.assertEquals(expected4, StringUtils.cleanPath(path4)); + assertEquals(expected4, StringUtils.cleanPath(path4)); // Test case 5: path with top path String path5 = "path/../top"; String expected5 = "top"; - Assert.assertEquals(expected5, StringUtils.cleanPath(path5)); + assertEquals(expected5, StringUtils.cleanPath(path5)); // Test case 6: path with multiple top path String path6 = "path/../../top"; String expected6 = "../top"; - Assert.assertEquals(expected6, StringUtils.cleanPath(path6)); + assertEquals(expected6, StringUtils.cleanPath(path6)); // Test case 7: path with leading colon String path7 = "file:../top"; String expected7 = "file:../top"; - Assert.assertEquals(expected7, StringUtils.cleanPath(path7)); + assertEquals(expected7, StringUtils.cleanPath(path7)); // Test case 8: path with leading slash String path8 = "file:/path/../file"; String expected8 = "file:/file"; - Assert.assertEquals(expected8, StringUtils.cleanPath(path8)); + assertEquals(expected8, StringUtils.cleanPath(path8)); // Test case 9: path with empty prefix String path9 = "file:path/../file"; String expected9 = "file:file"; - Assert.assertEquals(expected9, StringUtils.cleanPath(path9)); + assertEquals(expected9, StringUtils.cleanPath(path9)); // Test case 10: prefix contain separator String path10 = "file/:path/../file"; String expected10 = "file/file"; - Assert.assertEquals(expected10, StringUtils.cleanPath(path10)); + assertEquals(expected10, StringUtils.cleanPath(path10)); // Test case 11: dot in file name String path11 = "file:/path/to/file.txt"; String expected11 = "file:/path/to/file.txt"; - Assert.assertEquals(expected11, StringUtils.cleanPath(path11)); + assertEquals(expected11, StringUtils.cleanPath(path11)); // Test case 12: dot in path String path12 = "file:/path/./file.txt"; String expected12 = "file:/path/file.txt"; - Assert.assertEquals(expected12, StringUtils.cleanPath(path12)); + assertEquals(expected12, StringUtils.cleanPath(path12)); // Test case 13: path with dot and slash String path13 = "file:aaa/../"; String expected13 = "file:./"; - Assert.assertEquals(expected13, StringUtils.cleanPath(path13)); + assertEquals(expected13, StringUtils.cleanPath(path13)); } @Test - public void testDelimitedListToStringArrayWithNull() { - Assert.assertEquals(0, StringUtils.delimitedListToStringArray(null, ",", "").length); - Assert.assertEquals(1, StringUtils.delimitedListToStringArray("a,b", null, "").length); + void testDelimitedListToStringArrayWithNull() { + assertEquals(0, StringUtils.delimitedListToStringArray(null, ",", "").length); + assertEquals(1, StringUtils.delimitedListToStringArray("a,b", null, "").length); } @Test - public void testDelimitedListToStringArrayWithEmptyDelimiter() { + void testDelimitedListToStringArrayWithEmptyDelimiter() { String testCase = "a,b"; String[] actual = StringUtils.delimitedListToStringArray(testCase, "", ""); - Assert.assertEquals(3, actual.length); - Assert.assertEquals("a", actual[0]); - Assert.assertEquals(",", actual[1]); - Assert.assertEquals("b", actual[2]); + assertEquals(3, actual.length); + assertEquals("a", actual[0]); + assertEquals(",", actual[1]); + assertEquals("b", actual[2]); } @Test - public void testDeleteAny() { + void testDeleteAny() { // Test case 1: inString is empty, charsToDelete is empty String inString1 = ""; String charsToDelete1 = ""; - Assert.assertEquals("", StringUtils.deleteAny(inString1, charsToDelete1)); + assertEquals("", StringUtils.deleteAny(inString1, charsToDelete1)); // Test case 2: inString is empty, charsToDelete is not empty String inString2 = ""; String charsToDelete2 = "abc"; - Assert.assertEquals("", StringUtils.deleteAny(inString2, charsToDelete2)); + assertEquals("", StringUtils.deleteAny(inString2, charsToDelete2)); // Test case 3: inString is not empty, charsToDelete is empty String inString3 = "abc"; String charsToDelete3 = ""; - Assert.assertEquals("abc", StringUtils.deleteAny(inString3, charsToDelete3)); + assertEquals("abc", StringUtils.deleteAny(inString3, charsToDelete3)); // Test case 4: inString is not empty, charsToDelete is not empty String inString4 = "abc"; String charsToDelete4 = "a"; - Assert.assertEquals("bc", StringUtils.deleteAny(inString4, charsToDelete4)); + assertEquals("bc", StringUtils.deleteAny(inString4, charsToDelete4)); // Test case 5: inString contains special characters String inString5 = "abc\n"; String charsToDelete5 = "\n"; - Assert.assertEquals("abc", StringUtils.deleteAny(inString5, charsToDelete5)); - + assertEquals("abc", StringUtils.deleteAny(inString5, charsToDelete5)); + // Test case 6: inString not contains special characters String inString6 = "abc\n"; String charsToDelete6 = "d"; - Assert.assertEquals("abc\n", StringUtils.deleteAny(inString6, charsToDelete6)); + assertEquals("abc\n", StringUtils.deleteAny(inString6, charsToDelete6)); } @Test - public void testReplace() { + void testReplace() { // Test case 1: pattern is empty - Assert.assertEquals("abc", StringUtils.replace("abc", "", "a")); + assertEquals("abc", StringUtils.replace("abc", "", "a")); // Test case 2: oldPattern less than newPattern - Assert.assertEquals("aabc", StringUtils.replace("abc", "a", "aa")); - + assertEquals("aabc", StringUtils.replace("abc", "a", "aa")); + // Test case 3: oldPattern more than newPattern - Assert.assertEquals("dc", StringUtils.replace("abc", "ab", "d")); + assertEquals("dc", StringUtils.replace("abc", "ab", "d")); } @Test - public void testApplyRelativePath() { + void testApplyRelativePath() { // Test case 1 String path1 = "/path/to/file"; String relativePath1 = "subfolder/subfile"; String expected1 = "/path/to/subfolder/subfile"; String result1 = StringUtils.applyRelativePath(path1, relativePath1); - Assert.assertEquals(expected1, result1); + assertEquals(expected1, result1); // Test case 2 String path2 = "path/to/file"; String relativePath2 = "subfolder/subfile"; String expected2 = "path/to/subfolder/subfile"; String result2 = StringUtils.applyRelativePath(path2, relativePath2); - Assert.assertEquals(expected2, result2); + assertEquals(expected2, result2); // Test case 3 String path3 = "/path/to/file"; String relativePath3 = "/subfolder/subfile"; String expected3 = "/path/to/subfolder/subfile"; String result3 = StringUtils.applyRelativePath(path3, relativePath3); - Assert.assertEquals(expected3, result3); + assertEquals(expected3, result3); //Test case 4 String path4 = "file"; String relativePath4 = "/subfolder/subfile"; String expected4 = "/subfolder/subfile"; String result4 = StringUtils.applyRelativePath(path4, relativePath4); - Assert.assertEquals(expected4, result4); + assertEquals(expected4, result4); } @Test - public void testGetFilename() { + void testGetFilename() { // Test case 1: null path String path1 = null; String result1 = StringUtils.getFilename(path1); - Assert.assertNull(result1); + assertNull(result1); // Test case 2: path without separator String path2 = "myFile.txt"; String expectedResult2 = "myFile.txt"; String result2 = StringUtils.getFilename(path2); - Assert.assertEquals(expectedResult2, result2); + assertEquals(expectedResult2, result2); // Test case 3: path with separator String path3 = "myPath/myFile.txt"; String expectedResult3 = "myFile.txt"; String result3 = StringUtils.getFilename(path3); - Assert.assertEquals(expectedResult3, result3); + assertEquals(expectedResult3, result3); // Test case 4: path with multiple separators String path4 = "myPath/subPath/myFile.txt"; String expectedResult4 = "myFile.txt"; String result4 = StringUtils.getFilename(path4); - Assert.assertEquals(expectedResult4, result4); + assertEquals(expectedResult4, result4); } @Test - public void testCapitalize() { + void testCapitalize() { // Test for an empty string String str1 = ""; - Assert.assertEquals("", StringUtils.capitalize(str1)); + assertEquals("", StringUtils.capitalize(str1)); // Test for a single word string String str2 = "hello"; - Assert.assertEquals("Hello", StringUtils.capitalize(str2)); + assertEquals("Hello", StringUtils.capitalize(str2)); // Test for a multiple word string String str3 = "hello world"; - Assert.assertEquals("Hello world", StringUtils.capitalize(str3)); + assertEquals("Hello world", StringUtils.capitalize(str3)); // Test for a string with special characters String str4 = "!@#$%^&*()"; - Assert.assertEquals("!@#$%^&*()", StringUtils.capitalize(str4)); + assertEquals("!@#$%^&*()", StringUtils.capitalize(str4)); // Test for a string with numbers String str5 = "abc123"; - Assert.assertEquals("Abc123", StringUtils.capitalize(str5)); + assertEquals("Abc123", StringUtils.capitalize(str5)); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/ThreadFactoryBuilderTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/ThreadFactoryBuilderTest.java index 0a65577456f..a8c9a82d4ee 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/ThreadFactoryBuilderTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/ThreadFactoryBuilderTest.java @@ -16,113 +16,101 @@ package com.alibaba.nacos.common.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * thread factory builder unit test. + * * @author zzq * @date 2021/8/3 */ -public class ThreadFactoryBuilderTest { +class ThreadFactoryBuilderTest { int priority = 2; @Test - public void simpleTest() { - ThreadFactory threadFactory = new ThreadFactoryBuilder() - .daemon(true) - .priority(priority) - .nameFormat("nacos-grpc-executor-%d") - .build(); + void simpleTest() { + ThreadFactory threadFactory = new ThreadFactoryBuilder().daemon(true).priority(priority) + .nameFormat("nacos-grpc-executor-%d").build(); Thread thread1 = threadFactory.newThread(() -> { }); - Assert.assertEquals("nacos-grpc-executor-0", thread1.getName()); - Assert.assertEquals(priority, thread1.getPriority()); - Assert.assertTrue(thread1.isDaemon()); + assertEquals("nacos-grpc-executor-0", thread1.getName()); + assertEquals(priority, thread1.getPriority()); + assertTrue(thread1.isDaemon()); Thread thread2 = threadFactory.newThread(() -> { }); - Assert.assertEquals("nacos-grpc-executor-1", thread2.getName()); - Assert.assertEquals(priority, thread2.getPriority()); - Assert.assertTrue(thread2.isDaemon()); + assertEquals("nacos-grpc-executor-1", thread2.getName()); + assertEquals(priority, thread2.getPriority()); + assertTrue(thread2.isDaemon()); } @Test - public void customizeFactoryTest() { + void customizeFactoryTest() { String threadName = "hello is me!"; ThreadFactory myFactory = r -> { Thread thread = new Thread(); thread.setName(threadName); return thread; }; - ThreadFactory factory = new ThreadFactoryBuilder() - .daemon(true) - .priority(priority) - .customizeFactory(myFactory) - .build(); - Thread thread = factory.newThread(() -> { }); - Assert.assertEquals(threadName, thread.getName()); + ThreadFactory factory = new ThreadFactoryBuilder().daemon(true).priority(priority).customizeFactory(myFactory).build(); + Thread thread = factory.newThread(() -> { + }); + assertEquals(threadName, thread.getName()); } @Test - public void uncaughtExceptionHandlerTest() throws Exception { + void uncaughtExceptionHandlerTest() throws Exception { AtomicBoolean state = new AtomicBoolean(false); - ThreadFactory threadFactory = new ThreadFactoryBuilder() - .daemon(true) - .priority(priority) - .nameFormat("nacos-grpc-executor-%d") - .uncaughtExceptionHandler((t, e) -> state.set(true)) - .build(); + ThreadFactory threadFactory = new ThreadFactoryBuilder().daemon(true).priority(priority) + .nameFormat("nacos-grpc-executor-%d").uncaughtExceptionHandler((t, e) -> state.set(true)).build(); threadFactory.newThread(() -> { throw new NullPointerException("null pointer"); }).start(); TimeUnit.SECONDS.sleep(1); - Assert.assertTrue(state.get()); + assertTrue(state.get()); } - @Test(expected = IllegalArgumentException.class) - public void propertyPriorityTest1() { - new ThreadFactoryBuilder() - .priority(11) - .nameFormat("nacos-grpc-executor-%d") - .build(); + @Test + void propertyPriorityTest1() { + assertThrows(IllegalArgumentException.class, () -> { + new ThreadFactoryBuilder().priority(11).nameFormat("nacos-grpc-executor-%d").build(); + }); } - @Test(expected = IllegalArgumentException.class) - public void propertyPriorityTest2() { - new ThreadFactoryBuilder() - .priority(-1) - .nameFormat("nacos-grpc-executor-%d") - .build(); + @Test + void propertyPriorityTest2() { + assertThrows(IllegalArgumentException.class, () -> { + new ThreadFactoryBuilder().priority(-1).nameFormat("nacos-grpc-executor-%d").build(); + }); } - @Test(expected = IllegalArgumentException.class) - public void propertyNameFormatTest() { - new ThreadFactoryBuilder() - .priority(priority) - .nameFormat(null) - .build(); + @Test + void propertyNameFormatTest() { + assertThrows(IllegalArgumentException.class, () -> { + new ThreadFactoryBuilder().priority(priority).nameFormat(null).build(); + }); } - @Test(expected = IllegalArgumentException.class) - public void propertyUncaughtExceptionHandlerTest() { - new ThreadFactoryBuilder() - .priority(priority) - .nameFormat("nacos-grpc-executor-%d") - .uncaughtExceptionHandler(null) - .build(); + @Test + void propertyUncaughtExceptionHandlerTest() { + assertThrows(IllegalArgumentException.class, () -> { + new ThreadFactoryBuilder().priority(priority).nameFormat("nacos-grpc-executor-%d").uncaughtExceptionHandler(null) + .build(); + }); } - @Test(expected = IllegalArgumentException.class) - public void propertyCustomizeFactoryHandlerTest() { - new ThreadFactoryBuilder() - .priority(priority) - .nameFormat("nacos-grpc-executor-%d") - .customizeFactory(null) - .build(); + @Test + void propertyCustomizeFactoryHandlerTest() { + assertThrows(IllegalArgumentException.class, () -> { + new ThreadFactoryBuilder().priority(priority).nameFormat("nacos-grpc-executor-%d").customizeFactory(null).build(); + }); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/ThreadUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/ThreadUtilsTest.java index e6ea4f1b82c..534188de4f0 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/ThreadUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/ThreadUtilsTest.java @@ -16,9 +16,9 @@ package com.alibaba.nacos.common.utils; -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 org.slf4j.Logger; import java.util.concurrent.CountDownLatch; @@ -26,31 +26,31 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -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; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class ThreadUtilsTest { +class ThreadUtilsTest { private ExecutorService executorService; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { System.setProperty("nacos.common.processors", "2"); executorService = Executors.newFixedThreadPool(1); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { System.setProperty("nacos.common.processors", ""); ThreadUtils.shutdownThreadPool(executorService); } @Test - public void testLatchAwait() { + void testLatchAwait() { final CountDownLatch countDownLatch = new CountDownLatch(1); long currentTime = System.currentTimeMillis(); executorService.execute(() -> { @@ -62,7 +62,7 @@ public void testLatchAwait() { } @Test - public void testLatchAwaitForTimeout() { + void testLatchAwaitForTimeout() { final CountDownLatch countDownLatch = new CountDownLatch(1); long currentTime = System.currentTimeMillis(); ThreadUtils.latchAwait(countDownLatch, 50, TimeUnit.MILLISECONDS); @@ -71,13 +71,13 @@ public void testLatchAwaitForTimeout() { } @Test - public void testGetSuitableThreadCount() { + void testGetSuitableThreadCount() { assertEquals(4, ThreadUtils.getSuitableThreadCount()); assertEquals(8, ThreadUtils.getSuitableThreadCount(3)); } @Test - public void testShutdownThreadPoolWithInterruptedException() throws InterruptedException { + void testShutdownThreadPoolWithInterruptedException() throws InterruptedException { ExecutorService executor = mock(ExecutorService.class); when(executor.awaitTermination(100, TimeUnit.MILLISECONDS)).thenThrow(new InterruptedException()); ThreadUtils.shutdownThreadPool(executor); @@ -85,7 +85,7 @@ public void testShutdownThreadPoolWithInterruptedException() throws InterruptedE } @Test - public void testShutdownThreadPoolWithOtherException() throws InterruptedException { + void testShutdownThreadPoolWithOtherException() throws InterruptedException { ExecutorService executor = mock(ExecutorService.class); Logger logger = mock(Logger.class); Throwable cause = new RuntimeException(); @@ -96,7 +96,7 @@ public void testShutdownThreadPoolWithOtherException() throws InterruptedExcepti } @Test - public void testAddShutdownHook() { + void testAddShutdownHook() { Runnable shutdownHook = () -> { }; ThreadUtils.addShutdownHook(shutdownHook); diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/TlsTypeResolveTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/TlsTypeResolveTest.java index 40ac12d35ed..b2383a87c54 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/TlsTypeResolveTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/TlsTypeResolveTest.java @@ -17,27 +17,28 @@ package com.alibaba.nacos.common.utils; import io.grpc.netty.shaded.io.netty.handler.ssl.SslProvider; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class TlsTypeResolveTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +class TlsTypeResolveTest { + @Test - public void test() { - + void test() { + SslProvider openssl = TlsTypeResolve.getSslProvider("openssl"); - Assert.assertEquals(SslProvider.OPENSSL, openssl); - + assertEquals(SslProvider.OPENSSL, openssl); + SslProvider openSsL = TlsTypeResolve.getSslProvider("openSSL"); - Assert.assertEquals(SslProvider.OPENSSL, openSsL); - + assertEquals(SslProvider.OPENSSL, openSsL); + SslProvider jdk = TlsTypeResolve.getSslProvider("JDK"); - Assert.assertEquals(SslProvider.JDK, jdk); - + assertEquals(SslProvider.JDK, jdk); + SslProvider anySsl = TlsTypeResolve.getSslProvider("anySSL"); - Assert.assertEquals(SslProvider.OPENSSL, anySsl); + assertEquals(SslProvider.OPENSSL, anySsl); SslProvider refcnt = TlsTypeResolve.getSslProvider("openSSL_refcnt"); - Assert.assertEquals(SslProvider.OPENSSL_REFCNT, refcnt); + assertEquals(SslProvider.OPENSSL_REFCNT, refcnt); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/TypeUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/TypeUtilsTest.java index 0e98c560b52..9fc3bf21efd 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/TypeUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/TypeUtilsTest.java @@ -16,57 +16,67 @@ package com.alibaba.nacos.common.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List; import java.util.Map; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + /** * type utils test. * * @author zzq */ -public class TypeUtilsTest { +class TypeUtilsTest { @Test - public void parameterize() { + void parameterize() { ParameterizedType stringComparableType = TypeUtils.parameterize(List.class, String.class); - Assert.assertEquals("java.util.List", stringComparableType.toString()); - Assert.assertEquals(List.class, stringComparableType.getRawType()); - Assert.assertNull(stringComparableType.getOwnerType()); - Assert.assertEquals(1, stringComparableType.getActualTypeArguments().length); - Assert.assertEquals(String.class, stringComparableType.getActualTypeArguments()[0]); + assertEquals("java.util.List", stringComparableType.toString()); + assertEquals(List.class, stringComparableType.getRawType()); + assertNull(stringComparableType.getOwnerType()); + assertEquals(1, stringComparableType.getActualTypeArguments().length); + assertEquals(String.class, stringComparableType.getActualTypeArguments()[0]); ParameterizedType stringIntegerComparableType = TypeUtils.parameterize(Map.class, String.class, Integer.class); - Assert.assertEquals("java.util.Map", - stringIntegerComparableType.toString()); - Assert.assertEquals(Map.class, stringIntegerComparableType.getRawType()); - Assert.assertNull(stringComparableType.getOwnerType()); - Assert.assertEquals(2, stringIntegerComparableType.getActualTypeArguments().length); - Assert.assertEquals(String.class, stringIntegerComparableType.getActualTypeArguments()[0]); - Assert.assertEquals(Integer.class, stringIntegerComparableType.getActualTypeArguments()[1]); + assertEquals("java.util.Map", stringIntegerComparableType.toString()); + assertEquals(Map.class, stringIntegerComparableType.getRawType()); + assertNull(stringComparableType.getOwnerType()); + assertEquals(2, stringIntegerComparableType.getActualTypeArguments().length); + assertEquals(String.class, stringIntegerComparableType.getActualTypeArguments()[0]); + assertEquals(Integer.class, stringIntegerComparableType.getActualTypeArguments()[1]); } - @Test(expected = NullPointerException.class) - public void testParameterizeForNull() { - TypeUtils.parameterize(null, String.class); + @Test + void testParameterizeForNull() { + assertThrows(NullPointerException.class, () -> { + TypeUtils.parameterize(null, String.class); + }); } - @Test(expected = NullPointerException.class) - public void testParameterizeForNullType() { - TypeUtils.parameterize(List.class, (Type[]) null); + @Test + void testParameterizeForNullType() { + assertThrows(NullPointerException.class, () -> { + TypeUtils.parameterize(List.class, (Type[]) null); + }); } - @Test(expected = IllegalArgumentException.class) - public void testParameterizeForNullTypeArray() { - TypeUtils.parameterize(List.class, (Type) null); + @Test + void testParameterizeForNullTypeArray() { + assertThrows(IllegalArgumentException.class, () -> { + TypeUtils.parameterize(List.class, (Type) null); + }); } - @Test(expected = IllegalArgumentException.class) - public void testParameterizeForDiffLength() { - TypeUtils.parameterize(List.class, String.class, Integer.class); + @Test + void testParameterizeForDiffLength() { + assertThrows(IllegalArgumentException.class, () -> { + TypeUtils.parameterize(List.class, String.class, Integer.class); + }); } } diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/UuidUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/UuidUtilsTest.java index 1d40252d1e0..3425ddc40b2 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/UuidUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/UuidUtilsTest.java @@ -16,14 +16,14 @@ package com.alibaba.nacos.common.utils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.UUID; -public class UuidUtilsTest { +class UuidUtilsTest { @Test - public void testGenerateUuid() { + void testGenerateUuid() { String uuid = UuidUtils.generateUuid(); // try parse to UUID. UUID.fromString(uuid); diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/VersionUtilsTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/VersionUtilsTest.java index 4978a1cb039..41abdcccf84 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/VersionUtilsTest.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/VersionUtilsTest.java @@ -16,80 +16,90 @@ package com.alibaba.nacos.common.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.net.URL; -public class VersionUtilsTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class VersionUtilsTest { @Test - public void testVersionCompareLt() { - Assert.assertTrue(VersionUtils.compareVersion("1.2.0", "1.2.1") < 0); - Assert.assertTrue(VersionUtils.compareVersion("0.2.0", "1.2.0") < 0); - Assert.assertTrue(VersionUtils.compareVersion("1.2.0", "1.3.0") < 0); + void testVersionCompareLt() { + assertTrue(VersionUtils.compareVersion("1.2.0", "1.2.1") < 0); + assertTrue(VersionUtils.compareVersion("0.2.0", "1.2.0") < 0); + assertTrue(VersionUtils.compareVersion("1.2.0", "1.3.0") < 0); } @Test - public void testVersionCompareGt() { - Assert.assertTrue(VersionUtils.compareVersion("1.2.2", "1.2.1") > 0); - Assert.assertTrue(VersionUtils.compareVersion("2.2.0", "1.2.0") > 0); - Assert.assertTrue(VersionUtils.compareVersion("1.3.0", "1.2.0") > 0); + void testVersionCompareGt() { + assertTrue(VersionUtils.compareVersion("1.2.2", "1.2.1") > 0); + assertTrue(VersionUtils.compareVersion("2.2.0", "1.2.0") > 0); + assertTrue(VersionUtils.compareVersion("1.3.0", "1.2.0") > 0); } @Test - public void testVersionCompareEt() { - Assert.assertEquals(0, VersionUtils.compareVersion("1.2.1", "1.2.1")); + void testVersionCompareEt() { + assertEquals(0, VersionUtils.compareVersion("1.2.1", "1.2.1")); } @Test - public void testVersionCompareLtWithChar() { - Assert.assertTrue(VersionUtils.compareVersion("1.2.0-beta", "1.2.1") < 0); + void testVersionCompareLtWithChar() { + assertTrue(VersionUtils.compareVersion("1.2.0-beta", "1.2.1") < 0); } @Test - public void testVersionCompareGtWithChar() { - Assert.assertTrue(VersionUtils.compareVersion("1.2.2-beta", "1.2.1-beta") > 0); + void testVersionCompareGtWithChar() { + assertTrue(VersionUtils.compareVersion("1.2.2-beta", "1.2.1-beta") > 0); } @Test - public void testVersionCompareEtWithChar() { - Assert.assertEquals(0, VersionUtils.compareVersion("1.2.1", "1.2.1-beta")); + void testVersionCompareEtWithChar() { + assertEquals(0, VersionUtils.compareVersion("1.2.1", "1.2.1-beta")); } @Test - public void testVersionCompareResourceNotExist() { + void testVersionCompareResourceNotExist() { URL resource = VersionUtils.class.getClassLoader().getResource("nacos-version.txt"); - Assert.assertNotNull(resource); + assertNotNull(resource); File originFile = new File(resource.getFile()); File tempFile = new File(originFile.getAbsolutePath() + ".rename"); - Assert.assertTrue(originFile.renameTo(tempFile)); - + assertTrue(originFile.renameTo(tempFile)); + // not throw any exception VersionUtils.compareVersion("1.2.1", "1.2.1"); - - Assert.assertTrue(tempFile.renameTo(originFile)); + + assertTrue(tempFile.renameTo(originFile)); } - @Test(expected = IllegalArgumentException.class) - public void testVersionCompareVersionNotValid1() { - VersionUtils.compareVersion("1.2.1.1", "1.2.1.1"); + @Test + void testVersionCompareVersionNotValid1() { + assertThrows(IllegalArgumentException.class, () -> { + VersionUtils.compareVersion("1.2.1.1", "1.2.1.1"); + }); } - @Test(expected = IllegalArgumentException.class) - public void testVersionCompareVersionNotValid2() { - VersionUtils.compareVersion("1.2.1", "1.2.1.1"); + @Test + void testVersionCompareVersionNotValid2() { + assertThrows(IllegalArgumentException.class, () -> { + VersionUtils.compareVersion("1.2.1", "1.2.1.1"); + }); } - @Test(expected = IllegalArgumentException.class) - public void testVersionCompareVersionNotValid3() { - VersionUtils.compareVersion("1.2.1.1", "1.2.1"); + @Test + void testVersionCompareVersionNotValid3() { + assertThrows(IllegalArgumentException.class, () -> { + VersionUtils.compareVersion("1.2.1.1", "1.2.1"); + }); } @Test - public void testFullClientVersion() { - Assert.assertNotNull(VersionUtils.getFullClientVersion()); - Assert.assertTrue(VersionUtils.getFullClientVersion().startsWith("Nacos-Java-Client:v")); + void testFullClientVersion() { + assertNotNull(VersionUtils.getFullClientVersion()); + assertTrue(VersionUtils.getFullClientVersion().startsWith("Nacos-Java-Client:v")); } } \ No newline at end of file diff --git a/common/src/test/java/com/alibaba/nacos/common/utils/to/User.java b/common/src/test/java/com/alibaba/nacos/common/utils/to/User.java index f74846db434..241f0db019e 100644 --- a/common/src/test/java/com/alibaba/nacos/common/utils/to/User.java +++ b/common/src/test/java/com/alibaba/nacos/common/utils/to/User.java @@ -17,8 +17,9 @@ package com.alibaba.nacos.common.utils.to; public class User { + private Integer id; - + private String name; public User(Integer id, String name) { diff --git a/config/pom.xml b/config/pom.xml index f37acf76067..c10e7df3796 100644 --- a/config/pom.xml +++ b/config/pom.xml @@ -124,6 +124,16 @@ spring-boot-test-autoconfigure test + + org.springframework + spring-test + test + + + org.hamcrest + hamcrest + test + diff --git a/config/src/main/java/com/alibaba/nacos/config/server/configuration/ConfigCommonConfig.java b/config/src/main/java/com/alibaba/nacos/config/server/configuration/ConfigCommonConfig.java index 83884f85c5c..ac6e286877d 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/configuration/ConfigCommonConfig.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/configuration/ConfigCommonConfig.java @@ -33,6 +33,8 @@ public class ConfigCommonConfig extends AbstractDynamicConfig { private int maxPushRetryTimes = 50; + private boolean derbyOpsEnabled = false; + private ConfigCommonConfig() { super(CONFIG_COMMON); resetConfig(); @@ -50,13 +52,28 @@ public void setMaxPushRetryTimes(int maxPushRetryTimes) { this.maxPushRetryTimes = maxPushRetryTimes; } + public boolean isDerbyOpsEnabled() { + return derbyOpsEnabled; + } + + public void setDerbyOpsEnabled(boolean derbyOpsEnabled) { + this.derbyOpsEnabled = derbyOpsEnabled; + } + @Override protected void getConfigFromEnv() { maxPushRetryTimes = EnvUtil.getProperty("nacos.config.push.maxRetryTime", Integer.class, 50); + derbyOpsEnabled = EnvUtil.getProperty("nacos.config.derby.ops.enabled", Boolean.class, false); } @Override protected String printConfig() { - return "ConfigCommonConfigs{" + "maxPushRetryTimes=" + maxPushRetryTimes + '}'; + return toString(); + } + + @Override + public String toString() { + return "ConfigCommonConfig{" + "maxPushRetryTimes=" + maxPushRetryTimes + ", derbyOpsEnabled=" + derbyOpsEnabled + + '}'; } } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/constant/ParametersField.java b/config/src/main/java/com/alibaba/nacos/config/server/constant/ParametersField.java new file mode 100644 index 00000000000..bf8886b21cd --- /dev/null +++ b/config/src/main/java/com/alibaba/nacos/config/server/constant/ParametersField.java @@ -0,0 +1,31 @@ +/* + * Copyright 1999-2018 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.config.server.constant; + +/** + * Parameters Field. + * + * @author haiqi.wang + * @date 2024/08/13 + */ +public final class ParametersField { + + /** + * Types. + */ + public static final String TYPES = "types"; +} \ No newline at end of file diff --git a/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java b/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java index d10aa0dacbf..a5c042eb718 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java @@ -26,6 +26,7 @@ import com.alibaba.nacos.common.utils.Pair; import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.config.server.constant.Constants; +import com.alibaba.nacos.config.server.constant.ParametersField; import com.alibaba.nacos.config.server.controller.parameters.SameNamespaceCloneConfigBean; import com.alibaba.nacos.config.server.model.ConfigAdvanceInfo; import com.alibaba.nacos.config.server.model.ConfigAllInfo; @@ -418,6 +419,7 @@ public Page fuzzySearchConfig(@RequestParam("dataId") String dataId, @RequestParam("group") String group, @RequestParam(value = "appName", required = false) String appName, @RequestParam(value = "tenant", required = false, defaultValue = StringUtils.EMPTY) String tenant, @RequestParam(value = "config_tags", required = false) String configTags, + @RequestParam(value = "types", required = false) String types, @RequestParam("pageNo") int pageNo, @RequestParam("pageSize") int pageSize) { MetricsMonitor.getFuzzySearchMonitor().incrementAndGet(); Map configAdvanceInfo = new HashMap<>(50); @@ -427,6 +429,9 @@ public Page fuzzySearchConfig(@RequestParam("dataId") String dataId, if (StringUtils.isNotBlank(configTags)) { configAdvanceInfo.put("config_tags", configTags); } + if (StringUtils.isNotBlank(types)) { + configAdvanceInfo.put(ParametersField.TYPES, types); + } try { return configInfoPersistService.findConfigInfoLike4Page(pageNo, pageSize, dataId, group, tenant, configAdvanceInfo); @@ -626,6 +631,9 @@ public RestResult> importAndPublishConfig(HttpServletRequest failedData.put("succCount", 0); return RestResultUtils.buildResult(ResultCodeEnum.NAMESPACE_NOT_EXIST, failedData); } + if (StringUtils.isBlank(srcUser)) { + srcUser = RequestUtil.getSrcUserName(request); + } List configInfoList = new ArrayList<>(); List> unrecognizedList = new ArrayList<>(); try { @@ -900,7 +908,9 @@ public RestResult> cloneConfig(HttpServletRequest request, ci.getEncryptedDataKey() == null ? StringUtils.EMPTY : ci.getEncryptedDataKey()); configInfoList4Clone.add(ci4save); } - + if (StringUtils.isBlank(srcUser)) { + srcUser = RequestUtil.getSrcUserName(request); + } final String srcIp = RequestUtil.getRemoteIp(request); String requestIpApp = RequestUtil.getAppName(request); final Timestamp time = TimeUtils.getCurrentTime(); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigOpsController.java b/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigOpsController.java index 9edc610abb2..f7afe9a32bb 100755 --- a/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigOpsController.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigOpsController.java @@ -17,24 +17,25 @@ package com.alibaba.nacos.config.server.controller; import com.alibaba.nacos.auth.annotation.Secured; -import com.alibaba.nacos.config.server.paramcheck.ConfigDefaultHttpParamExtractor; -import com.alibaba.nacos.core.paramcheck.ExtractorManager; -import com.alibaba.nacos.persistence.configuration.DatasourceConfiguration; -import com.alibaba.nacos.plugin.auth.constant.ActionTypes; import com.alibaba.nacos.common.model.RestResult; import com.alibaba.nacos.common.model.RestResultUtils; import com.alibaba.nacos.common.notify.NotifyCenter; +import com.alibaba.nacos.common.utils.StringUtils; +import com.alibaba.nacos.config.server.configuration.ConfigCommonConfig; import com.alibaba.nacos.config.server.constant.Constants; -import com.alibaba.nacos.persistence.model.event.DerbyImportEvent; -import com.alibaba.nacos.persistence.datasource.DynamicDataSource; -import com.alibaba.nacos.persistence.datasource.LocalDataSourceServiceImpl; +import com.alibaba.nacos.config.server.paramcheck.ConfigDefaultHttpParamExtractor; import com.alibaba.nacos.config.server.service.dump.DumpService; -import com.alibaba.nacos.persistence.repository.embedded.operate.DatabaseOperate; import com.alibaba.nacos.config.server.utils.LogUtil; +import com.alibaba.nacos.core.paramcheck.ExtractorManager; import com.alibaba.nacos.core.utils.WebUtils; +import com.alibaba.nacos.persistence.configuration.DatasourceConfiguration; +import com.alibaba.nacos.persistence.datasource.DynamicDataSource; +import com.alibaba.nacos.persistence.datasource.LocalDataSourceServiceImpl; +import com.alibaba.nacos.persistence.model.event.DerbyImportEvent; +import com.alibaba.nacos.persistence.repository.embedded.operate.DatabaseOperate; +import com.alibaba.nacos.plugin.auth.constant.ActionTypes; import com.alibaba.nacos.plugin.auth.constant.SignType; import com.alibaba.nacos.sys.utils.ApplicationUtils; -import com.alibaba.nacos.common.utils.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; @@ -106,8 +107,12 @@ public RestResult derbyOps(@RequestParam(value = "sql") String sql) { if (!DatasourceConfiguration.isEmbeddedStorage()) { return RestResultUtils.failed("The current storage mode is not Derby"); } - LocalDataSourceServiceImpl dataSourceService = (LocalDataSourceServiceImpl) DynamicDataSource - .getInstance().getDataSource(); + if (!ConfigCommonConfig.getInstance().isDerbyOpsEnabled()) { + return RestResultUtils.failed( + "Derby ops is disabled, please set `nacos.config.derby.ops.enabled=true` to enabled this feature."); + } + LocalDataSourceServiceImpl dataSourceService = (LocalDataSourceServiceImpl) DynamicDataSource.getInstance() + .getDataSource(); if (StringUtils.startsWithIgnoreCase(sql, selectSign)) { if (!StringUtils.containsIgnoreCase(sql, limitSign)) { sql += limit; @@ -139,6 +144,11 @@ public DeferredResult> importDerby(@RequestParam(value = "fil response.setResult(RestResultUtils.failed("Limited to embedded storage mode")); return response; } + if (!ConfigCommonConfig.getInstance().isDerbyOpsEnabled()) { + response.setResult(RestResultUtils.failed( + "Derby ops is disabled, please set `nacos.config.derby.ops.enabled=true` to enabled this feature.")); + return response; + } DatabaseOperate databaseOperate = ApplicationUtils.getBean(DatabaseOperate.class); WebUtils.onFileUpload(multipartFile, file -> { NotifyCenter.publishEvent(new DerbyImportEvent(false)); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/controller/v2/ConfigControllerV2.java b/config/src/main/java/com/alibaba/nacos/config/server/controller/v2/ConfigControllerV2.java index 68fae8550c9..b7f4b9ffdd9 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/controller/v2/ConfigControllerV2.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/controller/v2/ConfigControllerV2.java @@ -118,9 +118,13 @@ public void getConfig(HttpServletRequest request, HttpServletResponse response, public Result publishConfig(ConfigForm configForm, HttpServletRequest request) throws NacosException { // check required field configForm.validate(); - // encrypted - Pair pair = EncryptionHandler.encryptHandler(configForm.getDataId(), configForm.getContent()); - configForm.setContent(pair.getSecond()); + String encryptedDataKeyFinal = configForm.getEncryptedDataKey(); + if (StringUtils.isBlank(encryptedDataKeyFinal)) { + // encrypted + Pair pair = EncryptionHandler.encryptHandler(configForm.getDataId(), configForm.getContent()); + configForm.setContent(pair.getSecond()); + encryptedDataKeyFinal = pair.getFirst(); + } //fix issue #9783 configForm.setNamespaceId(NamespaceUtil.processNamespaceParameter(configForm.getNamespaceId())); // check param @@ -134,16 +138,14 @@ public Result publishConfig(ConfigForm configForm, HttpServletRequest r if (!ConfigType.isValidType(configForm.getType())) { configForm.setType(ConfigType.getDefaultType().getType()); } - + ConfigRequestInfo configRequestInfo = new ConfigRequestInfo(); configRequestInfo.setSrcIp(RequestUtil.getRemoteIp(request)); configRequestInfo.setRequestIpApp(RequestUtil.getAppName(request)); configRequestInfo.setBetaIps(request.getHeader("betaIps")); configRequestInfo.setCasMd5(request.getHeader("casMd5")); - - String encryptedDataKey = pair.getFirst(); - - return Result.success(configOperationService.publishConfig(configForm, configRequestInfo, encryptedDataKey)); + + return Result.success(configOperationService.publishConfig(configForm, configRequestInfo, encryptedDataKeyFinal)); } /** diff --git a/config/src/main/java/com/alibaba/nacos/config/server/model/form/ConfigForm.java b/config/src/main/java/com/alibaba/nacos/config/server/model/form/ConfigForm.java index 080e9b8d554..cf58f4a6d89 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/model/form/ConfigForm.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/model/form/ConfigForm.java @@ -60,11 +60,14 @@ public class ConfigForm implements Serializable { private String schema; + private String encryptedDataKey; + public ConfigForm() { } public ConfigForm(String dataId, String group, String namespaceId, String content, String tag, String appName, - String srcUser, String configTags, String desc, String use, String effect, String type, String schema) { + String srcUser, String configTags, String desc, String use, String effect, String type, String schema, + String encryptedDataKey) { this.dataId = dataId; this.group = group; this.namespaceId = namespaceId; @@ -78,6 +81,7 @@ public ConfigForm(String dataId, String group, String namespaceId, String conten this.effect = effect; this.type = type; this.schema = schema; + this.encryptedDataKey = encryptedDataKey; } public String getDataId() { @@ -184,6 +188,14 @@ public void setSchema(String schema) { this.schema = schema; } + public String getEncryptedDataKey() { + return encryptedDataKey; + } + + public void setEncryptedDataKey(String encryptedDataKey) { + this.encryptedDataKey = encryptedDataKey; + } + @Override public boolean equals(Object o) { if (this == o) { @@ -196,15 +208,16 @@ public boolean equals(Object o) { return dataId.equals(configForm.dataId) && group.equals(configForm.group) && Objects.equals(namespaceId, configForm.namespaceId) && content.equals(configForm.content) && Objects.equals(tag, configForm.tag) && Objects .equals(appName, configForm.appName) && Objects.equals(srcUser, configForm.srcUser) && Objects - .equals(configTags, configForm.configTags) && Objects.equals(desc, configForm.desc) && Objects - .equals(use, configForm.use) && Objects.equals(effect, configForm.effect) && Objects - .equals(type, configForm.type) && Objects.equals(schema, configForm.schema); + .equals(configTags, configForm.configTags) && Objects.equals(desc, configForm.desc) && Objects.equals( + use, configForm.use) && Objects.equals(effect, configForm.effect) && Objects.equals(type, + configForm.type) && Objects.equals(schema, configForm.schema) && Objects.equals(encryptedDataKey, + configForm.encryptedDataKey); } @Override public int hashCode() { return Objects.hash(dataId, group, namespaceId, content, tag, appName, srcUser, configTags, desc, use, effect, type, - schema); + schema, encryptedDataKey); } @Override @@ -213,7 +226,7 @@ public String toString() { + ", content='" + content + '\'' + ", tag='" + tag + '\'' + ", appName='" + appName + '\'' + ", srcUser='" + srcUser + '\'' + ", configTags='" + configTags + '\'' + ", desc='" + desc + '\'' + ", use='" + use + '\'' + ", effect='" + effect + '\'' + ", type='" + type + '\'' + ", schema='" - + schema + '\'' + '}'; + + schema + '\'' + ", encryptedDataKey='" + encryptedDataKey + '\'' + '}'; } /** diff --git a/config/src/main/java/com/alibaba/nacos/config/server/monitor/MetricsMonitor.java b/config/src/main/java/com/alibaba/nacos/config/server/monitor/MetricsMonitor.java index aca6c68e9f1..33842db2616 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/monitor/MetricsMonitor.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/monitor/MetricsMonitor.java @@ -194,6 +194,10 @@ public static Timer getNotifyRtTimer() { return NacosMeterRegistryCenter.timer(METER_REGISTRY, "nacos_timer", "module", "config", "name", "notifyRt"); } + public static Timer getDumpRtTimer() { + return NacosMeterRegistryCenter.timer(METER_REGISTRY, "nacos_timer", "module", "config", "name", "dumpRt"); + } + public static Counter getIllegalArgumentException() { return NacosMeterRegistryCenter .counter(METER_REGISTRY, "nacos_exception", "module", "config", "name", "illegalArgument"); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigCacheService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigCacheService.java index 89cb9353636..beb7c6e6181 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigCacheService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigCacheService.java @@ -139,7 +139,7 @@ public static boolean dumpWithMd5(String dataId, String group, String tenant, St DUMP_LOG.error("[dump-exception] save disk error. " + groupKey + ", " + ioe); if (ioe.getMessage() != null) { String errMsg = ioe.getMessage(); - if (NO_SPACE_CN.equals(errMsg) || NO_SPACE_EN.equals(errMsg) || errMsg.contains(DISK_QUOTA_CN) + if (errMsg.contains(NO_SPACE_CN) || errMsg.contains(NO_SPACE_EN) || errMsg.contains(DISK_QUOTA_CN) || errMsg.contains(DISK_QUOTA_EN)) { // Protect from disk full. FATAL_LOG.error("Local Disk Full,Exit", ioe); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigSubService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigSubService.java index 31b2a2c9234..ebf7afabb1a 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigSubService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigSubService.java @@ -83,6 +83,11 @@ private List runConfigListenerCollectionJob(Map pa return new ClusterListenerJob(params, completionService, memberManager).runJobs(); } + private List runConfigListenerByIpCollectionJob(Map params, + CompletionService completionService) { + return new ClusterListenerByIpJob(params, completionService, memberManager).runJobs(); + } + static class ClusterListenerJob extends ClusterJob { static final String URL = Constants.COMMUNICATION_CONTROLLER_PATH + "/configWatchers"; @@ -93,6 +98,16 @@ static class ClusterListenerJob extends ClusterJob { } } + static class ClusterListenerByIpJob extends ClusterJob { + + static final String URL = Constants.COMMUNICATION_CONTROLLER_PATH + "/watcherConfigs"; + + ClusterListenerByIpJob(Map params, CompletionService completionService, + ServerMemberManager serverMemberManager) { + super(URL, params, completionService, serverMemberManager); + } + } + private List runHasCheckListenerCollectionJob(Map params, CompletionService completionService) { return new ClusterCheckHasListenerJob(params, completionService, memberManager).runJobs(); @@ -324,7 +339,7 @@ public SampleResult getCollectSampleResultByIp(String ip, int sampleTime) { SampleResult sampleCollectResult = new SampleResult(); for (int i = 0; i < sampleTime; i++) { - List sampleResults = runConfigListenerCollectionJob(params, completionService); + List sampleResults = runConfigListenerByIpCollectionJob(params, completionService); if (sampleResults != null) { sampleCollectResult = mergeSampleResult(sampleCollectResult, sampleResults); } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DefaultHistoryConfigCleaner.java b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DefaultHistoryConfigCleaner.java new file mode 100644 index 00000000000..0d02458cee8 --- /dev/null +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DefaultHistoryConfigCleaner.java @@ -0,0 +1,91 @@ +/* + * Copyright 1999-2024 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.config.server.service.dump; + +import com.alibaba.nacos.config.server.service.repository.HistoryConfigInfoPersistService; +import com.alibaba.nacos.config.server.utils.TimeUtils; +import com.alibaba.nacos.sys.env.EnvUtil; +import com.alibaba.nacos.sys.utils.ApplicationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.sql.Timestamp; +import java.text.SimpleDateFormat; +import java.util.Calendar; + +import static com.alibaba.nacos.config.server.utils.LogUtil.FATAL_LOG; + +/** + * The type Default history config cleaner. + * + * @author Sunrisea + */ +public class DefaultHistoryConfigCleaner implements HistoryConfigCleaner { + + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultHistoryConfigCleaner.class); + + private HistoryConfigInfoPersistService historyConfigInfoPersistService; + + private int retentionDays = 30; + + @Override + public void cleanHistoryConfig() { + Timestamp startTime = getBeforeStamp(TimeUtils.getCurrentTime(), 24 * getRetentionDays()); + int pageSize = 1000; + LOGGER.warn("clearConfigHistory, getBeforeStamp:{}, pageSize:{}", startTime, pageSize); + getHistoryConfigInfoPersistService().removeConfigHistory(startTime, pageSize); + } + + private HistoryConfigInfoPersistService getHistoryConfigInfoPersistService() { + if (historyConfigInfoPersistService == null) { + historyConfigInfoPersistService = ApplicationUtils.getBean(HistoryConfigInfoPersistService.class); + } + return historyConfigInfoPersistService; + } + + private Timestamp getBeforeStamp(Timestamp date, int step) { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + cal.add(Calendar.HOUR_OF_DAY, -step); + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + return Timestamp.valueOf(format.format(cal.getTime())); + } + + private int getRetentionDays() { + String val = EnvUtil.getProperty("nacos.config.retention.days"); + if (null == val) { + return retentionDays; + } + + int tmp = 0; + try { + tmp = Integer.parseInt(val); + if (tmp > 0) { + retentionDays = tmp; + } + } catch (NumberFormatException nfe) { + FATAL_LOG.error("read nacos.config.retention.days wrong", nfe); + } + + return retentionDays; + } + + @Override + public String getName() { + return "nacos"; + } +} diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpService.java index e905194f52f..5a5ec201173 100755 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpService.java @@ -44,7 +44,6 @@ import com.alibaba.nacos.config.server.utils.GroupKey2; import com.alibaba.nacos.config.server.utils.LogUtil; import com.alibaba.nacos.config.server.utils.PropertyUtil; -import com.alibaba.nacos.config.server.utils.TimeUtils; import com.alibaba.nacos.core.cluster.ServerMemberManager; import com.alibaba.nacos.core.namespace.repository.NamespacePersistService; import com.alibaba.nacos.persistence.datasource.DynamicDataSource; @@ -54,14 +53,11 @@ import org.slf4j.LoggerFactory; import java.sql.Timestamp; -import java.text.SimpleDateFormat; -import java.util.Calendar; import java.util.List; import java.util.Random; import java.util.concurrent.TimeUnit; import static com.alibaba.nacos.config.server.utils.LogUtil.DUMP_LOG; -import static com.alibaba.nacos.config.server.utils.LogUtil.FATAL_LOG; /** * Dump data service. @@ -194,29 +190,31 @@ void handleConfigDataChange(Event event) { */ protected abstract void init() throws Throwable; - void clearConfigHistory() { - LOGGER.warn("clearConfigHistory start"); - if (canExecute()) { - try { - Timestamp startTime = getBeforeStamp(TimeUtils.getCurrentTime(), 24 * getRetentionDays()); - int pageSize = 1000; - LOGGER.warn("clearConfigHistory, getBeforeStamp:{}, pageSize:{}", startTime, pageSize); - historyConfigInfoPersistService.removeConfigHistory(startTime, pageSize); - } catch (Throwable e) { - LOGGER.error("clearConfigHistory error : {}", e.toString()); - } - } - - } - /** * config history clear. */ class ConfigHistoryClear implements Runnable { + private HistoryConfigCleaner historyConfigCleaner; + + public ConfigHistoryClear(HistoryConfigCleaner historyConfigCleaner) { + this.historyConfigCleaner = historyConfigCleaner; + } + @Override public void run() { - clearConfigHistory(); + LOGGER.warn("clearHistoryConfig get scheduled"); + if (canExecute()) { + try { + LOGGER.warn("clearHistoryConfig is enable in current context, try to run cleaner"); + historyConfigCleaner.cleanHistoryConfig(); + LOGGER.warn("history config cleaner successfully"); + } catch (Throwable e) { + LOGGER.error("clearConfigHistory error : {}", e.toString()); + } + } else { + LOGGER.warn("clearHistoryConfig is disable in current context"); + } } } @@ -316,7 +314,10 @@ protected void dumpOperate() throws NacosException { } - ConfigExecutor.scheduleConfigTask(new ConfigHistoryClear(), 10, 10, TimeUnit.MINUTES); + HistoryConfigCleaner cleaner = HistoryConfigCleanerManager.getHistoryConfigCleaner( + HistoryConfigCleanerConfig.getInstance().getActiveHistoryConfigCleaner()); + ConfigExecutor.scheduleConfigTask(new ConfigHistoryClear(cleaner), 10, 10, TimeUnit.MINUTES); + } finally { TimerContext.end(dumpFileContext, LogUtil.DUMP_LOG); } @@ -335,34 +336,6 @@ private void dumpAllConfigInfoOnStartup(DumpAllProcessor dumpAllProcessor) { } } - private Timestamp getBeforeStamp(Timestamp date, int step) { - Calendar cal = Calendar.getInstance(); - cal.setTime(date); - // before 6 hour - cal.add(Calendar.HOUR_OF_DAY, -step); - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - return Timestamp.valueOf(format.format(cal.getTime())); - } - - private int getRetentionDays() { - String val = EnvUtil.getProperty("nacos.config.retention.days"); - if (null == val) { - return retentionDays; - } - - int tmp = 0; - try { - tmp = Integer.parseInt(val); - if (tmp > 0) { - retentionDays = tmp; - } - } catch (NumberFormatException nfe) { - FATAL_LOG.error("read nacos.config.retention.days wrong", nfe); - } - - return retentionDays; - } - /** * dump operation. * diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/HistoryConfigCleaner.java b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/HistoryConfigCleaner.java new file mode 100644 index 00000000000..45d6978060b --- /dev/null +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/HistoryConfigCleaner.java @@ -0,0 +1,36 @@ +/* + * Copyright 1999-2024 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.config.server.service.dump; + +/** + * The interface History config cleaner. + * @author Sunrisea + */ +public interface HistoryConfigCleaner { + + /** + * Clean history config. + */ + public void cleanHistoryConfig(); + + /** + * Gets name. + * + * @return the name + */ + public String getName(); +} diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/HistoryConfigCleanerConfig.java b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/HistoryConfigCleanerConfig.java new file mode 100644 index 00000000000..45871a99b86 --- /dev/null +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/HistoryConfigCleanerConfig.java @@ -0,0 +1,79 @@ +/* + * Copyright 1999-2024 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.config.server.service.dump; + +import com.alibaba.nacos.api.utils.StringUtils; +import com.alibaba.nacos.core.config.AbstractDynamicConfig; +import com.alibaba.nacos.sys.env.EnvUtil; + +/** + * The type History config cleaner config. + * @author Sunrisea + */ +public class HistoryConfigCleanerConfig extends AbstractDynamicConfig { + + private static final String HISTORY_CONFIG_CLEANER = "historyConfigCleaner"; + + private static final HistoryConfigCleanerConfig INSTANCE = new HistoryConfigCleanerConfig(); + + private String activeHistoryConfigCleaner = "nacos"; + + private HistoryConfigCleanerConfig() { + super(HISTORY_CONFIG_CLEANER); + resetConfig(); + } + + /** + * Gets instance. + * + * @return the instance + */ + public static HistoryConfigCleanerConfig getInstance() { + return INSTANCE; + } + + @Override + protected void getConfigFromEnv() { + activeHistoryConfigCleaner = EnvUtil.getProperty("nacos.config.history.clear.name", String.class, "nacos"); + if (StringUtils.isBlank(activeHistoryConfigCleaner)) { + activeHistoryConfigCleaner = "nacos"; + } + } + + /** + * Gets active history config cleaner. + * + * @return the active history config cleaner + */ + public String getActiveHistoryConfigCleaner() { + return activeHistoryConfigCleaner; + } + + /** + * Sets active history config cleaner. + * + * @param activeHistoryConfigCleaner the active history config cleaner + */ + public void setActiveHistoryConfigCleaner(String activeHistoryConfigCleaner) { + this.activeHistoryConfigCleaner = activeHistoryConfigCleaner; + } + + @Override + protected String printConfig() { + return "activeHistoryConfigCleaner{ " + "activeHistoryConfigCleaner=" + activeHistoryConfigCleaner + "}"; + } +} diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/HistoryConfigCleanerManager.java b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/HistoryConfigCleanerManager.java new file mode 100644 index 00000000000..d460141d0bd --- /dev/null +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/HistoryConfigCleanerManager.java @@ -0,0 +1,48 @@ +/* + * Copyright 1999-2024 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.config.server.service.dump; + +import com.alibaba.nacos.common.spi.NacosServiceLoader; + +import java.util.HashMap; + +/** + * The type History config cleaner manager. + * + * @author Sunrisea + */ +public class HistoryConfigCleanerManager { + + private static HashMap historyConfigCleanerMap = new HashMap(); + + static { + NacosServiceLoader.load(HistoryConfigCleaner.class).forEach(historyConfigCleaner -> { + historyConfigCleanerMap.put(historyConfigCleaner.getName(), historyConfigCleaner); + }); + historyConfigCleanerMap.put("nacos", new DefaultHistoryConfigCleaner()); + } + + /** + * Gets history config cleaner. + * + * @param name the name + * @return the history config cleaner + */ + public static HistoryConfigCleaner getHistoryConfigCleaner(String name) { + return historyConfigCleanerMap.getOrDefault(name, historyConfigCleanerMap.get("nacos")); + } +} diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/disk/ConfigRawDiskService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/disk/ConfigRawDiskService.java index 099efeaebe9..a9e34250710 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/disk/ConfigRawDiskService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/disk/ConfigRawDiskService.java @@ -17,6 +17,7 @@ package com.alibaba.nacos.config.server.service.dump.disk; import com.alibaba.nacos.api.utils.StringUtils; +import com.alibaba.nacos.common.pathencoder.PathEncoderManager; import com.alibaba.nacos.common.utils.IoUtils; import com.alibaba.nacos.config.server.utils.LogUtil; import com.alibaba.nacos.sys.env.EnvUtil; @@ -65,6 +66,10 @@ public void saveToDisk(String dataId, String group, String tenant, String conten * Returns the path of the server cache file. */ private static File targetFile(String dataId, String group, String tenant) { + // fix https://github.com/alibaba/nacos/issues/10067 + dataId = PathEncoderManager.getInstance().encode(dataId); + group = PathEncoderManager.getInstance().encode(group); + tenant = PathEncoderManager.getInstance().encode(tenant); File file = null; if (StringUtils.isBlank(tenant)) { file = new File(EnvUtil.getNacosHome(), BASE_DIR); @@ -81,6 +86,10 @@ private static File targetFile(String dataId, String group, String tenant) { * Returns the path of cache file in server. */ private static File targetBetaFile(String dataId, String group, String tenant) { + // fix https://github.com/alibaba/nacos/issues/10067 + dataId = PathEncoderManager.getInstance().encode(dataId); + group = PathEncoderManager.getInstance().encode(group); + tenant = PathEncoderManager.getInstance().encode(tenant); File file = null; if (StringUtils.isBlank(tenant)) { file = new File(EnvUtil.getNacosHome(), BETA_DIR); @@ -97,6 +106,10 @@ private static File targetBetaFile(String dataId, String group, String tenant) { * Returns the path of the tag cache file in server. */ private static File targetTagFile(String dataId, String group, String tenant, String tag) { + // fix https://github.com/alibaba/nacos/issues/10067 + dataId = PathEncoderManager.getInstance().encode(dataId); + group = PathEncoderManager.getInstance().encode(group); + tenant = PathEncoderManager.getInstance().encode(tenant); File file = null; if (StringUtils.isBlank(tenant)) { file = new File(EnvUtil.getNacosHome(), TAG_DIR); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigDumpApplyHook.java b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigDumpApplyHook.java index b6e042af9a8..65f0c16265f 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigDumpApplyHook.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigDumpApplyHook.java @@ -58,7 +58,7 @@ private void handleExtendInfo(Map extendInfo) { return; } if (extendInfo.containsKey(Constants.EXTEND_INFOS_CONFIG_DUMP_EVENT)) { - String jsonVal = extendInfo.get(Constants.EXTEND_INFO_CONFIG_DUMP_EVENT); + String jsonVal = extendInfo.get(Constants.EXTEND_INFOS_CONFIG_DUMP_EVENT); if (StringUtils.isNotBlank(jsonVal)) { List list = JacksonUtils.toObj(jsonVal, new GenericType>() { }.getType()); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoBetaPersistServiceImpl.java b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoBetaPersistServiceImpl.java index 584df79257c..2aa5f47b488 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoBetaPersistServiceImpl.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoBetaPersistServiceImpl.java @@ -125,20 +125,20 @@ public ConfigOperateResult addConfigInfo4Beta(ConfigInfo configInfo, String beta String md5 = MD5Utils.md5Hex(configInfo.getContent(), Constants.ENCODE); ConfigInfoBetaMapper configInfoBetaMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO_BETA); - Timestamp time = new Timestamp(System.currentTimeMillis()); - + final String sql = configInfoBetaMapper.insert( Arrays.asList("data_id", "group_id", "tenant_id", "app_name", "content", "md5", "beta_ips", - "src_ip", "src_user", "gmt_create", "gmt_modified", "encrypted_data_key")); - final Object[] args = new Object[] {configInfo.getDataId(), configInfo.getGroup(), tenantTmp, appNameTmp, - configInfo.getContent(), md5, betaIps, srcIp, srcUser, time, time, encryptedDataKey}; - + "src_ip", "src_user", "gmt_create@NOW()", "gmt_modified@NOW()", "encrypted_data_key")); + final Object[] args = new Object[]{configInfo.getDataId(), configInfo.getGroup(), tenantTmp, appNameTmp, + configInfo.getContent(), md5, betaIps, srcIp, srcUser, encryptedDataKey}; + + Timestamp time = new Timestamp(System.currentTimeMillis()); EmbeddedStorageContextUtils.onModifyConfigBetaInfo(configInfo, betaIps, srcIp, time); EmbeddedStorageContextHolder.addSqlContext(sql, args); - + databaseOperate.blockUpdate(); return getBetaOperateResult(configInfo.getDataId(), configInfo.getGroup(), tenantTmp); - + } finally { EmbeddedStorageContextHolder.cleanAllContext(); } @@ -203,20 +203,20 @@ public ConfigOperateResult updateConfigInfo4Beta(ConfigInfo configInfo, String b String md5 = MD5Utils.md5Hex(configInfo.getContent(), Constants.ENCODE); ConfigInfoBetaMapper configInfoBetaMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO_BETA); - Timestamp time = new Timestamp(System.currentTimeMillis()); final String sql = configInfoBetaMapper.update( - Arrays.asList("content", "md5", "beta_ips", "src_ip", "src_user", "gmt_modified", "app_name", - "encrypted_data_key"), Arrays.asList("data_id", "group_id", "tenant_id")); - - final Object[] args = new Object[] {configInfo.getContent(), md5, betaIps, srcIp, srcUser, time, appNameTmp, + Arrays.asList("content", "md5", "beta_ips", "src_ip", "src_user", "gmt_modified@NOW()", + "app_name", "encrypted_data_key"), Arrays.asList("data_id", "group_id", "tenant_id")); + + final Object[] args = new Object[]{configInfo.getContent(), md5, betaIps, srcIp, srcUser, appNameTmp, encryptedDataKey, configInfo.getDataId(), configInfo.getGroup(), tenantTmp}; - + + Timestamp time = new Timestamp(System.currentTimeMillis()); EmbeddedStorageContextUtils.onModifyConfigBetaInfo(configInfo, betaIps, srcIp, time); EmbeddedStorageContextHolder.addSqlContext(sql, args); - + databaseOperate.blockUpdate(); return getBetaOperateResult(configInfo.getDataId(), configInfo.getGroup(), tenantTmp); - + } finally { EmbeddedStorageContextHolder.cleanAllContext(); } @@ -234,29 +234,28 @@ public ConfigOperateResult updateConfigInfo4BetaCas(ConfigInfo configInfo, Strin ConfigInfoBetaMapper configInfoBetaMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO_BETA); - Timestamp time = new Timestamp(System.currentTimeMillis()); MapperContext context = new MapperContext(); context.putUpdateParameter(FieldConstant.CONTENT, configInfo.getContent()); context.putUpdateParameter(FieldConstant.MD5, md5); context.putUpdateParameter(FieldConstant.BETA_IPS, betaIps); context.putUpdateParameter(FieldConstant.SRC_IP, srcIp); context.putUpdateParameter(FieldConstant.SRC_USER, srcUser); - context.putUpdateParameter(FieldConstant.GMT_MODIFIED, time); context.putUpdateParameter(FieldConstant.APP_NAME, appNameTmp); - + context.putWhereParameter(FieldConstant.DATA_ID, configInfo.getDataId()); context.putWhereParameter(FieldConstant.GROUP_ID, configInfo.getGroup()); context.putWhereParameter(FieldConstant.TENANT_ID, tenantTmp); context.putWhereParameter(FieldConstant.MD5, configInfo.getMd5()); MapperResult mapperResult = configInfoBetaMapper.updateConfigInfo4BetaCas(context); - + final String sql = mapperResult.getSql(); List paramList = mapperResult.getParamList(); final Object[] args = paramList.toArray(); - + + Timestamp time = new Timestamp(System.currentTimeMillis()); EmbeddedStorageContextUtils.onModifyConfigBetaInfo(configInfo, betaIps, srcIp, time); EmbeddedStorageContextHolder.addSqlContext(sql, args); - + boolean success = databaseOperate.blockUpdate(); if (success) { return getBetaOperateResult(configInfo.getDataId(), configInfo.getGroup(), tenantTmp); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoPersistServiceImpl.java b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoPersistServiceImpl.java index ab5b53a58b2..d547771721d 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoPersistServiceImpl.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoPersistServiceImpl.java @@ -18,11 +18,13 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; +import com.alibaba.nacos.common.constant.Symbols; import com.alibaba.nacos.common.notify.NotifyCenter; import com.alibaba.nacos.common.utils.MD5Utils; import com.alibaba.nacos.common.utils.Pair; import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.config.server.constant.Constants; +import com.alibaba.nacos.config.server.constant.ParametersField; import com.alibaba.nacos.config.server.enums.FileTypeEnum; import com.alibaba.nacos.config.server.exception.NacosConfigException; import com.alibaba.nacos.config.server.model.ConfigAdvanceInfo; @@ -215,8 +217,8 @@ private ConfigOperateResult addConfigInfo(final String srcIp, final String srcUs addConfigTagsRelation(configId, configTags, configInfo.getDataId(), configInfo.getGroup(), configInfo.getTenant()); + Timestamp now = new Timestamp(System.currentTimeMillis()); - historyConfigInfoPersistService.insertConfigHistoryAtomic(hisId, configInfo, srcIp, srcUser, now, "I"); EmbeddedStorageContextUtils.onModifyConfigInfo(configInfo, srcIp, now); databaseOperate.blockUpdate(consumer); @@ -264,15 +266,13 @@ public long addConfigInfoAtomic(final long id, final String srcIp, final String configInfo.getEncryptedDataKey() == null ? StringUtils.EMPTY : configInfo.getEncryptedDataKey(); ConfigInfoMapper configInfoMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO); - Timestamp time = new Timestamp(System.currentTimeMillis()); - + final String sql = configInfoMapper.insert( Arrays.asList("id", "data_id", "group_id", "tenant_id", "app_name", "content", "md5", "src_ip", - "src_user", "gmt_create", "gmt_modified", "c_desc", "c_use", "effect", "type", "c_schema", - "encrypted_data_key")); - final Object[] args = new Object[] {id, configInfo.getDataId(), configInfo.getGroup(), tenantTmp, appNameTmp, - configInfo.getContent(), md5Tmp, srcIp, srcUser, time, time, desc, use, effect, type, schema, - encryptedDataKey}; + "src_user", "gmt_create@NOW()", "gmt_modified@NOW()", "c_desc", "c_use", "effect", + "type", "c_schema", "encrypted_data_key")); + final Object[] args = new Object[]{id, configInfo.getDataId(), configInfo.getGroup(), tenantTmp, appNameTmp, + configInfo.getContent(), md5Tmp, srcIp, srcUser, desc, use, effect, type, schema, encryptedDataKey}; EmbeddedStorageContextHolder.addSqlContext(sql, args); return id; } @@ -522,14 +522,11 @@ public ConfigOperateResult updateConfigInfo(final ConfigInfo configInfo, final S } Timestamp time = new Timestamp(System.currentTimeMillis()); - historyConfigInfoPersistService.insertConfigHistoryAtomic(oldConfigInfo.getId(), oldConfigInfo, srcIp, srcUser, time, "U"); - EmbeddedStorageContextUtils.onModifyConfigInfo(configInfo, srcIp, time); databaseOperate.blockUpdate(); return getConfigInfoOperateResult(configInfo.getDataId(), configInfo.getGroup(), tenantTmp); - } finally { EmbeddedStorageContextHolder.cleanAllContext(); } @@ -563,11 +560,10 @@ public ConfigOperateResult updateConfigInfoCas(final ConfigInfo configInfo, fina addConfigTagsRelation(oldConfigInfo.getId(), configTags, configInfo.getDataId(), configInfo.getGroup(), configInfo.getTenant()); } + Timestamp time = new Timestamp(System.currentTimeMillis()); - historyConfigInfoPersistService.insertConfigHistoryAtomic(oldConfigInfo.getId(), oldConfigInfo, srcIp, srcUser, time, "U"); - EmbeddedStorageContextUtils.onModifyConfigInfo(configInfo, srcIp, time); boolean success = databaseOperate.blockUpdate(); if (success) { @@ -594,13 +590,11 @@ private ConfigOperateResult updateConfigInfoAtomicCas(final ConfigInfo configInf configInfo.getEncryptedDataKey() == null ? StringUtils.EMPTY : configInfo.getEncryptedDataKey(); ConfigInfoMapper configInfoMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO); - Timestamp time = new Timestamp(System.currentTimeMillis()); MapperContext context = new MapperContext(); context.putUpdateParameter(FieldConstant.CONTENT, configInfo.getContent()); context.putUpdateParameter(FieldConstant.MD5, md5Tmp); context.putUpdateParameter(FieldConstant.SRC_IP, srcIp); context.putUpdateParameter(FieldConstant.SRC_USER, srcUser); - context.putUpdateParameter(FieldConstant.GMT_MODIFIED, time); context.putUpdateParameter(FieldConstant.APP_NAME, appNameTmp); context.putUpdateParameter(FieldConstant.C_DESC, desc); context.putUpdateParameter(FieldConstant.C_USE, use); @@ -632,18 +626,17 @@ public void updateConfigInfoAtomic(final ConfigInfo configInfo, final String src final String schema = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("schema"); final String encryptedDataKey = configInfo.getEncryptedDataKey() == null ? StringUtils.EMPTY : configInfo.getEncryptedDataKey(); - + ConfigInfoMapper configInfoMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO); final String sql = configInfoMapper.update( - Arrays.asList("content", "md5", "src_ip", "src_user", "gmt_modified", "app_name", "c_desc", "c_use", - "effect", "type", "c_schema", "encrypted_data_key"), + Arrays.asList("content", "md5", "src_ip", "src_user", "gmt_modified@NOW()", "app_name", + "c_desc", "c_use", "effect", "type", "c_schema", "encrypted_data_key"), Arrays.asList("data_id", "group_id", "tenant_id")); - Timestamp time = new Timestamp(System.currentTimeMillis()); - - final Object[] args = new Object[] {configInfo.getContent(), md5Tmp, srcIp, srcUser, time, appNameTmp, desc, + + final Object[] args = new Object[]{configInfo.getContent(), md5Tmp, srcIp, srcUser, appNameTmp, desc, use, effect, type, schema, encryptedDataKey, configInfo.getDataId(), configInfo.getGroup(), tenantTmp}; - + EmbeddedStorageContextHolder.addSqlContext(sql, args); } @@ -809,6 +802,7 @@ public Page findConfigInfoLike4Page(final int pageNo, final int page String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant; final String appName = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("appName"); final String content = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("content"); + final String types = Optional.ofNullable(configAdvanceInfo).map(e -> (String) e.get(ParametersField.TYPES)).orElse(null); final String configTags = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("config_tags"); MapperResult sqlCountRows; MapperResult sqlFetchRows; @@ -828,6 +822,10 @@ public Page findConfigInfoLike4Page(final int pageNo, final int page if (!StringUtils.isBlank(content)) { context.putWhereParameter(FieldConstant.CONTENT, generateLikeArgument(content)); } + if (StringUtils.isNotBlank(types)) { + String[] typesArr = types.split(Symbols.COMMA); + context.putWhereParameter(FieldConstant.TYPE, typesArr); + } if (StringUtils.isNotBlank(configTags)) { String[] tagArr = configTags.split(","); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalConfigInfoBetaPersistServiceImpl.java b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalConfigInfoBetaPersistServiceImpl.java index d0b62bd498d..d7ec111db67 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalConfigInfoBetaPersistServiceImpl.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalConfigInfoBetaPersistServiceImpl.java @@ -46,7 +46,6 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.support.TransactionTemplate; -import java.sql.Timestamp; import java.util.Arrays; import java.util.List; @@ -94,13 +93,12 @@ public ConfigOperateResult addConfigInfo4Beta(ConfigInfo configInfo, String beta try { ConfigInfoBetaMapper configInfoBetaMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO_BETA); - Timestamp time = new Timestamp(System.currentTimeMillis()); jt.update(configInfoBetaMapper.insert( Arrays.asList("data_id", "group_id", "tenant_id", "app_name", "content", "md5", "beta_ips", - "src_ip", "src_user", "gmt_create", "gmt_modified", "encrypted_data_key")), + "src_ip", "src_user", "gmt_create@NOW()", "gmt_modified@NOW()", "encrypted_data_key")), configInfo.getDataId(), configInfo.getGroup(), tenantTmp, appNameTmp, configInfo.getContent(), md5, - betaIps, srcIp, srcUser, time, time, encryptedDataKey); + betaIps, srcIp, srcUser, encryptedDataKey); return getBetaOperateResult(configInfo.getDataId(), configInfo.getGroup(), tenantTmp); } catch (CannotGetJdbcConnectionException e) { @@ -165,12 +163,11 @@ public ConfigOperateResult updateConfigInfo4Beta(ConfigInfo configInfo, String b try { ConfigInfoBetaMapper configInfoBetaMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO_BETA); - Timestamp time = new Timestamp(System.currentTimeMillis()); - + jt.update(configInfoBetaMapper.update( - Arrays.asList("content", "md5", "beta_ips", "src_ip", "src_user", "gmt_modified", "app_name", - "encrypted_data_key"), Arrays.asList("data_id", "group_id", "tenant_id")), - configInfo.getContent(), md5, betaIps, srcIp, srcUser, time, appNameTmp, encryptedDataKey, + Arrays.asList("content", "md5", "beta_ips", "src_ip", "src_user", "gmt_modified@NOW()", + "app_name", "encrypted_data_key"), Arrays.asList("data_id", "group_id", "tenant_id")), + configInfo.getContent(), md5, betaIps, srcIp, srcUser, appNameTmp, encryptedDataKey, configInfo.getDataId(), configInfo.getGroup(), tenantTmp); return getBetaOperateResult(configInfo.getDataId(), configInfo.getGroup(), tenantTmp); @@ -214,15 +211,13 @@ public ConfigOperateResult updateConfigInfo4BetaCas(ConfigInfo configInfo, Strin try { ConfigInfoBetaMapper configInfoBetaMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO_BETA); - Timestamp time = new Timestamp(System.currentTimeMillis()); - + MapperContext context = new MapperContext(); context.putUpdateParameter(FieldConstant.CONTENT, configInfo.getContent()); context.putUpdateParameter(FieldConstant.MD5, md5); context.putUpdateParameter(FieldConstant.BETA_IPS, betaIps); context.putUpdateParameter(FieldConstant.SRC_IP, srcIp); context.putUpdateParameter(FieldConstant.SRC_USER, srcUser); - context.putUpdateParameter(FieldConstant.GMT_MODIFIED, time); context.putUpdateParameter(FieldConstant.APP_NAME, appNameTmp); context.putWhereParameter(FieldConstant.DATA_ID, configInfo.getDataId()); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalConfigInfoPersistServiceImpl.java b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalConfigInfoPersistServiceImpl.java index 916fe373637..b768c83c8c3 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalConfigInfoPersistServiceImpl.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalConfigInfoPersistServiceImpl.java @@ -17,10 +17,12 @@ package com.alibaba.nacos.config.server.service.repository.extrnal; import com.alibaba.nacos.api.exception.NacosException; +import com.alibaba.nacos.common.constant.Symbols; import com.alibaba.nacos.common.utils.MD5Utils; import com.alibaba.nacos.common.utils.Pair; import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.config.server.constant.Constants; +import com.alibaba.nacos.config.server.constant.ParametersField; import com.alibaba.nacos.config.server.enums.FileTypeEnum; import com.alibaba.nacos.config.server.model.ConfigAdvanceInfo; import com.alibaba.nacos.config.server.model.ConfigAllInfo; @@ -77,6 +79,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import static com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.CONFIG_ADVANCE_INFO_ROW_MAPPER; import static com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.CONFIG_ALL_INFO_ROW_MAPPER; @@ -234,11 +237,8 @@ public long addConfigInfoAtomic(final long configId, final String srcIp, final S PreparedStatement createPsForInsertConfigInfo(final String srcIp, final String srcUser, final ConfigInfo configInfo, Map configAdvanceInfo, Connection connection, ConfigInfoMapper configInfoMapper) throws SQLException { - - Timestamp now = new Timestamp(System.currentTimeMillis()); final String appNameTmp = StringUtils.defaultEmptyIfBlank(configInfo.getAppName()); final String tenantTmp = StringUtils.defaultEmptyIfBlank(configInfo.getTenant()); - final String desc = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("desc"); final String use = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("use"); final String effect = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("effect"); @@ -246,12 +246,11 @@ PreparedStatement createPsForInsertConfigInfo(final String srcIp, final String s final String schema = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("schema"); final String encryptedDataKey = configInfo.getEncryptedDataKey() == null ? StringUtils.EMPTY : configInfo.getEncryptedDataKey(); - final String md5Tmp = MD5Utils.md5Hex(configInfo.getContent(), Constants.ENCODE); - + String insertSql = configInfoMapper.insert( Arrays.asList("data_id", "group_id", "tenant_id", "app_name", "content", "md5", "src_ip", "src_user", - "gmt_create", "gmt_modified", "c_desc", "c_use", "effect", "type", "c_schema", + "gmt_create@NOW()", "gmt_modified@NOW()", "c_desc", "c_use", "effect", "type", "c_schema", "encrypted_data_key")); PreparedStatement ps = connection.prepareStatement(insertSql, configInfoMapper.getPrimaryKeyGeneratedKeys()); ps.setString(1, configInfo.getDataId()); @@ -262,14 +261,12 @@ PreparedStatement createPsForInsertConfigInfo(final String srcIp, final String s ps.setString(6, md5Tmp); ps.setString(7, srcIp); ps.setString(8, srcUser); - ps.setTimestamp(9, now); - ps.setTimestamp(10, now); - ps.setString(11, desc); - ps.setString(12, use); - ps.setString(13, effect); - ps.setString(14, type); - ps.setString(15, schema); - ps.setString(16, encryptedDataKey); + ps.setString(9, desc); + ps.setString(10, use); + ps.setString(11, effect); + ps.setString(12, type); + ps.setString(13, schema); + ps.setString(14, encryptedDataKey); return ps; } @@ -528,8 +525,8 @@ public ConfigOperateResult updateConfigInfo(final ConfigInfo configInfo, final S addConfigTagsRelation(oldConfigInfo.getId(), configTags, configInfo.getDataId(), configInfo.getGroup(), configInfo.getTenant()); } + Timestamp now = new Timestamp(System.currentTimeMillis()); - historyConfigInfoPersistService.insertConfigHistoryAtomic(oldConfigInfo.getId(), oldConfigInfo, srcIp, srcUser, now, "U"); return getConfigInfoOperateResult(configInfo.getDataId(), configInfo.getGroup(), @@ -615,14 +612,12 @@ private int updateConfigInfoAtomicCas(final ConfigInfo configInfo, final String try { ConfigInfoMapper configInfoMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO); - Timestamp now = new Timestamp(System.currentTimeMillis()); - + MapperContext context = new MapperContext(); context.putUpdateParameter(FieldConstant.CONTENT, configInfo.getContent()); context.putUpdateParameter(FieldConstant.MD5, md5Tmp); context.putUpdateParameter(FieldConstant.SRC_IP, srcIp); context.putUpdateParameter(FieldConstant.SRC_USER, srcUser); - context.putUpdateParameter(FieldConstant.GMT_MODIFIED, now); context.putUpdateParameter(FieldConstant.APP_NAME, appNameTmp); context.putUpdateParameter(FieldConstant.C_DESC, desc); context.putUpdateParameter(FieldConstant.C_USE, use); @@ -656,18 +651,15 @@ public void updateConfigInfoAtomic(final ConfigInfo configInfo, final String src String schema = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("schema"); final String encryptedDataKey = configInfo.getEncryptedDataKey() == null ? StringUtils.EMPTY : configInfo.getEncryptedDataKey(); - try { ConfigInfoMapper configInfoMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO); - Timestamp now = new Timestamp(System.currentTimeMillis()); - jt.update(configInfoMapper.update( - Arrays.asList("content", "md5", "src_ip", "src_user", "gmt_modified", "app_name", "c_desc", "c_use", - "effect", "type", "c_schema", "encrypted_data_key"), - Arrays.asList("data_id", "group_id", "tenant_id")), configInfo.getContent(), md5Tmp, srcIp, srcUser, - now, appNameTmp, desc, use, effect, type, schema, encryptedDataKey, configInfo.getDataId(), - configInfo.getGroup(), tenantTmp); + Arrays.asList("content", "md5", "src_ip", "src_user", "gmt_modified@NOW()", + "app_name", "c_desc", "c_use", "effect", "type", "c_schema", "encrypted_data_key"), + Arrays.asList("data_id", "group_id", "tenant_id")), + configInfo.getContent(), md5Tmp, srcIp, srcUser, appNameTmp, desc, use, effect, type, schema, + encryptedDataKey, configInfo.getDataId(), configInfo.getGroup(), tenantTmp); } catch (CannotGetJdbcConnectionException e) { LogUtil.FATAL_LOG.error("[db-error] " + e, e); throw e; @@ -847,6 +839,7 @@ public Page findConfigInfoLike4Page(final int pageNo, final int page String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant; final String appName = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("appName"); final String content = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("content"); + final String types = Optional.ofNullable(configAdvanceInfo).map(e -> (String) e.get(ParametersField.TYPES)).orElse(null); final String configTags = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("config_tags"); PaginationHelper helper = createPaginationHelper(); MapperResult sqlCountRows; @@ -867,6 +860,10 @@ public Page findConfigInfoLike4Page(final int pageNo, final int page if (!StringUtils.isBlank(content)) { context.putWhereParameter(FieldConstant.CONTENT, generateLikeArgument(content)); } + if (StringUtils.isNotBlank(types)) { + String[] typesArr = types.split(Symbols.COMMA); + context.putWhereParameter(FieldConstant.TYPE, typesArr); + } if (StringUtils.isNotBlank(configTags)) { String[] tagArr = configTags.split(","); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/trace/ConfigTraceService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/trace/ConfigTraceService.java index 8b720c2b463..ec9b4a58fcc 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/trace/ConfigTraceService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/trace/ConfigTraceService.java @@ -142,7 +142,6 @@ public static void logPersistenceEvent(String dataId, String group, String tenan //localIp | dataid | group | tenant | requestIpAppName | ts | client ip | event | type | [delayed = -1] | ext // (md5) String md5 = content == null ? null : MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE); - LogUtil.TRACE_LOG.info("{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}", InetUtils.getSelfIP(), dataId, group, tenant, requestIpAppName, ts, handleIp, event, type, -1, md5); } @@ -165,17 +164,14 @@ public static void logNotifyEvent(String dataId, String group, String tenant, St if (!LogUtil.TRACE_LOG.isInfoEnabled()) { return; } - if (delayed < 0) { delayed = 0; } - MetricsMonitor.getNotifyRtTimer().record(delayed, TimeUnit.MILLISECONDS); // Convenient tlog segmentation if (StringUtils.isBlank(tenant)) { tenant = null; } - //localIp | dataid | group | tenant | requestIpAppName | ts | handleIp | event | type | [delayed] | ext // (targetIp) LogUtil.TRACE_LOG.info("{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}", InetUtils.getSelfIP(), dataId, group, tenant, @@ -227,6 +223,7 @@ private static void logDumpEventInner(String dataId, String group, String tenant if (delayed < 0) { delayed = 0; } + MetricsMonitor.getDumpRtTimer().record(delayed, TimeUnit.MILLISECONDS); // Convenient tlog segmentation if (StringUtils.isBlank(tenant)) { tenant = null; @@ -284,11 +281,9 @@ public static void logPullEvent(String dataId, String group, String tenant, Stri if (StringUtils.isBlank(tenant)) { tenant = null; } - if (isNotify && delayed < 0) { delayed = 0; } - // localIp | dataid | group | tenant| requestIpAppName| ts | event | type | [delayed] |clientIp| isNotify | mode(http/grpc) LogUtil.TRACE_LOG.info("{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}", InetUtils.getSelfIP(), dataId, group, tenant, requestIpAppName, ts, event, type, delayed, clientIp, isNotify, model); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/RequestUtil.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/RequestUtil.java index fd566906a66..0e34c86d080 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/RequestUtil.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/RequestUtil.java @@ -18,6 +18,9 @@ import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.common.utils.StringUtils; +import com.alibaba.nacos.core.context.RequestContextHolder; +import com.alibaba.nacos.core.utils.WebUtils; +import com.alibaba.nacos.plugin.auth.api.IdentityContext; import javax.servlet.http.HttpServletRequest; @@ -28,30 +31,24 @@ */ public class RequestUtil { - private static final String X_REAL_IP = "X-Real-IP"; - - private static final String X_FORWARDED_FOR = "X-Forwarded-For"; - - private static final String X_FORWARDED_FOR_SPLIT_SYMBOL = ","; - public static final String CLIENT_APPNAME_HEADER = "Client-AppName"; /** - * get real client ip - * - *

    first use X-Forwarded-For header https://zh.wikipedia.org/wiki/X-Forwarded-For next nginx X-Real-IP last - * {@link HttpServletRequest#getRemoteAddr()} + * Get real client ip from context first, if no value, use + * {@link com.alibaba.nacos.core.utils.WebUtils#getRemoteIp(HttpServletRequest)}. * * @param request {@link HttpServletRequest} * @return remote ip address. */ public static String getRemoteIp(HttpServletRequest request) { - String xForwardedFor = request.getHeader(X_FORWARDED_FOR); - if (!StringUtils.isBlank(xForwardedFor)) { - return xForwardedFor.split(X_FORWARDED_FOR_SPLIT_SYMBOL)[0].trim(); + String remoteIp = RequestContextHolder.getContext().getBasicContext().getAddressContext().getSourceIp(); + if (StringUtils.isBlank(remoteIp)) { + remoteIp = RequestContextHolder.getContext().getBasicContext().getAddressContext().getRemoteIp(); } - String nginxHeader = request.getHeader(X_REAL_IP); - return StringUtils.isBlank(nginxHeader) ? request.getRemoteAddr() : nginxHeader; + if (StringUtils.isBlank(remoteIp)) { + remoteIp = WebUtils.getRemoteIp(request); + } + return remoteIp; } /** @@ -61,7 +58,12 @@ public static String getRemoteIp(HttpServletRequest request) { * @return may be return null */ public static String getAppName(HttpServletRequest request) { - return request.getHeader(CLIENT_APPNAME_HEADER); + String result = RequestContextHolder.getContext().getBasicContext().getApp(); + return isUnknownApp(result) ? request.getHeader(CLIENT_APPNAME_HEADER) : result; + } + + private static boolean isUnknownApp(String appName) { + return StringUtils.isBlank(appName) || StringUtils.equalsIgnoreCase("unknown", appName); } /** @@ -71,8 +73,12 @@ public static String getAppName(HttpServletRequest request) { * @return may be return null */ public static String getSrcUserName(HttpServletRequest request) { - String result = (String) request.getSession() - .getAttribute(com.alibaba.nacos.plugin.auth.constant.Constants.Identity.IDENTITY_ID); + IdentityContext identityContext = RequestContextHolder.getContext().getAuthContext().getIdentityContext(); + String result = StringUtils.EMPTY; + if (null != identityContext) { + result = (String) identityContext.getParameter( + com.alibaba.nacos.plugin.auth.constant.Constants.Identity.IDENTITY_ID); + } // If auth is disabled, get username from parameters by agreed key return StringUtils.isBlank(result) ? request.getParameter(Constants.USERNAME) : result; } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/aspect/CapacityManagementAspectTest.java b/config/src/test/java/com/alibaba/nacos/config/server/aspect/CapacityManagementAspectTest.java index 3bc2c1b0ac5..11855300e67 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/aspect/CapacityManagementAspectTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/aspect/CapacityManagementAspectTest.java @@ -26,28 +26,38 @@ import com.alibaba.nacos.plugin.datasource.constants.CommonConstant; import com.alibaba.nacos.sys.env.EnvUtil; import org.aspectj.lang.ProceedingJoinPoint; -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.MockedStatic; import org.mockito.Mockito; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import static com.alibaba.nacos.config.server.aspect.CapacityManagementAspect.LimitType.OVER_CLUSTER_QUOTA; import static com.alibaba.nacos.config.server.aspect.CapacityManagementAspect.LimitType.OVER_MAX_SIZE; -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.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; -@RunWith(SpringJUnit4ClassRunner.class) -public class CapacityManagementAspectTest { +@ExtendWith(SpringExtension.class) +class CapacityManagementAspectTest { + + final String mockProceedingJoinPointResult = "mock success return"; + + final String mockDataId = "mockDataId"; + + final String mockGroup = "mockGroup"; + + final String mockTenant = "mockTenant"; + + final String mockContent = "mockContent"; @Mock ProceedingJoinPoint proceedingJoinPoint; @@ -69,18 +79,8 @@ public class CapacityManagementAspectTest { MockedStatic envUtilMockedStatic; - final String mockProceedingJoinPointResult = "mock success return"; - - final String mockDataId = "mockDataId"; - - final String mockGroup = "mockGroup"; - - final String mockTenant = "mockTenant"; - - final String mockContent = "mockContent"; - - @Before - public void before() throws Throwable { + @BeforeEach + void before() throws Throwable { //PropertyUtil.isCapacityLimitCheck() propertyUtilMockedStatic = Mockito.mockStatic(PropertyUtil.class); when(PropertyUtil.getCorrectUsageDelay()).thenReturn(10 * 60); @@ -97,14 +97,14 @@ public void before() throws Throwable { when(localMockProceedingJoinPoint.proceed()).thenThrow(mockException); } - @After - public void after() { + @AfterEach + void after() { propertyUtilMockedStatic.close(); envUtilMockedStatic.close(); } @Test - public void testAroundSyncUpdateConfigAllForInsertAspect() throws Throwable { + void testAroundSyncUpdateConfigAllForInsertAspect() throws Throwable { //test with insert //condition: // 1. has tenant: true @@ -121,7 +121,7 @@ public void testAroundSyncUpdateConfigAllForInsertAspect() throws Throwable { } @Test - public void testAroundSyncUpdateConfigAllForInsertAspect1() throws Throwable { + void testAroundSyncUpdateConfigAllForInsertAspect1() throws Throwable { //test with insert //condition: // 1. has tenant: true @@ -141,7 +141,7 @@ public void testAroundSyncUpdateConfigAllForInsertAspect1() throws Throwable { } @Test - public void testAroundSyncUpdateConfigAllForInsertAspect2Tenant() throws Throwable { + void testAroundSyncUpdateConfigAllForInsertAspect2Tenant() throws Throwable { //test with insert //condition: // 1. has tenant: true @@ -167,7 +167,7 @@ public void testAroundSyncUpdateConfigAllForInsertAspect2Tenant() throws Throwab } @Test - public void testAroundSyncUpdateConfigAllForInsertAspect2Group() throws Throwable { + void testAroundSyncUpdateConfigAllForInsertAspect2Group() throws Throwable { //test with insert //condition: // 1. has tenant: false @@ -193,7 +193,7 @@ public void testAroundSyncUpdateConfigAllForInsertAspect2Group() throws Throwabl } @Test - public void testAroundSyncUpdateConfigAllForInsertAspect3Tenant() throws Throwable { + void testAroundSyncUpdateConfigAllForInsertAspect3Tenant() throws Throwable { //test with insert //condition: // 1. has tenant: true @@ -237,7 +237,7 @@ public void testAroundSyncUpdateConfigAllForInsertAspect3Tenant() throws Throwab } @Test - public void testAroundSyncUpdateConfigAllForInsertAspect3Group() throws Throwable { + void testAroundSyncUpdateConfigAllForInsertAspect3Group() throws Throwable { //test with insert //condition: // 1. has tenant: true @@ -281,7 +281,7 @@ public void testAroundSyncUpdateConfigAllForInsertAspect3Group() throws Throwabl } @Test - public void testAroundSyncUpdateConfigAllForUpdateAspectTenant() throws Throwable { + void testAroundSyncUpdateConfigAllForUpdateAspectTenant() throws Throwable { //condition: // 1. has tenant: true // 2. capacity limit check: true @@ -311,7 +311,7 @@ public void testAroundSyncUpdateConfigAllForUpdateAspectTenant() throws Throwabl } @Test - public void testAroundSyncUpdateConfigAllForUpdateAspectGroup() throws Throwable { + void testAroundSyncUpdateConfigAllForUpdateAspectGroup() throws Throwable { //condition: // 1. has tenant: false // 2. capacity limit check: true @@ -341,7 +341,7 @@ public void testAroundSyncUpdateConfigAllForUpdateAspectGroup() throws Throwable } @Test - public void testAroundSyncUpdateConfigAllForInsertRollbackAspect() throws Throwable { + void testAroundSyncUpdateConfigAllForInsertRollbackAspect() throws Throwable { //test with insert //condition: // 1. has tenant: true @@ -365,9 +365,8 @@ public void testAroundSyncUpdateConfigAllForInsertRollbackAspect() throws Throwa MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); try { - localMockResult = (String) capacityManagementAspect.aroundSyncUpdateConfigAll( - localMockProceedingJoinPoint, mockHttpServletRequest, mockHttpServletResponse, - mockDataId, mockGroup, mockContent, null, null, mockTenant, null); + localMockResult = (String) capacityManagementAspect.aroundSyncUpdateConfigAll(localMockProceedingJoinPoint, + mockHttpServletRequest, mockHttpServletResponse, mockDataId, mockGroup, mockContent, null, null, mockTenant, null); } catch (Throwable e) { assertEquals(e.getMessage(), mockException.getMessage()); } @@ -381,7 +380,7 @@ public void testAroundSyncUpdateConfigAllForInsertRollbackAspect() throws Throwa } @Test - public void testAroundDeleteConfigForTenant() throws Throwable { + void testAroundDeleteConfigForTenant() throws Throwable { when(PropertyUtil.isManageCapacity()).thenReturn(true); when(configInfoPersistService.findConfigInfo(any(), any(), any())).thenReturn(null); when(capacityService.insertAndUpdateClusterUsage(any(), anyBoolean())).thenReturn(true); @@ -401,26 +400,28 @@ public void testAroundDeleteConfigForTenant() throws Throwable { mockHttpServletResponse, mockDataId, mockGroup, mockTenant); assertEquals(localMockResult, mockProceedingJoinPointResult); Mockito.verify(capacityService, Mockito.times(1)).insertAndUpdateClusterUsage(eq(CounterMode.DECREMENT), anyBoolean()); - Mockito.verify(capacityService, Mockito.times(1)).insertAndUpdateTenantUsage(eq(CounterMode.DECREMENT), eq(mockTenant), anyBoolean()); + Mockito.verify(capacityService, Mockito.times(1)) + .insertAndUpdateTenantUsage(eq(CounterMode.DECREMENT), eq(mockTenant), anyBoolean()); Mockito.verify(proceedingJoinPoint, Mockito.times(2)).proceed(); localMockResult = null; try { - localMockResult = (String) capacityManagementAspect.aroundDeleteConfig(localMockProceedingJoinPoint, - mockHttpServletRequest, mockHttpServletResponse, mockDataId, mockGroup, mockTenant); + localMockResult = (String) capacityManagementAspect.aroundDeleteConfig(localMockProceedingJoinPoint, mockHttpServletRequest, + mockHttpServletResponse, mockDataId, mockGroup, mockTenant); } catch (Throwable e) { assertEquals(e.getMessage(), mockException.getMessage()); } assertNull(localMockResult); Mockito.verify(capacityService, Mockito.times(2)).insertAndUpdateClusterUsage(eq(CounterMode.DECREMENT), anyBoolean()); Mockito.verify(capacityService, Mockito.times(1)).updateClusterUsage(eq(CounterMode.INCREMENT)); - Mockito.verify(capacityService, Mockito.times(2)).insertAndUpdateTenantUsage(eq(CounterMode.DECREMENT), eq(mockTenant), anyBoolean()); + Mockito.verify(capacityService, Mockito.times(2)) + .insertAndUpdateTenantUsage(eq(CounterMode.DECREMENT), eq(mockTenant), anyBoolean()); Mockito.verify(capacityService, Mockito.times(1)).updateTenantUsage(eq(CounterMode.INCREMENT), eq(mockTenant)); Mockito.verify(localMockProceedingJoinPoint, Mockito.times(1)).proceed(); } @Test - public void testAroundDeleteConfigForGroup() throws Throwable { + void testAroundDeleteConfigForGroup() throws Throwable { when(PropertyUtil.isManageCapacity()).thenReturn(true); when(configInfoPersistService.findConfigInfo(any(), any(), any())).thenReturn(null); when(capacityService.insertAndUpdateClusterUsage(any(), anyBoolean())).thenReturn(true); @@ -445,8 +446,8 @@ public void testAroundDeleteConfigForGroup() throws Throwable { localMockResult = null; try { - localMockResult = (String) capacityManagementAspect.aroundDeleteConfig(localMockProceedingJoinPoint, - mockHttpServletRequest, mockHttpServletResponse, mockDataId, mockGroup, null); + localMockResult = (String) capacityManagementAspect.aroundDeleteConfig(localMockProceedingJoinPoint, mockHttpServletRequest, + mockHttpServletResponse, mockDataId, mockGroup, null); } catch (Throwable e) { assertEquals(e.getMessage(), mockException.getMessage()); } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/aspect/ConfigChangeAspectTest.java b/config/src/test/java/com/alibaba/nacos/config/server/aspect/ConfigChangeAspectTest.java index 612b8db93c6..0f31ad53ae5 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/aspect/ConfigChangeAspectTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/aspect/ConfigChangeAspectTest.java @@ -35,15 +35,14 @@ import com.alibaba.nacos.plugin.config.spi.ConfigChangePluginService; import com.alibaba.nacos.sys.utils.PropertiesUtil; import org.aspectj.lang.ProceedingJoinPoint; -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.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; @@ -51,11 +50,14 @@ import java.util.Arrays; 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.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; -@RunWith(SpringJUnit4ClassRunner.class) -public class ConfigChangeAspectTest { +@ExtendWith(SpringExtension.class) +class ConfigChangeAspectTest { ConfigChangeAspect configChangeAspect; @@ -68,17 +70,17 @@ public class ConfigChangeAspectTest { MockedStatic requestUtilMockedStatic; - @Before - public void before() { + @BeforeEach + void before() { //mock config change service enabled. propertiesStatic = Mockito.mockStatic(PropertiesUtil.class); requestUtilMockedStatic = Mockito.mockStatic(RequestUtil.class); Properties properties = new Properties(); properties.put("mockedConfigChangeService.enabled", "true"); - propertiesStatic.when(() -> PropertiesUtil.getPropertiesWithPrefix(any(), - eq(ConfigChangeConstants.NACOS_CORE_CONFIG_PLUGIN_PREFIX))).thenReturn(properties); - requestUtilMockedStatic.when(() -> RequestUtil.getSrcUserName(any(HttpServletRequest.class))) - .thenReturn("mockedUser"); + propertiesStatic.when( + () -> PropertiesUtil.getPropertiesWithPrefix(any(), eq(ConfigChangeConstants.NACOS_CORE_CONFIG_PLUGIN_PREFIX))) + .thenReturn(properties); + requestUtilMockedStatic.when(() -> RequestUtil.getSrcUserName(any(HttpServletRequest.class))).thenReturn("mockedUser"); Mockito.when(configChangePluginService.getServiceType()).thenReturn("mockedConfigChangeService"); Mockito.when(configChangePluginService.pointcutMethodNames()).thenReturn(ConfigChangePointCutTypes.values()); Mockito.when(configChangePluginService.executeType()).thenReturn(ConfigChangeExecuteTypes.EXECUTE_AFTER_TYPE); @@ -89,14 +91,14 @@ public void before() { configChangeAspect = new ConfigChangeAspect(configChangeConfigs); } - @After - public void after() { + @AfterEach + void after() { propertiesStatic.close(); requestUtilMockedStatic.close(); } @Test - public void testImportConfigAround() throws Throwable { + void testImportConfigAround() throws Throwable { Mockito.when(configChangePluginService.executeType()).thenReturn(ConfigChangeExecuteTypes.EXECUTE_AFTER_TYPE); ProceedingJoinPoint proceedingJoinPoint = Mockito.mock(ProceedingJoinPoint.class); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); @@ -105,19 +107,18 @@ public void testImportConfigAround() throws Throwable { SameConfigPolicy policy = SameConfigPolicy.ABORT; MultipartFile file = Mockito.mock(MultipartFile.class); Mockito.when(proceedingJoinPoint.proceed(any())).thenReturn("mock success return"); - Object o = configChangeAspect.importConfigAround(proceedingJoinPoint, request, srcUser, namespace, policy, - file); + Object o = configChangeAspect.importConfigAround(proceedingJoinPoint, request, srcUser, namespace, policy, file); Thread.sleep(20L); // expect service executed. Mockito.verify(configChangePluginService, Mockito.times(1)) .execute(any(ConfigChangeRequest.class), any(ConfigChangeResponse.class)); //expect join point processed success. - Assert.assertEquals("mock success return", o); + assertEquals("mock success return", o); } @Test - public void testPublishOrUpdateConfigAround() throws Throwable { + void testPublishOrUpdateConfigAround() throws Throwable { Mockito.when(configChangePluginService.executeType()).thenReturn(ConfigChangeExecuteTypes.EXECUTE_AFTER_TYPE); ProceedingJoinPoint proceedingJoinPoint = Mockito.mock(ProceedingJoinPoint.class); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); @@ -128,19 +129,19 @@ public void testPublishOrUpdateConfigAround() throws Throwable { String group = "g1"; String tenant = "t1"; Mockito.when(proceedingJoinPoint.proceed(any())).thenReturn("mock success return"); - Object o = configChangeAspect.publishOrUpdateConfigAround(proceedingJoinPoint, request, response, dataId, group, - tenant, "c1", null, null, srcUser, null, null, null, null, null); + Object o = configChangeAspect.publishOrUpdateConfigAround(proceedingJoinPoint, request, response, dataId, group, tenant, "c1", null, + null, srcUser, null, null, null, null, null); Thread.sleep(20L); // expect service executed. Mockito.verify(configChangePluginService, Mockito.times(1)) .execute(any(ConfigChangeRequest.class), any(ConfigChangeResponse.class)); //expect join point processed success. - Assert.assertEquals("mock success return", o); + assertEquals("mock success return", o); } @Test - public void testRemoveConfigByIdAround() throws Throwable { + void testRemoveConfigByIdAround() throws Throwable { Mockito.when(configChangePluginService.executeType()).thenReturn(ConfigChangeExecuteTypes.EXECUTE_AFTER_TYPE); ProceedingJoinPoint proceedingJoinPoint = Mockito.mock(ProceedingJoinPoint.class); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); @@ -150,19 +151,18 @@ public void testRemoveConfigByIdAround() throws Throwable { String group = "g1"; String tenant = "t1"; Mockito.when(proceedingJoinPoint.proceed(any())).thenReturn("mock success return"); - Object o = configChangeAspect.removeConfigByIdAround(proceedingJoinPoint, request, response, dataId, group, - tenant); + Object o = configChangeAspect.removeConfigByIdAround(proceedingJoinPoint, request, response, dataId, group, tenant); Thread.sleep(20L); // expect service executed. Mockito.verify(configChangePluginService, Mockito.times(1)) .execute(any(ConfigChangeRequest.class), any(ConfigChangeResponse.class)); //expect join point processed success. - Assert.assertEquals("mock success return", o); + assertEquals("mock success return", o); } @Test - public void testRemoveConfigByIdsAround() throws Throwable { + void testRemoveConfigByIdsAround() throws Throwable { Mockito.when(configChangePluginService.executeType()).thenReturn(ConfigChangeExecuteTypes.EXECUTE_AFTER_TYPE); ProceedingJoinPoint proceedingJoinPoint = Mockito.mock(ProceedingJoinPoint.class); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); @@ -174,11 +174,11 @@ public void testRemoveConfigByIdsAround() throws Throwable { Mockito.verify(configChangePluginService, Mockito.times(1)) .execute(any(ConfigChangeRequest.class), any(ConfigChangeResponse.class)); //expect join point processed success. - Assert.assertEquals("mock success return", o); + assertEquals("mock success return", o); } @Test - public void testPublishConfigAroundRpc() throws Throwable { + void testPublishConfigAroundRpc() throws Throwable { Mockito.when(configChangePluginService.executeType()).thenReturn(ConfigChangeExecuteTypes.EXECUTE_BEFORE_TYPE); ProceedingJoinPoint proceedingJoinPoint = Mockito.mock(ProceedingJoinPoint.class); ConfigPublishRequest request = new ConfigPublishRequest(); @@ -190,11 +190,11 @@ public void testPublishConfigAroundRpc() throws Throwable { //expect Mockito.verify(configChangePluginService, Mockito.times(1)) .execute(any(ConfigChangeRequest.class), any(ConfigChangeResponse.class)); - Assert.assertEquals(configPublishResponse, o); + assertEquals(configPublishResponse, o); } @Test - public void testPublishConfigAroundRpcException() throws Throwable { + void testPublishConfigAroundRpcException() throws Throwable { Mockito.when(configChangePluginService.executeType()).thenReturn(ConfigChangeExecuteTypes.EXECUTE_BEFORE_TYPE); ProceedingJoinPoint proceedingJoinPoint = Mockito.mock(ProceedingJoinPoint.class); ConfigPublishRequest request = new ConfigPublishRequest(); @@ -207,11 +207,11 @@ public void testPublishConfigAroundRpcException() throws Throwable { Mockito.verify(configChangePluginService, Mockito.times(1)) .execute(any(ConfigChangeRequest.class), any(ConfigChangeResponse.class)); - Assert.assertTrue(((ConfigPublishResponse) o).getMessage().contains("config change join point fail")); + assertTrue(((ConfigPublishResponse) o).getMessage().contains("config change join point fail")); } @Test - public void testRemoveConfigAroundRpc() throws Throwable { + void testRemoveConfigAroundRpc() throws Throwable { Mockito.when(configChangePluginService.executeType()).thenReturn(ConfigChangeExecuteTypes.EXECUTE_BEFORE_TYPE); ProceedingJoinPoint proceedingJoinPoint = Mockito.mock(ProceedingJoinPoint.class); ConfigRemoveRequest request = new ConfigRemoveRequest(); @@ -223,35 +223,35 @@ public void testRemoveConfigAroundRpc() throws Throwable { //expect Mockito.verify(configChangePluginService, Mockito.times(1)) .execute(any(ConfigChangeRequest.class), any(ConfigChangeResponse.class)); - Assert.assertEquals(configPublishResponse, o); + assertEquals(configPublishResponse, o); } @Test - public void testRemoveConfigAroundRpcException() throws Throwable { + void testRemoveConfigAroundRpcException() throws Throwable { Mockito.when(configChangePluginService.executeType()).thenReturn(ConfigChangeExecuteTypes.EXECUTE_BEFORE_TYPE); ProceedingJoinPoint proceedingJoinPoint = Mockito.mock(ProceedingJoinPoint.class); ConfigRemoveRequest request = new ConfigRemoveRequest(); RequestMeta requestMeta = new RequestMeta(); - + Mockito.when(proceedingJoinPoint.proceed(any())).thenThrow(new NacosRuntimeException(503)); //execute Object o = configChangeAspect.removeConfigAroundRpc(proceedingJoinPoint, request, requestMeta); //expect Mockito.verify(configChangePluginService, Mockito.times(1)) .execute(any(ConfigChangeRequest.class), any(ConfigChangeResponse.class)); - - Assert.assertTrue(((ConfigRemoveResponse) o).getMessage().contains("config change join point fail")); + + assertTrue(((ConfigRemoveResponse) o).getMessage().contains("config change join point fail")); } @Test - public void testDisEnablePluginService() throws Throwable { + void testDisEnablePluginService() throws Throwable { Properties properties = new Properties(); properties.put("mockedConfigChangeService.enabled", "false"); - propertiesStatic.when(() -> PropertiesUtil.getPropertiesWithPrefix(any(), - eq(ConfigChangeConstants.NACOS_CORE_CONFIG_PLUGIN_PREFIX))).thenReturn(properties); + propertiesStatic.when( + () -> PropertiesUtil.getPropertiesWithPrefix(any(), eq(ConfigChangeConstants.NACOS_CORE_CONFIG_PLUGIN_PREFIX))) + .thenReturn(properties); configChangeConfigs.onEvent(ServerConfigChangeEvent.newEvent()); - Assert.assertFalse(Boolean.parseBoolean(configChangeConfigs - .getPluginProperties("mockedConfigChangeService").getProperty("enabled"))); + assertFalse(Boolean.parseBoolean(configChangeConfigs.getPluginProperties("mockedConfigChangeService").getProperty("enabled"))); Mockito.when(configChangePluginService.executeType()).thenReturn(ConfigChangeExecuteTypes.EXECUTE_BEFORE_TYPE); Mockito.when(configChangePluginService.getServiceType()).thenReturn("mockedConfigChangeService"); @@ -265,7 +265,7 @@ public void testDisEnablePluginService() throws Throwable { //expect Mockito.verify(configChangePluginService, Mockito.times(0)) .execute(any(ConfigChangeRequest.class), any(ConfigChangeResponse.class)); - Assert.assertEquals(configPublishResponse, o); + assertEquals(configPublishResponse, o); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/configuration/ConfigChangeConfigsTest.java b/config/src/test/java/com/alibaba/nacos/config/server/configuration/ConfigChangeConfigsTest.java index 8afdbdb085b..3ae828c1cc4 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/configuration/ConfigChangeConfigsTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/configuration/ConfigChangeConfigsTest.java @@ -18,24 +18,26 @@ import com.alibaba.nacos.common.event.ServerConfigChangeEvent; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.mock.env.MockEnvironment; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Nacos config change configs test. * * @author liyunfei **/ -public class ConfigChangeConfigsTest { +class ConfigChangeConfigsTest { private ConfigChangeConfigs configChangeConfigs; private MockEnvironment environment; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { environment = new MockEnvironment(); environment.setProperty("nacos.core.config.plugin.mockPlugin.enabled", "true"); EnvUtil.setEnvironment(environment); @@ -43,17 +45,15 @@ public void setUp() throws Exception { } @Test - public void testEnable() { - Assert.assertTrue(Boolean.parseBoolean(configChangeConfigs - .getPluginProperties("mockPlugin").getProperty("enabled"))); + void testEnable() { + assertTrue(Boolean.parseBoolean(configChangeConfigs.getPluginProperties("mockPlugin").getProperty("enabled"))); } @Test - public void testUpgradeEnable() { + void testUpgradeEnable() { environment.setProperty("nacos.core.config.plugin.mockPlugin.enabled", "false"); configChangeConfigs.onEvent(ServerConfigChangeEvent.newEvent()); - Assert.assertFalse(Boolean.parseBoolean(configChangeConfigs - .getPluginProperties("mockPlugin").getProperty("enabled"))); + assertFalse(Boolean.parseBoolean(configChangeConfigs.getPluginProperties("mockPlugin").getProperty("enabled"))); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/configuration/ConfigCommonConfigTest.java b/config/src/test/java/com/alibaba/nacos/config/server/configuration/ConfigCommonConfigTest.java index 86c0fb35dc9..1fb93644220 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/configuration/ConfigCommonConfigTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/configuration/ConfigCommonConfigTest.java @@ -18,28 +18,29 @@ import com.alibaba.nacos.common.event.ServerConfigChangeEvent; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.mock.env.MockEnvironment; import java.lang.reflect.Constructor; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Nacos config common configs test. * * @author blake.qiu */ -public class ConfigCommonConfigTest { +class ConfigCommonConfigTest { private ConfigCommonConfig commonConfig; private MockEnvironment environment; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { environment = new MockEnvironment(); EnvUtil.setEnvironment(environment); Constructor declaredConstructor = ConfigCommonConfig.class.getDeclaredConstructor(); @@ -48,13 +49,13 @@ public void setUp() throws Exception { } @Test - public void getMaxPushRetryTimes() { + void getMaxPushRetryTimes() { Integer property = EnvUtil.getProperty("nacos.config.push.maxRetryTime", Integer.class, 50); assertEquals(property.intValue(), commonConfig.getMaxPushRetryTimes()); } @Test - public void setMaxPushRetryTimes() { + void setMaxPushRetryTimes() { int maxPushRetryTimesOld = commonConfig.getMaxPushRetryTimes(); commonConfig.setMaxPushRetryTimes(100); assertEquals(100, commonConfig.getMaxPushRetryTimes()); @@ -62,20 +63,29 @@ public void setMaxPushRetryTimes() { } @Test - public void testUpgradeFromEvent() { + void testSetDerbyOpsEnabled() { + assertFalse(commonConfig.isDerbyOpsEnabled()); + commonConfig.setDerbyOpsEnabled(true); + assertTrue(commonConfig.isDerbyOpsEnabled()); + } + + @Test + void testUpgradeFromEvent() { environment.setProperty("nacos.config.push.maxRetryTime", "100"); + environment.setProperty("nacos.config.derby.ops.enabled", "true"); commonConfig.onEvent(ServerConfigChangeEvent.newEvent()); assertEquals(100, commonConfig.getMaxPushRetryTimes()); + assertTrue(commonConfig.isDerbyOpsEnabled()); } @Test - public void testInitConfigFormEnv() throws ReflectiveOperationException { + void testInitConfigFormEnv() throws ReflectiveOperationException { MockEnvironment environment = new MockEnvironment(); EnvUtil.setEnvironment(environment); environment.setProperty("nacos.config.push.maxRetryTime", "6"); Constructor declaredConstructor = ConfigCommonConfig.class.getDeclaredConstructor(); declaredConstructor.setAccessible(true); ConfigCommonConfig configCommonConfig = declaredConstructor.newInstance(); - Assert.assertEquals(6, configCommonConfig.getMaxPushRetryTimes()); + assertEquals(6, configCommonConfig.getMaxPushRetryTimes()); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/constant/ConfigModuleStateBuilderTest.java b/config/src/test/java/com/alibaba/nacos/config/server/constant/ConfigModuleStateBuilderTest.java index 2f974b00b7b..f0294f60489 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/constant/ConfigModuleStateBuilderTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/constant/ConfigModuleStateBuilderTest.java @@ -21,14 +21,15 @@ import com.alibaba.nacos.plugin.datasource.constants.CommonConstant; import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.module.ModuleState; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.mock.env.MockEnvironment; import java.util.Map; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * config module state builder test. @@ -36,29 +37,27 @@ * @author 985492783@qq.com * @date 2023/4/7 23:34 */ -public class ConfigModuleStateBuilderTest { +class ConfigModuleStateBuilderTest { private ConfigurableEnvironment environment; - @Before - public void setUp() { - environment = new MockEnvironment() - .withProperty(PersistenceConstant.DATASOURCE_PLATFORM_PROPERTY, PersistenceConstant.DERBY) + @BeforeEach + void setUp() { + environment = new MockEnvironment().withProperty(PersistenceConstant.DATASOURCE_PLATFORM_PROPERTY, PersistenceConstant.DERBY) .withProperty(CommonConstant.NACOS_PLUGIN_DATASOURCE_LOG, "true"); EnvUtil.setEnvironment(environment); } @Test - public void testBuild() { + void testBuild() { ModuleState actual = new ConfigModuleStateBuilder().build(); Map states = actual.getStates(); assertEquals(PersistenceConstant.DERBY, states.get(Constants.DATASOURCE_PLATFORM_PROPERTY_STATE)); - assertEquals(true, states.get(Constants.NACOS_PLUGIN_DATASOURCE_LOG_STATE)); + assertTrue((Boolean) states.get(Constants.NACOS_PLUGIN_DATASOURCE_LOG_STATE)); assertEquals(PropertyUtil.getNotifyConnectTimeout(), states.get(PropertiesConstant.NOTIFY_CONNECT_TIMEOUT)); assertEquals(PropertyUtil.getNotifySocketTimeout(), states.get(PropertiesConstant.NOTIFY_SOCKET_TIMEOUT)); assertEquals(PropertyUtil.isHealthCheck(), states.get(PropertiesConstant.IS_HEALTH_CHECK)); - assertEquals(PropertyUtil.getMaxHealthCheckFailCount(), - states.get(PropertiesConstant.MAX_HEALTH_CHECK_FAIL_COUNT)); + assertEquals(PropertyUtil.getMaxHealthCheckFailCount(), states.get(PropertiesConstant.MAX_HEALTH_CHECK_FAIL_COUNT)); assertEquals(PropertyUtil.getMaxContent(), states.get(PropertiesConstant.MAX_CONTENT)); assertEquals(PropertyUtil.isManageCapacity(), states.get(PropertiesConstant.IS_MANAGE_CAPACITY)); assertEquals(PropertyUtil.isCapacityLimitCheck(), states.get(PropertiesConstant.IS_CAPACITY_LIMIT_CHECK)); diff --git a/config/src/test/java/com/alibaba/nacos/config/server/constant/ConstantsTest.java b/config/src/test/java/com/alibaba/nacos/config/server/constant/ConstantsTest.java index f16e58ba244..c74906f8f29 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/constant/ConstantsTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/constant/ConstantsTest.java @@ -16,8 +16,7 @@ package com.alibaba.nacos.config.server.constant; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static com.alibaba.nacos.config.server.constant.Constants.CAPACITY_CONTROLLER_PATH; import static com.alibaba.nacos.config.server.constant.Constants.COMMUNICATION_CONTROLLER_PATH; @@ -29,26 +28,27 @@ import static com.alibaba.nacos.config.server.constant.Constants.NAMESPACE_CONTROLLER_PATH; import static com.alibaba.nacos.config.server.constant.Constants.OPS_CONTROLLER_PATH; import static com.alibaba.nacos.config.server.constant.Constants.RECV_WAIT_TIMEOUT; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class ConstantsTest { +class ConstantsTest { @Test - public void testControllerPathsDefaultValues() { + void testControllerPathsDefaultValues() { - Assert.assertEquals("/v1/cs/ops", OPS_CONTROLLER_PATH); - Assert.assertEquals("/v1/cs/capacity", CAPACITY_CONTROLLER_PATH); - Assert.assertEquals("/v1/cs/communication", COMMUNICATION_CONTROLLER_PATH); - Assert.assertEquals("/v1/cs/configs", CONFIG_CONTROLLER_PATH); - Assert.assertEquals("/v1/cs/health", HEALTH_CONTROLLER_PATH); - Assert.assertEquals("/v1/cs/history", HISTORY_CONTROLLER_PATH); - Assert.assertEquals("/v1/cs/listener", LISTENER_CONTROLLER_PATH); - Assert.assertEquals("/v1/cs/namespaces", NAMESPACE_CONTROLLER_PATH); - Assert.assertEquals("/v1/cs/metrics", METRICS_CONTROLLER_PATH); + assertEquals("/v1/cs/ops", OPS_CONTROLLER_PATH); + assertEquals("/v1/cs/capacity", CAPACITY_CONTROLLER_PATH); + assertEquals("/v1/cs/communication", COMMUNICATION_CONTROLLER_PATH); + assertEquals("/v1/cs/configs", CONFIG_CONTROLLER_PATH); + assertEquals("/v1/cs/health", HEALTH_CONTROLLER_PATH); + assertEquals("/v1/cs/history", HISTORY_CONTROLLER_PATH); + assertEquals("/v1/cs/listener", LISTENER_CONTROLLER_PATH); + assertEquals("/v1/cs/namespaces", NAMESPACE_CONTROLLER_PATH); + assertEquals("/v1/cs/metrics", METRICS_CONTROLLER_PATH); } @Test - public void testRecvWaitTimeoutDefaultValue() { + void testRecvWaitTimeoutDefaultValue() { - Assert.assertEquals(10000, RECV_WAIT_TIMEOUT); + assertEquals(10000, RECV_WAIT_TIMEOUT); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/constant/CounterModeTest.java b/config/src/test/java/com/alibaba/nacos/config/server/constant/CounterModeTest.java index ce6bddb8712..0043566b645 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/constant/CounterModeTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/constant/CounterModeTest.java @@ -16,21 +16,22 @@ package com.alibaba.nacos.config.server.constant; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mock; -public class CounterModeTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class CounterModeTest { @Mock CounterMode counterMode; @Test - public void testReverse() { + void testReverse() { counterMode = CounterMode.INCREMENT; - Assert.assertEquals(CounterMode.DECREMENT, counterMode.reverse()); + assertEquals(CounterMode.DECREMENT, counterMode.reverse()); counterMode = CounterMode.DECREMENT; - Assert.assertEquals(CounterMode.INCREMENT, counterMode.reverse()); + assertEquals(CounterMode.INCREMENT, counterMode.reverse()); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/controller/CapacityControllerTest.java b/config/src/test/java/com/alibaba/nacos/config/server/controller/CapacityControllerTest.java index 28ef4a9d732..0e3e0897943 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/controller/CapacityControllerTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/controller/CapacityControllerTest.java @@ -21,16 +21,15 @@ import com.alibaba.nacos.config.server.model.capacity.Capacity; import com.alibaba.nacos.config.server.service.capacity.CapacityService; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.core.env.StandardEnvironment; import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; @@ -41,13 +40,15 @@ import javax.servlet.ServletContext; import java.sql.Timestamp; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; -@RunWith(SpringJUnit4ClassRunner.class) +@ExtendWith(SpringExtension.class) @ContextConfiguration(classes = MockServletContext.class) @WebAppConfiguration -public class CapacityControllerTest { +class CapacityControllerTest { @InjectMocks CapacityController capacityController; @@ -60,8 +61,8 @@ public class CapacityControllerTest { @Mock private ServletContext servletContext; - @Before - public void setUp() { + @BeforeEach + void setUp() { EnvUtil.setEnvironment(new StandardEnvironment()); when(servletContext.getContextPath()).thenReturn("/nacos"); ReflectionTestUtils.setField(capacityController, "capacityService", capacityService); @@ -69,7 +70,7 @@ public void setUp() { } @Test - public void testGetCapacityNormal() throws Exception { + void testGetCapacityNormal() throws Exception { Capacity capacity = new Capacity(); capacity.setId(1L); @@ -80,22 +81,22 @@ public void testGetCapacityNormal() throws Exception { capacity.setGmtModified(new Timestamp(2)); when(capacityService.getCapacityWithDefault(eq("test"), eq("test"))).thenReturn(capacity); - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.CAPACITY_CONTROLLER_PATH) - .param("group", "test").param("tenant", "test"); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.CAPACITY_CONTROLLER_PATH).param("group", "test") + .param("tenant", "test"); String actualValue = mockMvc.perform(builder).andReturn().getResponse().getContentAsString(); Capacity result = JacksonUtils.toObj(JacksonUtils.toObj(actualValue).get("data").toString(), Capacity.class); - Assert.assertNotNull(result); - Assert.assertEquals(capacity.getId(), result.getId()); - Assert.assertEquals(capacity.getMaxAggrCount(), result.getMaxAggrCount()); - Assert.assertEquals(capacity.getMaxSize(), result.getMaxSize()); - Assert.assertEquals(capacity.getMaxAggrSize(), result.getMaxAggrSize()); - Assert.assertEquals(capacity.getGmtCreate(), result.getGmtCreate()); - Assert.assertEquals(capacity.getGmtModified(), result.getGmtModified()); + assertNotNull(result); + assertEquals(capacity.getId(), result.getId()); + assertEquals(capacity.getMaxAggrCount(), result.getMaxAggrCount()); + assertEquals(capacity.getMaxSize(), result.getMaxSize()); + assertEquals(capacity.getMaxAggrSize(), result.getMaxAggrSize()); + assertEquals(capacity.getGmtCreate(), result.getGmtCreate()); + assertEquals(capacity.getGmtModified(), result.getGmtModified()); } @Test - public void testGetCapacityException() throws Exception { + void testGetCapacityException() throws Exception { Capacity capacity = new Capacity(); capacity.setId(1L); @@ -111,70 +112,67 @@ public void testGetCapacityException() throws Exception { System.out.println(actualValue); // tenant is blank& group is null - MockHttpServletRequestBuilder builder2 = MockMvcRequestBuilders.get(Constants.CAPACITY_CONTROLLER_PATH) - .param("tenant", ""); + MockHttpServletRequestBuilder builder2 = MockMvcRequestBuilders.get(Constants.CAPACITY_CONTROLLER_PATH).param("tenant", ""); String actualValue2 = mockMvc.perform(builder2).andReturn().getResponse().getContentAsString(); System.out.println(actualValue2); // tenant is blank& group is null when(capacityService.getCapacityWithDefault(eq("g1"), eq("123"))).thenThrow(new NullPointerException()); - MockHttpServletRequestBuilder builder3 = MockMvcRequestBuilders.get(Constants.CAPACITY_CONTROLLER_PATH) - .param("tenant", "123").param("group", "g1"); + MockHttpServletRequestBuilder builder3 = MockMvcRequestBuilders.get(Constants.CAPACITY_CONTROLLER_PATH).param("tenant", "123") + .param("group", "g1"); String actualValue3 = mockMvc.perform(builder3).andReturn().getResponse().getContentAsString(); System.out.println(actualValue3); } @Test - public void testUpdateCapacity1x() throws Exception { + void testUpdateCapacity1x() throws Exception { when(capacityService.insertOrUpdateCapacity("test", "test", 1, 1, 1, 1)).thenReturn(true); - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(Constants.CAPACITY_CONTROLLER_PATH) - .param("group", "test").param("tenant", "test").param("quota", "1").param("maxSize", "1") - .param("maxAggrCount", "1").param("maxAggrSize", "1"); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(Constants.CAPACITY_CONTROLLER_PATH).param("group", "test") + .param("tenant", "test").param("quota", "1").param("maxSize", "1").param("maxAggrCount", "1").param("maxAggrSize", "1"); String actualValue = mockMvc.perform(builder).andReturn().getResponse().getContentAsString(); String code = JacksonUtils.toObj(actualValue).get("code").toString(); String data = JacksonUtils.toObj(actualValue).get("data").toString(); - Assert.assertEquals("200", code); - Assert.assertEquals("true", data); + assertEquals("200", code); + assertEquals("true", data); } @Test - public void testUpdateCapacity2x() throws Exception { + void testUpdateCapacity2x() throws Exception { MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(Constants.CAPACITY_CONTROLLER_PATH); String actualValue = mockMvc.perform(builder).andReturn().getResponse().getContentAsString(); String code = JacksonUtils.toObj(actualValue).get("code").toString(); String data = JacksonUtils.toObj(actualValue).get("data").toString(); - Assert.assertEquals("400", code); - Assert.assertEquals("false", data); + assertEquals("400", code); + assertEquals("false", data); } @Test - public void testUpdateCapacity3x() throws Exception { + void testUpdateCapacity3x() throws Exception { - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(Constants.CAPACITY_CONTROLLER_PATH) - .param("group", "test").param("tenant", "test"); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(Constants.CAPACITY_CONTROLLER_PATH).param("group", "test") + .param("tenant", "test"); String actualValue = mockMvc.perform(builder).andReturn().getResponse().getContentAsString(); String code = JacksonUtils.toObj(actualValue).get("code").toString(); String data = JacksonUtils.toObj(actualValue).get("data").toString(); - Assert.assertEquals("400", code); - Assert.assertEquals("false", data); + assertEquals("400", code); + assertEquals("false", data); } @Test - public void testUpdateCapacity4x() throws Exception { + void testUpdateCapacity4x() throws Exception { when(capacityService.insertOrUpdateCapacity("test", "test", 1, 1, 1, 1)).thenReturn(false); - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(Constants.CAPACITY_CONTROLLER_PATH) - .param("group", "test").param("tenant", "test").param("quota", "1").param("maxSize", "1") - .param("maxAggrCount", "1").param("maxAggrSize", "1"); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(Constants.CAPACITY_CONTROLLER_PATH).param("group", "test") + .param("tenant", "test").param("quota", "1").param("maxSize", "1").param("maxAggrCount", "1").param("maxAggrSize", "1"); String actualValue = mockMvc.perform(builder).andReturn().getResponse().getContentAsString(); String code = JacksonUtils.toObj(actualValue).get("code").toString(); String data = JacksonUtils.toObj(actualValue).get("data").toString(); - Assert.assertEquals("500", code); - Assert.assertEquals("false", data); + assertEquals("500", code); + assertEquals("false", data); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/controller/ClientMetricsControllerTest.java b/config/src/test/java/com/alibaba/nacos/config/server/controller/ClientMetricsControllerTest.java index d674ea4cacc..7c61815d245 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/controller/ClientMetricsControllerTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/controller/ClientMetricsControllerTest.java @@ -24,17 +24,16 @@ import com.alibaba.nacos.core.remote.Connection; import com.alibaba.nacos.core.remote.ConnectionManager; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.springframework.core.env.StandardEnvironment; import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; @@ -43,22 +42,22 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import javax.servlet.ServletContext; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; -@RunWith(SpringJUnit4ClassRunner.class) +@ExtendWith(SpringExtension.class) @ContextConfiguration(classes = MockServletContext.class) @WebAppConfiguration -public class ClientMetricsControllerTest { +class ClientMetricsControllerTest { @InjectMocks ClientMetricsController clientMetricsController; @@ -74,8 +73,8 @@ public class ClientMetricsControllerTest { @Mock private ServletContext servletContext; - @Before - public void setUp() { + @BeforeEach + void setUp() { EnvUtil.setEnvironment(new StandardEnvironment()); when(servletContext.getContextPath()).thenReturn("/nacos"); ReflectionTestUtils.setField(clientMetricsController, "serverMemberManager", memberManager); @@ -84,7 +83,7 @@ public void setUp() { } @Test - public void testGetClusterMetric() throws Exception { + void testGetClusterMetric() throws Exception { List members = new ArrayList<>(); Member m1 = new Member(); m1.setIp("127.0.0.1"); @@ -101,15 +100,14 @@ public void testGetClusterMetric() throws Exception { when(memberManager.allMembers()).thenReturn(members); - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get( - Constants.METRICS_CONTROLLER_PATH + "/cluster").param("ip", "127.0.0.1").param("tenant", "test") - .param("dataId", "test").param("group", "test"); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.METRICS_CONTROLLER_PATH + "/cluster") + .param("ip", "127.0.0.1").param("tenant", "test").param("dataId", "test").param("group", "test"); int actualValue = mockMvc.perform(builder).andReturn().getResponse().getStatus(); - Assert.assertEquals(200, actualValue); + assertEquals(200, actualValue); } @Test - public void testClusterMetricsCallBack() { + void testClusterMetricsCallBack() { Member m1 = new Member(); m1.setIp("127.0.0.1"); @@ -142,12 +140,12 @@ public void testClusterMetricsCallBack() { clusterMetricsCallBack.onError(new NullPointerException()); clusterMetricsCallBack.onCancel(); clusterMetricsCallBack.onCancel(); - Assert.assertEquals(stringObjectHashMap, responseMap); - Assert.assertEquals(0, latch.getCount()); + assertEquals(stringObjectHashMap, responseMap); + assertEquals(0, latch.getCount()); } @Test - public void testGetCurrentMetric() throws Exception { + void testGetCurrentMetric() throws Exception { ClientConfigMetricResponse response = new ClientConfigMetricResponse(); response.putMetric("test", "test"); @@ -157,11 +155,10 @@ public void testGetCurrentMetric() throws Exception { connections.add(connection); when(connectionManager.getConnectionByIp(eq("127.0.0.1"))).thenReturn(connections); - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get( - Constants.METRICS_CONTROLLER_PATH + "/current").param("ip", "127.0.0.1").param("tenant", "test") - .param("dataId", "test").param("group", "test"); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.METRICS_CONTROLLER_PATH + "/current") + .param("ip", "127.0.0.1").param("tenant", "test").param("dataId", "test").param("group", "test"); String actualValue = mockMvc.perform(builder).andReturn().getResponse().getContentAsString(); - Assert.assertEquals("{\"test\":\"test\"}", actualValue); + assertEquals("{\"test\":\"test\"}", actualValue); } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/controller/CommunicationControllerTest.java b/config/src/test/java/com/alibaba/nacos/config/server/controller/CommunicationControllerTest.java index 7576436b098..3bbd9d7f745 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/controller/CommunicationControllerTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/controller/CommunicationControllerTest.java @@ -28,16 +28,15 @@ import com.alibaba.nacos.core.remote.ConnectionMeta; import com.alibaba.nacos.core.remote.grpc.GrpcConnection; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.core.env.StandardEnvironment; import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; @@ -46,7 +45,6 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import javax.servlet.ServletContext; - import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -54,21 +52,17 @@ import java.util.Map; import java.util.Set; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; -@RunWith(SpringJUnit4ClassRunner.class) +@ExtendWith(SpringExtension.class) @ContextConfiguration(classes = MockServletContext.class) @WebAppConfiguration -public class CommunicationControllerTest { +class CommunicationControllerTest { @InjectMocks CommunicationController communicationController; - private MockMvc mockMvc; - - @Mock - private ServletContext servletContext; - @Mock DumpService dumpService; @@ -81,8 +75,13 @@ public class CommunicationControllerTest { @Mock ConnectionManager connectionManager; - @Before - public void setUp() { + private MockMvc mockMvc; + + @Mock + private ServletContext servletContext; + + @BeforeEach + void setUp() { EnvUtil.setEnvironment(new StandardEnvironment()); when(servletContext.getContextPath()).thenReturn("/nacos"); ReflectionTestUtils.setField(communicationController, "longPollingService", longPollingService); @@ -92,8 +91,8 @@ public void setUp() { } @Test - public void testGetSubClientConfig1x() throws Exception { - + void testGetSubClientConfig1x() throws Exception { + SampleResult result = new SampleResult(); Map lisentersGroupkeyStatus = new HashMap<>(); lisentersGroupkeyStatus.put("test", "test"); @@ -103,11 +102,11 @@ public void testGetSubClientConfig1x() throws Exception { MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.COMMUNICATION_CONTROLLER_PATH + "/configWatchers") .param("dataId", "test").param("group", "test").param("tenant", "test"); String actualValue = mockMvc.perform(builder).andReturn().getResponse().getContentAsString(); - Assert.assertEquals("{\"test\":\"test\"}", JacksonUtils.toObj(actualValue).get("lisentersGroupkeyStatus").toString()); + assertEquals("{\"test\":\"test\"}", JacksonUtils.toObj(actualValue).get("lisentersGroupkeyStatus").toString()); } @Test - public void testGetSubClientConfig2x() throws Exception { + void testGetSubClientConfig2x() throws Exception { SampleResult result = new SampleResult(); result.setLisentersGroupkeyStatus(new HashMap<>()); @@ -117,7 +116,8 @@ public void testGetSubClientConfig2x() throws Exception { String connectionId = "127.0.0.1"; listenersClients.add(connectionId); when(configChangeListenContext.getListeners(groupKey)).thenReturn(listenersClients); - ConnectionMeta connectionMeta = new ConnectionMeta(connectionId, connectionId, connectionId, 8888, 9848, "GRPC", "", "", new HashMap<>()); + ConnectionMeta connectionMeta = new ConnectionMeta(connectionId, connectionId, connectionId, 8888, 9848, "GRPC", "", "", + new HashMap<>()); Connection client = new GrpcConnection(connectionMeta, null, null); when(connectionManager.getConnection(connectionId)).thenReturn(client); when(configChangeListenContext.getListenKeyMd5(connectionId, groupKey)).thenReturn("md5"); @@ -125,12 +125,12 @@ public void testGetSubClientConfig2x() throws Exception { MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.COMMUNICATION_CONTROLLER_PATH + "/configWatchers") .param("dataId", "test").param("group", "test").param("tenant", "test"); String actualValue = mockMvc.perform(builder).andReturn().getResponse().getContentAsString(); - Assert.assertEquals("{\"127.0.0.1\":\"md5\"}", JacksonUtils.toObj(actualValue).get("lisentersGroupkeyStatus").toString()); + assertEquals("{\"127.0.0.1\":\"md5\"}", JacksonUtils.toObj(actualValue).get("lisentersGroupkeyStatus").toString()); } @Test - public void testGetSubClientConfigByIp() throws Exception { - + void testGetSubClientConfigByIp() throws Exception { + String ip = "127.0.0.1"; SampleResult result = new SampleResult(); result.setLisentersGroupkeyStatus(new HashMap<>()); @@ -143,11 +143,11 @@ public void testGetSubClientConfigByIp() throws Exception { Map map = new HashMap<>(); map.put("test", "test"); when(configChangeListenContext.getListenKeys(ip)).thenReturn(map); - + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.COMMUNICATION_CONTROLLER_PATH + "/watcherConfigs") .param("ip", ip); String actualValue = mockMvc.perform(builder).andReturn().getResponse().getContentAsString(); - Assert.assertEquals("{\"test\":\"test\"}", JacksonUtils.toObj(actualValue).get("lisentersGroupkeyStatus").toString()); - + assertEquals("{\"test\":\"test\"}", JacksonUtils.toObj(actualValue).get("lisentersGroupkeyStatus").toString()); + } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/controller/ConfigControllerTest.java b/config/src/test/java/com/alibaba/nacos/config/server/controller/ConfigControllerTest.java index d31a1c080ce..44c3010a18a 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/controller/ConfigControllerTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/controller/ConfigControllerTest.java @@ -41,10 +41,9 @@ import com.alibaba.nacos.persistence.model.Page; import com.alibaba.nacos.sys.env.EnvUtil; import com.fasterxml.jackson.databind.JsonNode; -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.InjectMocks; import org.mockito.Mock; import org.mockito.MockedStatic; @@ -53,7 +52,7 @@ import org.springframework.mock.web.MockMultipartFile; import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; @@ -69,16 +68,18 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicReference; +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.anyList; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; -@RunWith(SpringJUnit4ClassRunner.class) +@ExtendWith(SpringExtension.class) @ContextConfiguration(classes = MockServletContext.class) @WebAppConfiguration -public class ConfigControllerTest { +class ConfigControllerTest { @InjectMocks ConfigController configController; @@ -106,8 +107,8 @@ public class ConfigControllerTest { @Mock private ConfigSubService configSubService; - @Before - public void setUp() { + @BeforeEach + void setUp() { EnvUtil.setEnvironment(new StandardEnvironment()); when(servletContext.getContextPath()).thenReturn("/nacos"); ReflectionTestUtils.setField(configController, "configSubService", configSubService); @@ -120,27 +121,27 @@ public void setUp() { } @Test - public void testPublishConfig() throws Exception { + void testPublishConfig() throws Exception { when(configOperationService.publishConfig(any(), any(), anyString())).thenReturn(true); - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(Constants.CONFIG_CONTROLLER_PATH) - .param("dataId", "test").param("group", "test").param("tenant", "").param("content", "test") - .param("tag", "").param("appName", "").param("src_user", "").param("config_tags", "").param("desc", "") - .param("use", "").param("effect", "").param("type", "").param("schema", ""); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(Constants.CONFIG_CONTROLLER_PATH).param("dataId", "test") + .param("group", "test").param("tenant", "").param("content", "test").param("tag", "").param("appName", "") + .param("src_user", "").param("config_tags", "").param("desc", "").param("use", "").param("effect", "").param("type", "") + .param("schema", ""); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); - Assert.assertEquals("true", actualValue); + assertEquals("true", actualValue); } @Test - public void testGetConfig() throws Exception { - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.CONFIG_CONTROLLER_PATH) - .param("dataId", "test").param("group", "test").param("tenant", "").param("tag", ""); + void testGetConfig() throws Exception { + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.CONFIG_CONTROLLER_PATH).param("dataId", "test") + .param("group", "test").param("tenant", "").param("tag", ""); int actualValue = mockmvc.perform(builder).andReturn().getResponse().getStatus(); - Assert.assertEquals(200, actualValue); + assertEquals(200, actualValue); } @Test - public void testDetailConfigInfo() throws Exception { + void testDetailConfigInfo() throws Exception { ConfigAllInfo configAllInfo = new ConfigAllInfo(); configAllInfo.setDataId("test"); configAllInfo.setGroup("test"); @@ -149,32 +150,31 @@ public void testDetailConfigInfo() throws Exception { when(configInfoPersistService.findConfigAllInfo("test", "test", "")).thenReturn(configAllInfo); - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.CONFIG_CONTROLLER_PATH) - .param("show", "all").param("dataId", "test").param("group", "test").param("tenant", ""); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.CONFIG_CONTROLLER_PATH).param("show", "all") + .param("dataId", "test").param("group", "test").param("tenant", ""); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); ConfigAllInfo resConfigAllInfo = JacksonUtils.toObj(actualValue, ConfigAllInfo.class); - Assert.assertEquals(configAllInfo.getDataId(), resConfigAllInfo.getDataId()); - Assert.assertEquals(configAllInfo.getGroup(), resConfigAllInfo.getGroup()); - Assert.assertEquals(configAllInfo.getCreateIp(), resConfigAllInfo.getCreateIp()); - Assert.assertEquals(configAllInfo.getCreateUser(), resConfigAllInfo.getCreateUser()); + assertEquals(configAllInfo.getDataId(), resConfigAllInfo.getDataId()); + assertEquals(configAllInfo.getGroup(), resConfigAllInfo.getGroup()); + assertEquals(configAllInfo.getCreateIp(), resConfigAllInfo.getCreateIp()); + assertEquals(configAllInfo.getCreateUser(), resConfigAllInfo.getCreateUser()); } @Test - public void testDeleteConfig() throws Exception { - when(configOperationService.deleteConfig(anyString(), anyString(), anyString(), anyString(), any(), - any())).thenReturn(true); + void testDeleteConfig() throws Exception { + when(configOperationService.deleteConfig(anyString(), anyString(), anyString(), anyString(), any(), any())).thenReturn(true); - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.delete(Constants.CONFIG_CONTROLLER_PATH) - .param("dataId", "test").param("group", "test").param("tenant", "").param("tag", ""); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.delete(Constants.CONFIG_CONTROLLER_PATH).param("dataId", "test") + .param("group", "test").param("tenant", "").param("tag", ""); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); - Assert.assertEquals("true", actualValue); + assertEquals("true", actualValue); } @Test - public void testDeleteConfigs() throws Exception { + void testDeleteConfigs() throws Exception { List resultInfos = new ArrayList<>(); String dataId = "dataId1123"; @@ -200,22 +200,22 @@ public Class subscribeType() { } }); - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.delete(Constants.CONFIG_CONTROLLER_PATH) - .param("delType", "ids").param("ids", "1,2"); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.delete(Constants.CONFIG_CONTROLLER_PATH).param("delType", "ids") + .param("ids", "1,2"); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); String code = JacksonUtils.toObj(actualValue).get("code").toString(); String data = JacksonUtils.toObj(actualValue).get("data").toString(); - Assert.assertEquals("200", code); - Assert.assertEquals("true", data); + assertEquals("200", code); + assertEquals("true", data); Thread.sleep(200L); //expect - Assert.assertTrue(reference.get() != null); + assertTrue(reference.get() != null); } @Test - public void testGetConfigAdvanceInfo() throws Exception { + void testGetConfigAdvanceInfo() throws Exception { ConfigAdvanceInfo configAdvanceInfo = new ConfigAdvanceInfo(); configAdvanceInfo.setCreateIp("localhost"); @@ -224,31 +224,30 @@ public void testGetConfigAdvanceInfo() throws Exception { when(configInfoPersistService.findConfigAdvanceInfo("test", "test", "")).thenReturn(configAdvanceInfo); - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get( - Constants.CONFIG_CONTROLLER_PATH + "/catalog").param("dataId", "test").param("group", "test") - .param("tenant", ""); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.CONFIG_CONTROLLER_PATH + "/catalog") + .param("dataId", "test").param("group", "test").param("tenant", ""); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); String code = JacksonUtils.toObj(actualValue).get("code").toString(); String data = JacksonUtils.toObj(actualValue).get("data").toString(); ConfigAdvanceInfo resConfigAdvanceInfo = JacksonUtils.toObj(data, ConfigAdvanceInfo.class); - Assert.assertEquals("200", code); - Assert.assertEquals(configAdvanceInfo.getCreateIp(), resConfigAdvanceInfo.getCreateIp()); - Assert.assertEquals(configAdvanceInfo.getCreateUser(), resConfigAdvanceInfo.getCreateUser()); - Assert.assertEquals(configAdvanceInfo.getDesc(), resConfigAdvanceInfo.getDesc()); + assertEquals("200", code); + assertEquals(configAdvanceInfo.getCreateIp(), resConfigAdvanceInfo.getCreateIp()); + assertEquals(configAdvanceInfo.getCreateUser(), resConfigAdvanceInfo.getCreateUser()); + assertEquals(configAdvanceInfo.getDesc(), resConfigAdvanceInfo.getDesc()); } @Test - public void testListener() throws Exception { - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post( - Constants.CONFIG_CONTROLLER_PATH + "/listener").param("Listening-Configs", "test"); + void testListener() throws Exception { + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(Constants.CONFIG_CONTROLLER_PATH + "/listener") + .param("Listening-Configs", "test"); int actualValue = mockmvc.perform(builder).andReturn().getResponse().getStatus(); - Assert.assertEquals(200, actualValue); + assertEquals(200, actualValue); } @Test - public void testGetListeners() throws Exception { + void testGetListeners() throws Exception { Map listenersGroupkeyStatus = new HashMap<>(); listenersGroupkeyStatus.put("test", "test"); SampleResult sampleResult = new SampleResult(); @@ -256,20 +255,18 @@ public void testGetListeners() throws Exception { when(configSubService.getCollectSampleResult("test", "test", "", 1)).thenReturn(sampleResult); - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get( - Constants.CONFIG_CONTROLLER_PATH + "/listener").param("dataId", "test").param("group", "test") - .param("tenant", "").param("sampleTime", "1"); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.CONFIG_CONTROLLER_PATH + "/listener") + .param("dataId", "test").param("group", "test").param("tenant", "").param("sampleTime", "1"); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); - GroupkeyListenserStatus groupkeyListenserStatus = JacksonUtils.toObj(actualValue, - GroupkeyListenserStatus.class); - Assert.assertEquals(200, groupkeyListenserStatus.getCollectStatus()); - Assert.assertEquals(1, groupkeyListenserStatus.getLisentersGroupkeyStatus().size()); - Assert.assertEquals("test", groupkeyListenserStatus.getLisentersGroupkeyStatus().get("test")); + GroupkeyListenserStatus groupkeyListenserStatus = JacksonUtils.toObj(actualValue, GroupkeyListenserStatus.class); + assertEquals(200, groupkeyListenserStatus.getCollectStatus()); + assertEquals(1, groupkeyListenserStatus.getLisentersGroupkeyStatus().size()); + assertEquals("test", groupkeyListenserStatus.getLisentersGroupkeyStatus().get("test")); } @Test - public void testSearchConfig() throws Exception { + void testSearchConfig() throws Exception { List configInfoList = new ArrayList<>(); ConfigInfo configInfo = new ConfigInfo("test", "test", "test"); configInfoList.add(configInfo); @@ -281,12 +278,11 @@ public void testSearchConfig() throws Exception { page.setPageItems(configInfoList); Map configAdvanceInfo = new HashMap<>(8); - when(configInfoPersistService.findConfigInfo4Page(1, 10, "test", "test", "", configAdvanceInfo)).thenReturn( - page); + when(configInfoPersistService.findConfigInfo4Page(1, 10, "test", "test", "", configAdvanceInfo)).thenReturn(page); - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.CONFIG_CONTROLLER_PATH) - .param("search", "accurate").param("dataId", "test").param("group", "test").param("appName", "") - .param("tenant", "").param("config_tags", "").param("pageNo", "1").param("pageSize", "10"); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.CONFIG_CONTROLLER_PATH).param("search", "accurate") + .param("dataId", "test").param("group", "test").param("appName", "").param("tenant", "").param("config_tags", "") + .param("pageNo", "1").param("pageSize", "10"); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); @@ -294,14 +290,14 @@ public void testSearchConfig() throws Exception { List resultList = JacksonUtils.toObj(pageItemsNode.toString(), List.class); ConfigInfo resConfigInfo = JacksonUtils.toObj(pageItemsNode.get(0).toString(), ConfigInfo.class); - Assert.assertEquals(configInfoList.size(), resultList.size()); - Assert.assertEquals(configInfo.getDataId(), resConfigInfo.getDataId()); - Assert.assertEquals(configInfo.getGroup(), resConfigInfo.getGroup()); - Assert.assertEquals(configInfo.getContent(), resConfigInfo.getContent()); + assertEquals(configInfoList.size(), resultList.size()); + assertEquals(configInfo.getDataId(), resConfigInfo.getDataId()); + assertEquals(configInfo.getGroup(), resConfigInfo.getGroup()); + assertEquals(configInfo.getContent(), resConfigInfo.getContent()); } @Test - public void testFuzzySearchConfig() throws Exception { + void testFuzzySearchConfig() throws Exception { List configInfoList = new ArrayList<>(); ConfigInfo configInfo = new ConfigInfo("test", "test", "test"); @@ -314,41 +310,39 @@ public void testFuzzySearchConfig() throws Exception { page.setPageItems(configInfoList); Map configAdvanceInfo = new HashMap<>(8); - when(configInfoPersistService.findConfigInfoLike4Page(1, 10, "test", "test", "", configAdvanceInfo)).thenReturn( - page); + when(configInfoPersistService.findConfigInfoLike4Page(1, 10, "test", "test", "", configAdvanceInfo)).thenReturn(page); - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.CONFIG_CONTROLLER_PATH) - .param("search", "blur").param("dataId", "test").param("group", "test").param("appName", "") - .param("tenant", "").param("config_tags", "").param("pageNo", "1").param("pageSize", "10"); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.CONFIG_CONTROLLER_PATH).param("search", "blur") + .param("dataId", "test").param("group", "test").param("appName", "").param("tenant", "").param("config_tags", "") + .param("pageNo", "1").param("pageSize", "10"); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); List resultList = JacksonUtils.toObj(JacksonUtils.toObj(actualValue).get("pageItems").toString(), List.class); - ConfigInfo resConfigInfo = JacksonUtils.toObj( - JacksonUtils.toObj(actualValue).get("pageItems").get(0).toString(), ConfigInfo.class); + ConfigInfo resConfigInfo = JacksonUtils.toObj(JacksonUtils.toObj(actualValue).get("pageItems").get(0).toString(), ConfigInfo.class); - Assert.assertEquals(configInfoList.size(), resultList.size()); - Assert.assertEquals(configInfo.getDataId(), resConfigInfo.getDataId()); - Assert.assertEquals(configInfo.getGroup(), resConfigInfo.getGroup()); - Assert.assertEquals(configInfo.getContent(), resConfigInfo.getContent()); + assertEquals(configInfoList.size(), resultList.size()); + assertEquals(configInfo.getDataId(), resConfigInfo.getDataId()); + assertEquals(configInfo.getGroup(), resConfigInfo.getGroup()); + assertEquals(configInfo.getContent(), resConfigInfo.getContent()); } @Test - public void testStopBeta() throws Exception { + void testStopBeta() throws Exception { - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.delete(Constants.CONFIG_CONTROLLER_PATH) - .param("beta", "true").param("dataId", "test").param("group", "test").param("tenant", ""); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.delete(Constants.CONFIG_CONTROLLER_PATH).param("beta", "true") + .param("dataId", "test").param("group", "test").param("tenant", ""); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); String code = JacksonUtils.toObj(actualValue).get("code").toString(); String data = JacksonUtils.toObj(actualValue).get("data").toString(); - Assert.assertEquals("200", code); - Assert.assertEquals("true", data); + assertEquals("200", code); + assertEquals("true", data); } @Test - public void testQueryBeta() throws Exception { + void testQueryBeta() throws Exception { ConfigInfoBetaWrapper configInfoBetaWrapper = new ConfigInfoBetaWrapper(); configInfoBetaWrapper.setDataId("test"); @@ -357,22 +351,22 @@ public void testQueryBeta() throws Exception { when(configInfoBetaPersistService.findConfigInfo4Beta("test", "test", "")).thenReturn(configInfoBetaWrapper); - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.CONFIG_CONTROLLER_PATH) - .param("beta", "true").param("dataId", "test").param("group", "test").param("tenant", ""); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.CONFIG_CONTROLLER_PATH).param("beta", "true") + .param("dataId", "test").param("group", "test").param("tenant", ""); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); String code = JacksonUtils.toObj(actualValue).get("code").toString(); String data = JacksonUtils.toObj(actualValue).get("data").toString(); ConfigInfoBetaWrapper resConfigInfoBetaWrapper = JacksonUtils.toObj(data, ConfigInfoBetaWrapper.class); - Assert.assertEquals("200", code); - Assert.assertEquals(configInfoBetaWrapper.getDataId(), resConfigInfoBetaWrapper.getDataId()); - Assert.assertEquals(configInfoBetaWrapper.getGroup(), resConfigInfoBetaWrapper.getGroup()); - Assert.assertEquals(configInfoBetaWrapper.getContent(), resConfigInfoBetaWrapper.getContent()); + assertEquals("200", code); + assertEquals(configInfoBetaWrapper.getDataId(), resConfigInfoBetaWrapper.getDataId()); + assertEquals(configInfoBetaWrapper.getGroup(), resConfigInfoBetaWrapper.getGroup()); + assertEquals(configInfoBetaWrapper.getContent(), resConfigInfoBetaWrapper.getContent()); } @Test - public void testExportConfig() throws Exception { + void testExportConfig() throws Exception { String dataId = "dataId1.json"; String group = "group2"; @@ -389,17 +383,16 @@ public void testExportConfig() throws Exception { Mockito.when(configInfoPersistService.findAllConfigInfo4Export(eq(dataId), eq(group), eq(tenant), eq(appname), eq(Arrays.asList(1L, 2L)))).thenReturn(dataList); - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.CONFIG_CONTROLLER_PATH) - .param("export", "true").param("dataId", dataId).param("group", group).param("tenant", tenant) - .param("appName", appname).param("ids", "1,2"); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.CONFIG_CONTROLLER_PATH).param("export", "true") + .param("dataId", dataId).param("group", group).param("tenant", tenant).param("appName", appname).param("ids", "1,2"); int actualValue = mockmvc.perform(builder).andReturn().getResponse().getStatus(); - Assert.assertEquals(200, actualValue); + assertEquals(200, actualValue); } @Test - public void testExportConfigV2() throws Exception { + void testExportConfigV2() throws Exception { String dataId = "dataId2.json"; String group = "group2"; String tenant = "tenant234"; @@ -414,17 +407,16 @@ public void testExportConfigV2() throws Exception { dataList.add(configAllInfo); Mockito.when(configInfoPersistService.findAllConfigInfo4Export(eq(dataId), eq(group), eq(tenant), eq(appname), eq(Arrays.asList(1L, 2L)))).thenReturn(dataList); - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.CONFIG_CONTROLLER_PATH) - .param("exportV2", "true").param("dataId", dataId).param("group", group).param("tenant", tenant) - .param("appName", appname).param("ids", "1,2"); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.CONFIG_CONTROLLER_PATH).param("exportV2", "true") + .param("dataId", dataId).param("group", group).param("tenant", tenant).param("appName", appname).param("ids", "1,2"); int actualValue = mockmvc.perform(builder).andReturn().getResponse().getStatus(); - Assert.assertEquals(200, actualValue); + assertEquals(200, actualValue); } @Test - public void testImportAndPublishConfig() throws Exception { + void testImportAndPublishConfig() throws Exception { MockedStatic zipUtilsMockedStatic = Mockito.mockStatic(ZipUtils.class); List zipItems = new ArrayList<>(); ZipUtils.ZipItem zipItem = new ZipUtils.ZipItem("test/test", "test"); @@ -436,26 +428,23 @@ public void testImportAndPublishConfig() throws Exception { when(namespacePersistService.tenantInfoCountByTenantId("public")).thenReturn(1); Map map = new HashMap<>(); map.put("test", "test"); - when(configInfoPersistService.batchInsertOrUpdate(anyList(), anyString(), anyString(), any(), - any())).thenReturn(map); + when(configInfoPersistService.batchInsertOrUpdate(anyList(), anyString(), anyString(), any(), any())).thenReturn(map); - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.multipart(Constants.CONFIG_CONTROLLER_PATH) - .file(file).param("import", "true").param("src_user", "test").param("namespace", "public") - .param("policy", "ABORT"); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.multipart(Constants.CONFIG_CONTROLLER_PATH).file(file) + .param("import", "true").param("src_user", "test").param("namespace", "public").param("policy", "ABORT"); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); String code = JacksonUtils.toObj(actualValue).get("code").toString(); - Assert.assertEquals("200", code); - Map resultMap = JacksonUtils.toObj(JacksonUtils.toObj(actualValue).get("data").toString(), - Map.class); - Assert.assertEquals(map.get("test"), resultMap.get("test").toString()); + assertEquals("200", code); + Map resultMap = JacksonUtils.toObj(JacksonUtils.toObj(actualValue).get("data").toString(), Map.class); + assertEquals(map.get("test"), resultMap.get("test").toString()); zipUtilsMockedStatic.close(); } @Test - public void testImportAndPublishConfigV2() throws Exception { + void testImportAndPublishConfigV2() throws Exception { List zipItems = new ArrayList<>(); String dataId = "dataId23456.json"; String group = "group132"; @@ -478,26 +467,23 @@ public void testImportAndPublishConfigV2() throws Exception { when(namespacePersistService.tenantInfoCountByTenantId("public")).thenReturn(1); Map map = new HashMap<>(); map.put("test", "test"); - when(configInfoPersistService.batchInsertOrUpdate(anyList(), anyString(), anyString(), any(), - any())).thenReturn(map); + when(configInfoPersistService.batchInsertOrUpdate(anyList(), anyString(), anyString(), any(), any())).thenReturn(map); - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.multipart(Constants.CONFIG_CONTROLLER_PATH) - .file(file).param("import", "true").param("src_user", "test").param("namespace", "public") - .param("policy", "ABORT"); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.multipart(Constants.CONFIG_CONTROLLER_PATH).file(file) + .param("import", "true").param("src_user", "test").param("namespace", "public").param("policy", "ABORT"); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); String code = JacksonUtils.toObj(actualValue).get("code").toString(); - Assert.assertEquals("200", code); - Map resultMap = JacksonUtils.toObj(JacksonUtils.toObj(actualValue).get("data").toString(), - Map.class); - Assert.assertEquals(map.get("test"), resultMap.get("test").toString()); + assertEquals("200", code); + Map resultMap = JacksonUtils.toObj(JacksonUtils.toObj(actualValue).get("data").toString(), Map.class); + assertEquals(map.get("test"), resultMap.get("test").toString()); zipUtilsMockedStatic.close(); } @Test - public void testCloneConfig() throws Exception { + void testCloneConfig() throws Exception { SameNamespaceCloneConfigBean sameNamespaceCloneConfigBean = new SameNamespaceCloneConfigBean(); sameNamespaceCloneConfigBean.setCfgId(1L); sameNamespaceCloneConfigBean.setDataId("test"); @@ -516,24 +502,21 @@ public void testCloneConfig() throws Exception { List idList = new ArrayList<>(configBeansList.size()); idList.add(sameNamespaceCloneConfigBean.getCfgId()); - when(configInfoPersistService.findAllConfigInfo4Export(null, null, null, null, idList)).thenReturn( - queryedDataList); + when(configInfoPersistService.findAllConfigInfo4Export(null, null, null, null, idList)).thenReturn(queryedDataList); Map map = new HashMap<>(); map.put("test", "test"); - when(configInfoPersistService.batchInsertOrUpdate(anyList(), anyString(), anyString(), any(), - any())).thenReturn(map); + when(configInfoPersistService.batchInsertOrUpdate(anyList(), anyString(), anyString(), any(), any())).thenReturn(map); - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(Constants.CONFIG_CONTROLLER_PATH) - .param("clone", "true").param("src_user", "test").param("tenant", "public").param("policy", "ABORT") - .content(JacksonUtils.toJson(configBeansList)).contentType(MediaType.APPLICATION_JSON); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(Constants.CONFIG_CONTROLLER_PATH).param("clone", "true") + .param("src_user", "test").param("tenant", "public").param("policy", "ABORT").content(JacksonUtils.toJson(configBeansList)) + .contentType(MediaType.APPLICATION_JSON); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); String code = JacksonUtils.toObj(actualValue).get("code").toString(); - Assert.assertEquals("200", code); - Map resultMap = JacksonUtils.toObj(JacksonUtils.toObj(actualValue).get("data").toString(), - Map.class); - Assert.assertEquals(map.get("test"), resultMap.get("test").toString()); + assertEquals("200", code); + Map resultMap = JacksonUtils.toObj(JacksonUtils.toObj(actualValue).get("data").toString(), Map.class); + assertEquals(map.get("test"), resultMap.get("test").toString()); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/controller/ConfigOpsControllerTest.java b/config/src/test/java/com/alibaba/nacos/config/server/controller/ConfigOpsControllerTest.java index 884f97946f3..2c4a7f34d5e 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/controller/ConfigOpsControllerTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/controller/ConfigOpsControllerTest.java @@ -17,29 +17,27 @@ package com.alibaba.nacos.config.server.controller; import com.alibaba.nacos.common.utils.JacksonUtils; +import com.alibaba.nacos.config.server.configuration.ConfigCommonConfig; import com.alibaba.nacos.config.server.constant.Constants; +import com.alibaba.nacos.config.server.service.dump.DumpService; +import com.alibaba.nacos.persistence.configuration.DatasourceConfiguration; import com.alibaba.nacos.persistence.datasource.DynamicDataSource; import com.alibaba.nacos.persistence.datasource.LocalDataSourceServiceImpl; -import com.alibaba.nacos.config.server.service.dump.DumpService; import com.alibaba.nacos.persistence.repository.embedded.operate.DatabaseOperate; -import com.alibaba.nacos.persistence.configuration.DatasourceConfiguration; -import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.utils.ApplicationUtils; -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.InjectMocks; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.Mockito; -import org.springframework.core.env.StandardEnvironment; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.mock.web.MockMultipartFile; import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; @@ -50,21 +48,17 @@ import javax.servlet.ServletContext; import java.util.ArrayList; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; -@RunWith(SpringJUnit4ClassRunner.class) +@ExtendWith(SpringExtension.class) @ContextConfiguration(classes = MockServletContext.class) @WebAppConfiguration -public class ConfigOpsControllerTest { +class ConfigOpsControllerTest { @InjectMocks ConfigOpsController configOpsController; - private MockMvc mockMvc; - - @Mock - private ServletContext servletContext; - @Mock DumpService dumpService; @@ -74,16 +68,21 @@ public class ConfigOpsControllerTest { MockedStatic applicationUtilsMockedStatic; - @After - public void after() { + private MockMvc mockMvc; + + @Mock + private ServletContext servletContext; + + @AfterEach + void after() { datasourceConfigurationMockedStatic.close(); dynamicDataSourceMockedStatic.close(); applicationUtilsMockedStatic.close(); + ConfigCommonConfig.getInstance().setDerbyOpsEnabled(false); } - @Before - public void init() { - EnvUtil.setEnvironment(new StandardEnvironment()); + @BeforeEach + void init() { when(servletContext.getContextPath()).thenReturn("/nacos"); ReflectionTestUtils.setField(configOpsController, "dumpService", dumpService); mockMvc = MockMvcBuilders.standaloneSetup(configOpsController).build(); @@ -94,26 +93,25 @@ public void init() { } @Test - public void testUpdateLocalCacheFromStore() throws Exception { + void testUpdateLocalCacheFromStore() throws Exception { - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post( - Constants.OPS_CONTROLLER_PATH + "/localCache"); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(Constants.OPS_CONTROLLER_PATH + "/localCache"); int actualValue = mockMvc.perform(builder).andReturn().getResponse().getStatus(); - Assert.assertEquals(200, actualValue); + assertEquals(200, actualValue); } @Test - public void testSetLogLevel() throws Exception { + void testSetLogLevel() throws Exception { - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.put(Constants.OPS_CONTROLLER_PATH + "/log") - .param("logName", "test").param("logLevel", "test"); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.put(Constants.OPS_CONTROLLER_PATH + "/log").param("logName", "test") + .param("logLevel", "test"); int actualValue = mockMvc.perform(builder).andReturn().getResponse().getStatus(); - Assert.assertEquals(200, actualValue); + assertEquals(200, actualValue); } @Test - public void testDerbyOps() throws Exception { - + void testDerbyOps() throws Exception { + ConfigCommonConfig.getInstance().setDerbyOpsEnabled(true); datasourceConfigurationMockedStatic.when(DatasourceConfiguration::isEmbeddedStorage).thenReturn(true); DynamicDataSource dataSource = Mockito.mock(DynamicDataSource.class); dynamicDataSourceMockedStatic.when(DynamicDataSource::getInstance).thenReturn(dataSource); @@ -126,22 +124,22 @@ public void testDerbyOps() throws Exception { MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.OPS_CONTROLLER_PATH + "/derby") .param("sql", "SELECT * FROM TEST"); String actualValue = mockMvc.perform(builder).andReturn().getResponse().getContentAsString(); - Assert.assertEquals("200", JacksonUtils.toObj(actualValue).get("code").toString()); + assertEquals("200", JacksonUtils.toObj(actualValue).get("code").toString()); } @Test - public void testImportDerby() throws Exception { - + void testImportDerby() throws Exception { + ConfigCommonConfig.getInstance().setDerbyOpsEnabled(true); datasourceConfigurationMockedStatic.when(DatasourceConfiguration::isEmbeddedStorage).thenReturn(true); applicationUtilsMockedStatic.when(() -> ApplicationUtils.getBean(DatabaseOperate.class)) .thenReturn(Mockito.mock(DatabaseOperate.class)); MockMultipartFile file = new MockMultipartFile("file", "test.zip", "application/zip", "test".getBytes()); - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.multipart( - Constants.OPS_CONTROLLER_PATH + "/data/removal").file(file); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.multipart(Constants.OPS_CONTROLLER_PATH + "/data/removal") + .file(file); int actualValue = mockMvc.perform(builder).andReturn().getResponse().getStatus(); - Assert.assertEquals(200, actualValue); + assertEquals(200, actualValue); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/controller/ConfigServletInnerTest.java b/config/src/test/java/com/alibaba/nacos/config/server/controller/ConfigServletInnerTest.java index 56bf83211d9..115c39abe2a 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/controller/ConfigServletInnerTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/controller/ConfigServletInnerTest.java @@ -31,11 +31,10 @@ import com.alibaba.nacos.config.server.utils.MD5Util; import com.alibaba.nacos.config.server.utils.PropertyUtil; import com.alibaba.nacos.sys.env.EnvUtil; -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.InjectMocks; import org.mockito.Mock; import org.mockito.MockedStatic; @@ -43,7 +42,7 @@ import org.springframework.core.env.StandardEnvironment; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.util.ReflectionTestUtils; @@ -56,32 +55,34 @@ import static com.alibaba.nacos.api.common.Constants.VIPSERVER_TAG; import static com.alibaba.nacos.config.server.constant.Constants.CONTENT_MD5; import static com.alibaba.nacos.config.server.utils.RequestUtil.CLIENT_APPNAME_HEADER; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; -@RunWith(SpringJUnit4ClassRunner.class) +@ExtendWith(SpringExtension.class) @WebAppConfiguration -public class ConfigServletInnerTest { +class ConfigServletInnerTest { + + static MockedStatic configDiskServiceFactoryMockedStatic; @InjectMocks ConfigServletInner configServletInner; - @Mock - private LongPollingService longPollingService; - - @Mock - private ConfigRocksDbDiskService configRocksDbDiskService; - - static MockedStatic configDiskServiceFactoryMockedStatic; - MockedStatic configCacheServiceMockedStatic; MockedStatic propertyUtilMockedStatic; MockedStatic md5UtilMockedStatic; - @Before - public void setUp() { + @Mock + private LongPollingService longPollingService; + + @Mock + private ConfigRocksDbDiskService configRocksDbDiskService; + + @BeforeEach + void setUp() { EnvUtil.setEnvironment(new StandardEnvironment()); ReflectionTestUtils.setField(configServletInner, "longPollingService", longPollingService); configCacheServiceMockedStatic = Mockito.mockStatic(ConfigCacheService.class); @@ -93,8 +94,8 @@ public void setUp() { } - @After - public void after() { + @AfterEach + void after() { if (configCacheServiceMockedStatic != null) { configCacheServiceMockedStatic.close(); @@ -113,7 +114,7 @@ public void after() { } @Test - public void testDoPollingConfig() throws Exception { + void testDoPollingConfig() throws Exception { Map clientMd5Map = new HashMap<>(); MockHttpServletRequest request = new MockHttpServletRequest(); @@ -128,15 +129,15 @@ public void testDoPollingConfig() throws Exception { String actualValue = configServletInner.doPollingConfig(request, response, clientMd5Map, 1); - Assert.assertEquals(HttpServletResponse.SC_OK + "", actualValue); - Assert.assertEquals("test-old", response.getHeader(Constants.PROBE_MODIFY_RESPONSE)); - Assert.assertEquals("test-new", response.getHeader(Constants.PROBE_MODIFY_RESPONSE_NEW)); - Assert.assertEquals("no-cache,no-store", response.getHeader("Cache-Control")); + assertEquals(HttpServletResponse.SC_OK + "", actualValue); + assertEquals("test-old", response.getHeader(Constants.PROBE_MODIFY_RESPONSE)); + assertEquals("test-new", response.getHeader(Constants.PROBE_MODIFY_RESPONSE_NEW)); + assertEquals("no-cache,no-store", response.getHeader("Cache-Control")); } @Test - public void testDoGetConfigV1Beta() throws Exception { + void testDoGetConfigV1Beta() throws Exception { configCacheServiceMockedStatic.when(() -> ConfigCacheService.tryConfigReadLock(anyString())).thenReturn(1); @@ -152,8 +153,7 @@ public void testDoGetConfigV1Beta() throws Exception { String dataId = "testDataId135"; String group = "group23"; String tenant = "tenant234"; - configCacheServiceMockedStatic.when( - () -> ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataId, group, tenant))) + configCacheServiceMockedStatic.when(() -> ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataId, group, tenant))) .thenReturn(cacheItem); MockHttpServletRequest request = new MockHttpServletRequest(); @@ -162,13 +162,12 @@ public void testDoGetConfigV1Beta() throws Exception { MockHttpServletResponse response = new MockHttpServletResponse(); String mockBetaContent = "content3456543"; when(configRocksDbDiskService.getBetaContent(dataId, group, tenant)).thenReturn(mockBetaContent); - String actualValue = configServletInner.doGetConfig(request, response, dataId, group, tenant, "", "true", - "localhost"); - Assert.assertEquals(HttpServletResponse.SC_OK + "", actualValue); - Assert.assertEquals("true", response.getHeader("isBeta")); - Assert.assertEquals("md52345Beta", response.getHeader(CONTENT_MD5)); - Assert.assertEquals("betaKey1234567", response.getHeader("Encrypted-Data-Key")); - Assert.assertEquals(mockBetaContent, response.getContentAsString()); + String actualValue = configServletInner.doGetConfig(request, response, dataId, group, tenant, "", "true", "localhost"); + assertEquals(HttpServletResponse.SC_OK + "", actualValue); + assertEquals("true", response.getHeader("isBeta")); + assertEquals("md52345Beta", response.getHeader(CONTENT_MD5)); + assertEquals("betaKey1234567", response.getHeader("Encrypted-Data-Key")); + assertEquals(mockBetaContent, response.getContentAsString()); } /** @@ -177,13 +176,13 @@ public void testDoGetConfigV1Beta() throws Exception { * @throws Exception exception. */ @Test - public void testDoGetConfigV1Tag() throws Exception { + void testDoGetConfigV1Tag() throws Exception { String dataId = "dataId123455"; String group = "group"; String tenant = "tenant"; - configCacheServiceMockedStatic.when( - () -> ConfigCacheService.tryConfigReadLock(GroupKey2.getKey(dataId, group, tenant))).thenReturn(1); + configCacheServiceMockedStatic.when(() -> ConfigCacheService.tryConfigReadLock(GroupKey2.getKey(dataId, group, tenant))) + .thenReturn(1); //mock cache item with tag. CacheItem cacheItem = new CacheItem("test"); @@ -204,8 +203,7 @@ public void testDoGetConfigV1Tag() throws Exception { long specificTs = System.currentTimeMillis(); cacheItem.getConfigCacheTags().get(specificTag).setLastModifiedTs(specificTs); - configCacheServiceMockedStatic.when( - () -> ConfigCacheService.getContentCache(GroupKey2.getKey(dataId, group, tenant))) + configCacheServiceMockedStatic.when(() -> ConfigCacheService.getContentCache(GroupKey2.getKey(dataId, group, tenant))) .thenReturn(cacheItem); //test auto tag. @@ -216,44 +214,42 @@ public void testDoGetConfigV1Tag() throws Exception { MockHttpServletResponse response = new MockHttpServletResponse(); String autoTagContent = "1234566autotag"; Mockito.when(configRocksDbDiskService.getTagContent(dataId, group, tenant, autoTag)).thenReturn(autoTagContent); - String actualValue = configServletInner.doGetConfig(request, response, dataId, group, tenant, null, "true", - "localhost"); - Assert.assertEquals(HttpServletResponse.SC_OK + "", actualValue); - Assert.assertEquals(autoTagContent, response.getContentAsString()); - Assert.assertEquals("md5autotag11", response.getHeader(CONTENT_MD5)); - Assert.assertEquals("autoTagkey", response.getHeader("Encrypted-Data-Key")); + String actualValue = configServletInner.doGetConfig(request, response, dataId, group, tenant, null, "true", "localhost"); + assertEquals(HttpServletResponse.SC_OK + "", actualValue); + assertEquals(autoTagContent, response.getContentAsString()); + assertEquals("md5autotag11", response.getHeader(CONTENT_MD5)); + assertEquals("autoTagkey", response.getHeader("Encrypted-Data-Key")); //test for specific tag. has higher propority than auto tag. response = new MockHttpServletResponse(); String specificTagContent = "1234566autotag"; when(configRocksDbDiskService.getTagContent(dataId, group, tenant, specificTag)).thenReturn(specificTagContent); - actualValue = configServletInner.doGetConfig(request, response, dataId, group, tenant, specificTag, "true", - "localhost"); - Assert.assertEquals(HttpServletResponse.SC_OK + "", actualValue); - Assert.assertEquals(specificTagContent, response.getContentAsString()); - Assert.assertEquals("md5specificTag11", response.getHeader(CONTENT_MD5)); - Assert.assertEquals("specificTagkey", response.getHeader("Encrypted-Data-Key")); + actualValue = configServletInner.doGetConfig(request, response, dataId, group, tenant, specificTag, "true", "localhost"); + assertEquals(HttpServletResponse.SC_OK + "", actualValue); + assertEquals(specificTagContent, response.getContentAsString()); + assertEquals("md5specificTag11", response.getHeader(CONTENT_MD5)); + assertEquals("specificTagkey", response.getHeader("Encrypted-Data-Key")); // test for specific tag ,not exist when(configRocksDbDiskService.getTagContent(dataId, group, tenant, "auto-tag-test-not-exist")).thenReturn(null); response = new MockHttpServletResponse(); - actualValue = configServletInner.doGetConfig(request, response, dataId, group, tenant, - "auto-tag-test-not-exist", "true", "localhost"); - Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND + "", actualValue); + actualValue = configServletInner.doGetConfig(request, response, dataId, group, tenant, "auto-tag-test-not-exist", "true", + "localhost"); + assertEquals(HttpServletResponse.SC_NOT_FOUND + "", actualValue); String expectedContent = "config data not exist"; String actualContent = response.getContentAsString(); - Assert.assertTrue(actualContent.contains(expectedContent)); + assertTrue(actualContent.contains(expectedContent)); } @Test - public void testDoGetConfigFormal() throws Exception { + void testDoGetConfigFormal() throws Exception { String dataId = "dataId1234552333"; String group = "group"; String tenant = "tenant"; - configCacheServiceMockedStatic.when( - () -> ConfigCacheService.tryConfigReadLock(GroupKey2.getKey(dataId, group, tenant))).thenReturn(1); + configCacheServiceMockedStatic.when(() -> ConfigCacheService.tryConfigReadLock(GroupKey2.getKey(dataId, group, tenant))) + .thenReturn(1); //mock cache item . CacheItem cacheItem = new CacheItem("test"); @@ -264,29 +260,27 @@ public void testDoGetConfigFormal() throws Exception { long ts = System.currentTimeMillis(); cacheItem.getConfigCache().setLastModifiedTs(ts); cacheItem.getConfigCache().setEncryptedDataKey("key2345678"); - configCacheServiceMockedStatic.when( - () -> ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataId, group, tenant))) + configCacheServiceMockedStatic.when(() -> ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataId, group, tenant))) .thenReturn(cacheItem); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); when(configRocksDbDiskService.getContent(dataId, group, tenant)).thenReturn(content); - String actualValue = configServletInner.doGetConfig(request, response, dataId, group, tenant, null, "true", - "localhost"); - Assert.assertEquals(content, response.getContentAsString()); - Assert.assertEquals(HttpServletResponse.SC_OK + "", actualValue); - Assert.assertEquals(md5, response.getHeader(CONTENT_MD5)); - Assert.assertEquals("key2345678", response.getHeader("Encrypted-Data-Key")); + String actualValue = configServletInner.doGetConfig(request, response, dataId, group, tenant, null, "true", "localhost"); + assertEquals(content, response.getContentAsString()); + assertEquals(HttpServletResponse.SC_OK + "", actualValue); + assertEquals(md5, response.getHeader(CONTENT_MD5)); + assertEquals("key2345678", response.getHeader("Encrypted-Data-Key")); } @Test - public void testDoGetConfigFormalV2() throws Exception { + void testDoGetConfigFormalV2() throws Exception { String dataId = "dataId1234552333V2"; String group = "group"; String tenant = "tenant"; - configCacheServiceMockedStatic.when( - () -> ConfigCacheService.tryConfigReadLock(GroupKey2.getKey(dataId, group, tenant))).thenReturn(1); + configCacheServiceMockedStatic.when(() -> ConfigCacheService.tryConfigReadLock(GroupKey2.getKey(dataId, group, tenant))) + .thenReturn(1); //mock cache item . CacheItem cacheItem = new CacheItem("test"); @@ -297,41 +291,36 @@ public void testDoGetConfigFormalV2() throws Exception { long ts = System.currentTimeMillis(); cacheItem.getConfigCache().setLastModifiedTs(ts); cacheItem.getConfigCache().setEncryptedDataKey("key2345678"); - configCacheServiceMockedStatic.when( - () -> ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataId, group, tenant))) + configCacheServiceMockedStatic.when(() -> ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataId, group, tenant))) .thenReturn(cacheItem); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); when(configRocksDbDiskService.getContent(dataId, group, tenant)).thenReturn(content); - String actualValue = configServletInner.doGetConfig(request, response, dataId, group, tenant, null, "true", - "localhost", true); - Assert.assertEquals(JacksonUtils.toJson(Result.success(content)), response.getContentAsString()); - Assert.assertEquals(HttpServletResponse.SC_OK + "", actualValue); - Assert.assertEquals(md5, response.getHeader(CONTENT_MD5)); - Assert.assertEquals("key2345678", response.getHeader("Encrypted-Data-Key")); - Assert.assertEquals(MediaType.APPLICATION_JSON, response.getHeader(HttpHeaderConsts.CONTENT_TYPE)); + String actualValue = configServletInner.doGetConfig(request, response, dataId, group, tenant, null, "true", "localhost", true); + assertEquals(JacksonUtils.toJson(Result.success(content)), response.getContentAsString()); + assertEquals(HttpServletResponse.SC_OK + "", actualValue); + assertEquals(md5, response.getHeader(CONTENT_MD5)); + assertEquals("key2345678", response.getHeader("Encrypted-Data-Key")); + assertEquals(MediaType.APPLICATION_JSON, response.getHeader(HttpHeaderConsts.CONTENT_TYPE)); } @Test - public void testDoGetConfigNotExist() throws Exception { + void testDoGetConfigNotExist() throws Exception { // if lockResult equals 0,cache item not exist. configCacheServiceMockedStatic.when(() -> ConfigCacheService.tryConfigReadLock(anyString())).thenReturn(0); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); - String actualValue = configServletInner.doGetConfig(request, response, "test", "test", "test", "test", "true", - "localhost"); - Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND + "", actualValue); + String actualValue = configServletInner.doGetConfig(request, response, "test", "test", "test", "test", "true", "localhost"); + assertEquals(HttpServletResponse.SC_NOT_FOUND + "", actualValue); - configCacheServiceMockedStatic.when( - () -> ConfigCacheService.getContentCache(GroupKey2.getKey("test", "test", "test"))) + configCacheServiceMockedStatic.when(() -> ConfigCacheService.getContentCache(GroupKey2.getKey("test", "test", "test"))) .thenReturn(new CacheItem(GroupKey2.getKey("test", "test", "test"))); // if lockResult less than 0 configCacheServiceMockedStatic.when(() -> ConfigCacheService.tryConfigReadLock(anyString())).thenReturn(-1); - actualValue = configServletInner.doGetConfig(request, response, "test", "test", "test", "test", "true", - "localhost"); - Assert.assertEquals(HttpServletResponse.SC_CONFLICT + "", actualValue); + actualValue = configServletInner.doGetConfig(request, response, "test", "test", "test", "test", "true", "localhost"); + assertEquals(HttpServletResponse.SC_CONFLICT + "", actualValue); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/controller/HealthControllerTest.java b/config/src/test/java/com/alibaba/nacos/config/server/controller/HealthControllerTest.java index 05d6e911f9d..3cb0b334900 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/controller/HealthControllerTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/controller/HealthControllerTest.java @@ -17,20 +17,19 @@ package com.alibaba.nacos.config.server.controller; import com.alibaba.nacos.config.server.constant.Constants; -import com.alibaba.nacos.persistence.datasource.DataSourceService; import com.alibaba.nacos.core.cluster.MemberLookup; import com.alibaba.nacos.core.cluster.ServerMemberManager; +import com.alibaba.nacos.persistence.datasource.DataSourceService; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.core.env.StandardEnvironment; import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; @@ -42,12 +41,13 @@ import java.util.HashMap; import java.util.Map; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; -@RunWith(SpringJUnit4ClassRunner.class) +@ExtendWith(SpringExtension.class) @ContextConfiguration(classes = MockServletContext.class) @WebAppConfiguration -public class HealthControllerTest { +class HealthControllerTest { @InjectMocks HealthController healthController; @@ -66,8 +66,8 @@ public class HealthControllerTest { @Mock private MemberLookup memberLookup; - @Before - public void setUp() { + @BeforeEach + void setUp() { EnvUtil.setEnvironment(new StandardEnvironment()); Map infos = new HashMap<>(); infos.put("addressServerHealth", true); @@ -80,58 +80,58 @@ public void setUp() { } @Test - public void testGetHealth() throws Exception { + void testGetHealth() throws Exception { when(dataSourceService.getHealth()).thenReturn("UP"); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.HEALTH_CONTROLLER_PATH); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); - Assert.assertEquals("UP", actualValue); + assertEquals("UP", actualValue); } @Test - public void testGetHealthWhenTheLookUpIsNull() throws Exception { + void testGetHealthWhenTheLookUpIsNull() throws Exception { when(dataSourceService.getHealth()).thenReturn("UP"); when(memberManager.getLookup()).thenReturn(null); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.HEALTH_CONTROLLER_PATH); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); - Assert.assertEquals("DOWN:address server down. ", actualValue); + assertEquals("DOWN:address server down. ", actualValue); } @Test - public void testGetHealthWhenTheLoopUpNotUseAddressServer() throws Exception { + void testGetHealthWhenTheLoopUpNotUseAddressServer() throws Exception { when(dataSourceService.getHealth()).thenReturn("UP"); when(memberManager.getLookup()).thenReturn(memberLookup); when(memberLookup.useAddressServer()).thenReturn(false); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.HEALTH_CONTROLLER_PATH); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); - Assert.assertEquals("UP", actualValue); + assertEquals("UP", actualValue); } @Test - public void testGetHealthWhenTheLoopUpInfoIsNull() throws Exception { + void testGetHealthWhenTheLoopUpInfoIsNull() throws Exception { when(dataSourceService.getHealth()).thenReturn("UP"); when(memberManager.getLookup()).thenReturn(memberLookup); when(memberLookup.useAddressServer()).thenReturn(true); when(memberLookup.info()).thenReturn(null); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.HEALTH_CONTROLLER_PATH); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); - Assert.assertEquals("DOWN:address server down. ", actualValue); + assertEquals("DOWN:address server down. ", actualValue); } @Test - public void testGetHealthWhenTheLoopUpInfoIsEmpty() throws Exception { + void testGetHealthWhenTheLoopUpInfoIsEmpty() throws Exception { when(dataSourceService.getHealth()).thenReturn("UP"); when(memberManager.getLookup()).thenReturn(memberLookup); when(memberLookup.useAddressServer()).thenReturn(true); when(memberLookup.info()).thenReturn(new HashMap<>()); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.HEALTH_CONTROLLER_PATH); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); - Assert.assertEquals("DOWN:address server down. ", actualValue); + assertEquals("DOWN:address server down. ", actualValue); } @Test - public void testGetHealthWhenTheLoopUpInfoIsDown() throws Exception { + void testGetHealthWhenTheLoopUpInfoIsDown() throws Exception { when(dataSourceService.getHealth()).thenReturn("UP"); when(memberManager.getLookup()).thenReturn(memberLookup); when(memberLookup.useAddressServer()).thenReturn(true); @@ -142,11 +142,11 @@ public void testGetHealthWhenTheLoopUpInfoIsDown() throws Exception { MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.HEALTH_CONTROLLER_PATH); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); - Assert.assertEquals("DOWN:address server down. ", actualValue); + assertEquals("DOWN:address server down. ", actualValue); } @Test - public void testGetHealthWhenTheLoopUpInfoIsUP() throws Exception { + void testGetHealthWhenTheLoopUpInfoIsUP() throws Exception { when(dataSourceService.getHealth()).thenReturn("UP"); when(memberManager.getLookup()).thenReturn(memberLookup); when(memberLookup.useAddressServer()).thenReturn(true); @@ -157,11 +157,11 @@ public void testGetHealthWhenTheLoopUpInfoIsUP() throws Exception { MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.HEALTH_CONTROLLER_PATH); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); - Assert.assertEquals("UP", actualValue); + assertEquals("UP", actualValue); } @Test - public void testGetHealthWhenTheLoopUpInfoParseError() throws Exception { + void testGetHealthWhenTheLoopUpInfoParseError() throws Exception { when(dataSourceService.getHealth()).thenReturn("UP"); when(memberManager.getLookup()).thenReturn(memberLookup); when(memberLookup.useAddressServer()).thenReturn(true); @@ -172,6 +172,6 @@ public void testGetHealthWhenTheLoopUpInfoParseError() throws Exception { MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.HEALTH_CONTROLLER_PATH); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); - Assert.assertEquals("DOWN:address server down. ", actualValue); + assertEquals("DOWN:address server down. ", actualValue); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/controller/HistoryControllerTest.java b/config/src/test/java/com/alibaba/nacos/config/server/controller/HistoryControllerTest.java index 6eca767d07f..f36b2ddf662 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/controller/HistoryControllerTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/controller/HistoryControllerTest.java @@ -20,21 +20,20 @@ import com.alibaba.nacos.config.server.constant.Constants; import com.alibaba.nacos.config.server.model.ConfigHistoryInfo; import com.alibaba.nacos.config.server.model.ConfigInfoWrapper; -import com.alibaba.nacos.persistence.model.Page; import com.alibaba.nacos.config.server.service.HistoryService; +import com.alibaba.nacos.persistence.model.Page; import com.alibaba.nacos.sys.env.EnvUtil; import com.fasterxml.jackson.databind.JsonNode; -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.InjectMocks; import org.mockito.Mock; import org.springframework.core.env.StandardEnvironment; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; @@ -48,12 +47,13 @@ import java.util.Date; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; -@RunWith(SpringJUnit4ClassRunner.class) +@ExtendWith(SpringExtension.class) @ContextConfiguration(classes = MockServletContext.class) @WebAppConfiguration -public class HistoryControllerTest { +class HistoryControllerTest { @InjectMocks HistoryController historyController; @@ -66,8 +66,8 @@ public class HistoryControllerTest { @Mock private HistoryService historyService; - @Before - public void setUp() { + @BeforeEach + void setUp() { EnvUtil.setEnvironment(new StandardEnvironment()); when(servletContext.getContextPath()).thenReturn("/nacos"); ReflectionTestUtils.setField(historyController, "historyService", historyService); @@ -75,7 +75,7 @@ public void setUp() { } @Test - public void testListConfigHistory() throws Exception { + void testListConfigHistory() throws Exception { ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo(); configHistoryInfo.setDataId("test"); @@ -94,10 +94,8 @@ public void testListConfigHistory() throws Exception { when(historyService.listConfigHistory("test", "test", "", 1, 10)).thenReturn(page); - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.HISTORY_CONTROLLER_PATH) - .param("search", "accurate").param("dataId", "test") - .param("group", "test").param("tenant", "") - .param("appName", "").param("pageNo", "1") + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.HISTORY_CONTROLLER_PATH).param("search", "accurate") + .param("dataId", "test").param("group", "test").param("tenant", "").param("appName", "").param("pageNo", "1") .param("pageSize", "10"); MockHttpServletResponse response = mockmvc.perform(builder).andReturn().getResponse(); @@ -108,15 +106,15 @@ public void testListConfigHistory() throws Exception { List resultList = JacksonUtils.toObj(pageItemsNode.toString(), List.class); ConfigHistoryInfo resConfigHistoryInfo = JacksonUtils.toObj(pageItemsNode.get(0).toString(), ConfigHistoryInfo.class); - Assert.assertEquals(configHistoryInfoList.size(), resultList.size()); - Assert.assertEquals(configHistoryInfo.getDataId(), resConfigHistoryInfo.getDataId()); - Assert.assertEquals(configHistoryInfo.getGroup(), resConfigHistoryInfo.getGroup()); - Assert.assertEquals(configHistoryInfo.getContent(), resConfigHistoryInfo.getContent()); + assertEquals(configHistoryInfoList.size(), resultList.size()); + assertEquals(configHistoryInfo.getDataId(), resConfigHistoryInfo.getDataId()); + assertEquals(configHistoryInfo.getGroup(), resConfigHistoryInfo.getGroup()); + assertEquals(configHistoryInfo.getContent(), resConfigHistoryInfo.getContent()); } @Test - public void testGetConfigHistoryInfo() throws Exception { + void testGetConfigHistoryInfo() throws Exception { ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo(); configHistoryInfo.setDataId("test"); @@ -128,23 +126,20 @@ public void testGetConfigHistoryInfo() throws Exception { when(historyController.getConfigHistoryInfo("test", "test", "", 1L)).thenReturn(configHistoryInfo); - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.HISTORY_CONTROLLER_PATH) - .param("dataId", "test") - .param("group", "test") - .param("tenant", "") - .param("nid", "1"); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.HISTORY_CONTROLLER_PATH).param("dataId", "test") + .param("group", "test").param("tenant", "").param("nid", "1"); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); ConfigHistoryInfo resConfigHistoryInfo = JacksonUtils.toObj(actualValue, ConfigHistoryInfo.class); - Assert.assertEquals(configHistoryInfo.getDataId(), resConfigHistoryInfo.getDataId()); - Assert.assertEquals(configHistoryInfo.getGroup(), resConfigHistoryInfo.getGroup()); - Assert.assertEquals(configHistoryInfo.getContent(), resConfigHistoryInfo.getContent()); + assertEquals(configHistoryInfo.getDataId(), resConfigHistoryInfo.getDataId()); + assertEquals(configHistoryInfo.getGroup(), resConfigHistoryInfo.getGroup()); + assertEquals(configHistoryInfo.getContent(), resConfigHistoryInfo.getContent()); } @Test - public void testGetPreviousConfigHistoryInfo() throws Exception { + void testGetPreviousConfigHistoryInfo() throws Exception { ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo(); configHistoryInfo.setDataId("test"); @@ -157,22 +152,19 @@ public void testGetPreviousConfigHistoryInfo() throws Exception { when(historyService.getPreviousConfigHistoryInfo("test", "test", "", 1L)).thenReturn(configHistoryInfo); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.HISTORY_CONTROLLER_PATH + "/previous") - .param("dataId", "test") - .param("group", "test") - .param("tenant", "") - .param("id", "1"); + .param("dataId", "test").param("group", "test").param("tenant", "").param("id", "1"); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); ConfigHistoryInfo resConfigHistoryInfo = JacksonUtils.toObj(actualValue, ConfigHistoryInfo.class); - Assert.assertEquals(configHistoryInfo.getDataId(), resConfigHistoryInfo.getDataId()); - Assert.assertEquals(configHistoryInfo.getGroup(), resConfigHistoryInfo.getGroup()); - Assert.assertEquals(configHistoryInfo.getContent(), resConfigHistoryInfo.getContent()); + assertEquals(configHistoryInfo.getDataId(), resConfigHistoryInfo.getDataId()); + assertEquals(configHistoryInfo.getGroup(), resConfigHistoryInfo.getGroup()); + assertEquals(configHistoryInfo.getContent(), resConfigHistoryInfo.getContent()); } @Test - public void testGetDataIds() throws Exception { + void testGetDataIds() throws Exception { ConfigInfoWrapper configInfoWrapper = new ConfigInfoWrapper(); configInfoWrapper.setDataId("test"); @@ -187,12 +179,13 @@ public void testGetDataIds() throws Exception { String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); List resConfigInfoWrappers = JacksonUtils.toObj(actualValue, List.class); - ConfigInfoWrapper resConfigInfoWrapper = JacksonUtils.toObj(JacksonUtils.toObj(actualValue).get(0).toString(), ConfigInfoWrapper.class); + ConfigInfoWrapper resConfigInfoWrapper = JacksonUtils.toObj(JacksonUtils.toObj(actualValue).get(0).toString(), + ConfigInfoWrapper.class); - Assert.assertEquals(configInfoWrappers.size(), resConfigInfoWrappers.size()); - Assert.assertEquals(configInfoWrapper.getDataId(), resConfigInfoWrapper.getDataId()); - Assert.assertEquals(configInfoWrapper.getGroup(), resConfigInfoWrapper.getGroup()); - Assert.assertEquals(configInfoWrapper.getContent(), resConfigInfoWrapper.getContent()); + assertEquals(configInfoWrappers.size(), resConfigInfoWrappers.size()); + assertEquals(configInfoWrapper.getDataId(), resConfigInfoWrapper.getDataId()); + assertEquals(configInfoWrapper.getGroup(), resConfigInfoWrapper.getGroup()); + assertEquals(configInfoWrapper.getContent(), resConfigInfoWrapper.getContent()); } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/controller/ListenerControllerTest.java b/config/src/test/java/com/alibaba/nacos/config/server/controller/ListenerControllerTest.java index dadedd557e8..1078932b8ab 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/controller/ListenerControllerTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/controller/ListenerControllerTest.java @@ -22,16 +22,15 @@ import com.alibaba.nacos.config.server.model.SampleResult; import com.alibaba.nacos.config.server.service.ConfigSubService; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.core.env.StandardEnvironment; import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; @@ -40,16 +39,16 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import javax.servlet.ServletContext; - import java.util.HashMap; import java.util.Map; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; -@RunWith(SpringJUnit4ClassRunner.class) +@ExtendWith(SpringExtension.class) @ContextConfiguration(classes = MockServletContext.class) @WebAppConfiguration -public class ListenerControllerTest { +class ListenerControllerTest { @InjectMocks ListenerController listenerController; @@ -62,8 +61,8 @@ public class ListenerControllerTest { @Mock private ConfigSubService configSubService; - @Before - public void setUp() { + @BeforeEach + void setUp() { EnvUtil.setEnvironment(new StandardEnvironment()); when(servletContext.getContextPath()).thenReturn("/nacos"); ReflectionTestUtils.setField(listenerController, "configSubService", configSubService); @@ -71,7 +70,7 @@ public void setUp() { } @Test - public void testGetAllSubClientConfigByIp() throws Exception { + void testGetAllSubClientConfigByIp() throws Exception { SampleResult sampleResult = new SampleResult(); Map map = new HashMap<>(); @@ -79,15 +78,14 @@ public void testGetAllSubClientConfigByIp() throws Exception { sampleResult.setLisentersGroupkeyStatus(map); when(configSubService.getCollectSampleResultByIp("localhost", 1)).thenReturn(sampleResult); - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.LISTENER_CONTROLLER_PATH) - .param("ip", "localhost").param("all", "true") - .param("tenant", "test").param("sampleTime", "1"); + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.LISTENER_CONTROLLER_PATH).param("ip", "localhost") + .param("all", "true").param("tenant", "test").param("sampleTime", "1"); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); GroupkeyListenserStatus groupkeyListenserStatus = JacksonUtils.toObj(actualValue, GroupkeyListenserStatus.class); Map resultMap = groupkeyListenserStatus.getLisentersGroupkeyStatus(); - Assert.assertEquals(map.get("test"), resultMap.get("test")); + assertEquals(map.get("test"), resultMap.get("test")); } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/controller/v2/ConfigControllerV2Test.java b/config/src/test/java/com/alibaba/nacos/config/server/controller/v2/ConfigControllerV2Test.java index 89951dc7ffb..d53152f98c0 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/controller/v2/ConfigControllerV2Test.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/controller/v2/ConfigControllerV2Test.java @@ -24,21 +24,22 @@ import com.alibaba.nacos.config.server.controller.ConfigServletInner; import com.alibaba.nacos.config.server.model.ConfigInfo; import com.alibaba.nacos.config.server.model.ConfigRequestInfo; -import com.alibaba.nacos.persistence.model.Page; import com.alibaba.nacos.config.server.model.form.ConfigForm; import com.alibaba.nacos.config.server.service.ConfigDetailService; import com.alibaba.nacos.config.server.service.ConfigOperationService; import com.alibaba.nacos.config.server.service.repository.ConfigInfoPersistService; import com.alibaba.nacos.core.auth.AuthFilter; +import com.alibaba.nacos.persistence.model.Page; import com.alibaba.nacos.sys.env.EnvUtil; import com.fasterxml.jackson.databind.JsonNode; -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.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.mockito.stubbing.Answer; import org.springframework.core.env.StandardEnvironment; import org.springframework.mock.web.MockHttpServletRequest; @@ -51,13 +52,13 @@ import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import static org.junit.Assert.assertEquals; +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.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -65,8 +66,24 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class ConfigControllerV2Test { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class ConfigControllerV2Test { + + private static final String TEST_DATA_ID = "test"; + + private static final String TEST_GROUP = "test"; + + private static final String TEST_NAMESPACE_ID = ""; + + private static final String TEST_NAMESPACE_ID_PUBLIC = "public"; + + private static final String TEST_TAG = ""; + + private static final String TEST_CONTENT = "test config"; + + private static final String TEST_ENCRYPTED_DATA_KEY = "test_encrypted_data_key"; @InjectMocks private AuthFilter authFilter; @@ -92,20 +109,8 @@ public class ConfigControllerV2Test { private ConfigDetailService configDetailService; - private static final String TEST_DATA_ID = "test"; - - private static final String TEST_GROUP = "test"; - - private static final String TEST_NAMESPACE_ID = ""; - - private static final String TEST_NAMESPACE_ID_PUBLIC = "public"; - - private static final String TEST_TAG = ""; - - private static final String TEST_CONTENT = "test config"; - - @Before - public void setUp() { + @BeforeEach + void setUp() { EnvUtil.setEnvironment(new StandardEnvironment()); configDetailService = new ConfigDetailService(configInfoPersistService); configControllerV2 = new ConfigControllerV2(inner, configOperationService, configDetailService); @@ -114,24 +119,23 @@ public void setUp() { } @Test - public void testGetConfig() throws Exception { + void testGetConfig() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); Result stringResult = Result.success(TEST_CONTENT); doAnswer(x -> { x.getArgument(1, HttpServletResponse.class).setStatus(200); - x.getArgument(1, HttpServletResponse.class) - .setContentType(com.alibaba.nacos.common.http.param.MediaType.APPLICATION_JSON); + x.getArgument(1, HttpServletResponse.class).setContentType(com.alibaba.nacos.common.http.param.MediaType.APPLICATION_JSON); x.getArgument(1, HttpServletResponse.class).getWriter().print(JacksonUtils.toJson(stringResult)); return null; - }).when(inner).doGetConfig(any(HttpServletRequest.class), any(HttpServletResponse.class), eq(TEST_DATA_ID), - eq(TEST_GROUP), eq(TEST_NAMESPACE_ID), eq(TEST_TAG), eq(null), anyString(), eq(true)); + }).when(inner).doGetConfig(any(HttpServletRequest.class), any(HttpServletResponse.class), eq(TEST_DATA_ID), eq(TEST_GROUP), + eq(TEST_NAMESPACE_ID), eq(TEST_TAG), eq(null), anyString(), eq(true)); configControllerV2.getConfig(request, response, TEST_DATA_ID, TEST_GROUP, TEST_NAMESPACE_ID, TEST_TAG); - verify(inner).doGetConfig(eq(request), eq(response), eq(TEST_DATA_ID), eq(TEST_GROUP), eq(TEST_NAMESPACE_ID), - eq(TEST_TAG), eq(null), anyString(), eq(true)); + verify(inner).doGetConfig(eq(request), eq(response), eq(TEST_DATA_ID), eq(TEST_GROUP), eq(TEST_NAMESPACE_ID), eq(TEST_TAG), + eq(null), anyString(), eq(true)); JsonNode resNode = JacksonUtils.toObj(response.getContentAsString()); Integer errCode = JacksonUtils.toObj(resNode.get("code").toString(), Integer.class); String actContent = JacksonUtils.toObj(resNode.get("data").toString(), String.class); @@ -141,7 +145,7 @@ public void testGetConfig() throws Exception { } @Test - public void testPublishConfig() throws Exception { + void testPublishConfig() throws Exception { ConfigForm configForm = new ConfigForm(); configForm.setDataId(TEST_DATA_ID); @@ -150,19 +154,40 @@ public void testPublishConfig() throws Exception { configForm.setContent(TEST_CONTENT); MockHttpServletRequest request = new MockHttpServletRequest(); + when(configOperationService.publishConfig(any(ConfigForm.class), any(ConfigRequestInfo.class), anyString())).thenReturn(true); + + Result booleanResult = configControllerV2.publishConfig(configForm, request); + + verify(configOperationService).publishConfig(any(ConfigForm.class), any(ConfigRequestInfo.class), anyString()); + + assertEquals(ErrorCode.SUCCESS.getCode(), booleanResult.getCode()); + assertTrue(booleanResult.getData()); + } + + @Test + void testPublishConfigWithEncryptedDataKey() throws Exception { + + ConfigForm configForm = new ConfigForm(); + configForm.setDataId(TEST_DATA_ID); + configForm.setGroup(TEST_GROUP); + configForm.setNamespaceId(TEST_NAMESPACE_ID); + configForm.setContent(TEST_CONTENT); + configForm.setEncryptedDataKey(TEST_ENCRYPTED_DATA_KEY); + MockHttpServletRequest request = new MockHttpServletRequest(); + when(configOperationService.publishConfig(any(ConfigForm.class), any(ConfigRequestInfo.class), - anyString())).thenReturn(true); + eq(TEST_ENCRYPTED_DATA_KEY))).thenReturn(true); Result booleanResult = configControllerV2.publishConfig(configForm, request); verify(configOperationService).publishConfig(any(ConfigForm.class), any(ConfigRequestInfo.class), anyString()); assertEquals(ErrorCode.SUCCESS.getCode(), booleanResult.getCode()); - assertEquals(true, booleanResult.getData()); + assertTrue(booleanResult.getData()); } @Test - public void testPublishConfigWhenNameSpaceIsPublic() throws Exception { + void testPublishConfigWhenNameSpaceIsPublic() throws Exception { ConfigForm configForm = new ConfigForm(); configForm.setDataId(TEST_DATA_ID); @@ -171,8 +196,8 @@ public void testPublishConfigWhenNameSpaceIsPublic() throws Exception { configForm.setContent(TEST_CONTENT); MockHttpServletRequest request = new MockHttpServletRequest(); - when(configOperationService.publishConfig(any(ConfigForm.class), any(ConfigRequestInfo.class), - anyString())).thenAnswer((Answer) invocation -> { + when(configOperationService.publishConfig(any(ConfigForm.class), any(ConfigRequestInfo.class), anyString())).thenAnswer( + (Answer) invocation -> { if (invocation.getArgument(0, ConfigForm.class).getNamespaceId().equals(TEST_NAMESPACE_ID)) { return true; } @@ -184,46 +209,43 @@ public void testPublishConfigWhenNameSpaceIsPublic() throws Exception { verify(configOperationService).publishConfig(any(ConfigForm.class), any(ConfigRequestInfo.class), anyString()); assertEquals(ErrorCode.SUCCESS.getCode(), booleanResult.getCode()); - assertEquals(true, booleanResult.getData()); + assertTrue(booleanResult.getData()); } @Test - public void testDeleteConfigWhenNameSpaceIsPublic() throws Exception { + void testDeleteConfigWhenNameSpaceIsPublic() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); - when(configOperationService.deleteConfig(eq(TEST_DATA_ID), eq(TEST_GROUP), eq(TEST_NAMESPACE_ID), eq(TEST_TAG), - any(), any())).thenReturn(true); - Result booleanResult = configControllerV2.deleteConfig(request, TEST_DATA_ID, TEST_GROUP, - TEST_NAMESPACE_ID_PUBLIC, TEST_TAG); + when(configOperationService.deleteConfig(eq(TEST_DATA_ID), eq(TEST_GROUP), eq(TEST_NAMESPACE_ID), eq(TEST_TAG), any(), + any())).thenReturn(true); + Result booleanResult = configControllerV2.deleteConfig(request, TEST_DATA_ID, TEST_GROUP, TEST_NAMESPACE_ID_PUBLIC, + TEST_TAG); - verify(configOperationService).deleteConfig(eq(TEST_DATA_ID), eq(TEST_GROUP), eq(TEST_NAMESPACE_ID), - eq(TEST_TAG), any(), any()); + verify(configOperationService).deleteConfig(eq(TEST_DATA_ID), eq(TEST_GROUP), eq(TEST_NAMESPACE_ID), eq(TEST_TAG), any(), any()); assertEquals(ErrorCode.SUCCESS.getCode(), booleanResult.getCode()); - assertEquals(true, booleanResult.getData()); + assertTrue(booleanResult.getData()); } @Test - public void testDeleteConfig() throws Exception { + void testDeleteConfig() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); - when(configOperationService.deleteConfig(eq(TEST_DATA_ID), eq(TEST_GROUP), eq(TEST_NAMESPACE_ID), eq(TEST_TAG), - any(), any())).thenReturn(true); + when(configOperationService.deleteConfig(eq(TEST_DATA_ID), eq(TEST_GROUP), eq(TEST_NAMESPACE_ID), eq(TEST_TAG), any(), + any())).thenReturn(true); - Result booleanResult = configControllerV2.deleteConfig(request, TEST_DATA_ID, TEST_GROUP, - TEST_NAMESPACE_ID, TEST_TAG); + Result booleanResult = configControllerV2.deleteConfig(request, TEST_DATA_ID, TEST_GROUP, TEST_NAMESPACE_ID, TEST_TAG); - verify(configOperationService).deleteConfig(eq(TEST_DATA_ID), eq(TEST_GROUP), eq(TEST_NAMESPACE_ID), - eq(TEST_TAG), any(), any()); + verify(configOperationService).deleteConfig(eq(TEST_DATA_ID), eq(TEST_GROUP), eq(TEST_NAMESPACE_ID), eq(TEST_TAG), any(), any()); assertEquals(ErrorCode.SUCCESS.getCode(), booleanResult.getCode()); - assertEquals(true, booleanResult.getData()); + assertTrue(booleanResult.getData()); } @Test - public void testGetConfigByDetail() throws Exception { + void testGetConfigByDetail() throws Exception { List configInfoList = new ArrayList<>(); ConfigInfo configInfo = new ConfigInfo("test", "test", "test"); configInfoList.add(configInfo); @@ -236,13 +258,11 @@ public void testGetConfigByDetail() throws Exception { Map configAdvanceInfo = new HashMap<>(8); configAdvanceInfo.put("content", "server.port"); - when(configInfoPersistService.findConfigInfo4Page(1, 10, "test", "test", "", configAdvanceInfo)) - .thenReturn(page); + when(configInfoPersistService.findConfigInfo4Page(1, 10, "test", "test", "", configAdvanceInfo)).thenReturn(page); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.CONFIG_CONTROLLER_V2_PATH + "/searchDetail") - .param("search", "accurate").param("dataId", "test").param("group", "test") - .param("appName", "").param("tenant", "").param("config_tags", "") - .param("pageNo", "1").param("pageSize", "10").param("config_detail", "server.port"); + .param("search", "accurate").param("dataId", "test").param("group", "test").param("appName", "").param("tenant", "") + .param("config_tags", "").param("pageNo", "1").param("pageSize", "10").param("config_detail", "server.port"); MockHttpServletResponse response = mockmvc.perform(builder).andReturn().getResponse(); String actualValue = response.getContentAsString(); @@ -250,14 +270,14 @@ public void testGetConfigByDetail() throws Exception { List resultList = JacksonUtils.toObj(pageItemsNode.toString(), List.class); ConfigInfo resConfigInfo = JacksonUtils.toObj(pageItemsNode.get(0).toString(), ConfigInfo.class); - Assert.assertEquals(configInfoList.size(), resultList.size()); - Assert.assertEquals(configInfo.getDataId(), resConfigInfo.getDataId()); - Assert.assertEquals(configInfo.getGroup(), resConfigInfo.getGroup()); - Assert.assertEquals(configInfo.getContent(), resConfigInfo.getContent()); + assertEquals(configInfoList.size(), resultList.size()); + assertEquals(configInfo.getDataId(), resConfigInfo.getDataId()); + assertEquals(configInfo.getGroup(), resConfigInfo.getGroup()); + assertEquals(configInfo.getContent(), resConfigInfo.getContent()); } @Test - public void testGetConfigFuzzyByDetail() throws Exception { + void testGetConfigFuzzyByDetail() throws Exception { List configInfoList = new ArrayList<>(); ConfigInfo configInfo = new ConfigInfo("test", "test", "test"); configInfoList.add(configInfo); @@ -270,13 +290,11 @@ public void testGetConfigFuzzyByDetail() throws Exception { Map configAdvanceInfo = new HashMap<>(8); configAdvanceInfo.put("content", "server.port"); - when(configInfoPersistService.findConfigInfoLike4Page(1, 10, "test", "test", "", configAdvanceInfo)) - .thenReturn(page); + when(configInfoPersistService.findConfigInfoLike4Page(1, 10, "test", "test", "", configAdvanceInfo)).thenReturn(page); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.CONFIG_CONTROLLER_V2_PATH + "/searchDetail") - .param("search", "blur").param("dataId", "test").param("group", "test") - .param("appName", "").param("tenant", "").param("config_tags", "") - .param("pageNo", "1").param("pageSize", "10").param("config_detail", "server.port"); + .param("search", "blur").param("dataId", "test").param("group", "test").param("appName", "").param("tenant", "") + .param("config_tags", "").param("pageNo", "1").param("pageSize", "10").param("config_detail", "server.port"); MockHttpServletResponse response = mockmvc.perform(builder).andReturn().getResponse(); String actualValue = response.getContentAsString(); @@ -284,23 +302,22 @@ public void testGetConfigFuzzyByDetail() throws Exception { List resultList = JacksonUtils.toObj(pageItemsNode.toString(), List.class); ConfigInfo resConfigInfo = JacksonUtils.toObj(pageItemsNode.get(0).toString(), ConfigInfo.class); - Assert.assertEquals(configInfoList.size(), resultList.size()); - Assert.assertEquals(configInfo.getDataId(), resConfigInfo.getDataId()); - Assert.assertEquals(configInfo.getGroup(), resConfigInfo.getGroup()); - Assert.assertEquals(configInfo.getContent(), resConfigInfo.getContent()); + assertEquals(configInfoList.size(), resultList.size()); + assertEquals(configInfo.getDataId(), resConfigInfo.getDataId()); + assertEquals(configInfo.getGroup(), resConfigInfo.getGroup()); + assertEquals(configInfo.getContent(), resConfigInfo.getContent()); } @Test - public void testGetConfigAuthFilter() throws Exception { + void testGetConfigAuthFilter() throws Exception { when(authConfigs.isAuthEnabled()).thenReturn(true); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.CONFIG_CONTROLLER_V2_PATH + "/searchDetail") - .param("search", "accurate").param("dataId", "test").param("group", "test") - .param("appName", "").param("tenant", "").param("config_tags", "") - .param("pageNo", "1").param("pageSize", "10").param("config_detail", "server.port"); + .param("search", "accurate").param("dataId", "test").param("group", "test").param("appName", "").param("tenant", "") + .param("config_tags", "").param("pageNo", "1").param("pageSize", "10").param("config_detail", "server.port"); MockHttpServletResponse response = mockmvc.perform(builder).andReturn().getResponse(); - assertEquals(response.getStatus(), HttpServletResponse.SC_FORBIDDEN); + assertEquals(HttpServletResponse.SC_FORBIDDEN, response.getStatus()); assertEquals(response.getErrorMessage(), "Invalid server identity key or value, Please make sure set `nacos.core.auth.server.identity.key`" + " and `nacos.core.auth.server.identity.value`, or open `nacos.core.auth.enable.userAgentAuthWhite`"); diff --git a/config/src/test/java/com/alibaba/nacos/config/server/controller/v2/HistoryControllerV2Test.java b/config/src/test/java/com/alibaba/nacos/config/server/controller/v2/HistoryControllerV2Test.java index 8fb7bfd16c7..df6c0613594 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/controller/v2/HistoryControllerV2Test.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/controller/v2/HistoryControllerV2Test.java @@ -21,13 +21,13 @@ import com.alibaba.nacos.api.model.v2.Result; import com.alibaba.nacos.config.server.model.ConfigHistoryInfo; import com.alibaba.nacos.config.server.model.ConfigInfoWrapper; -import com.alibaba.nacos.persistence.model.Page; import com.alibaba.nacos.config.server.service.HistoryService; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import com.alibaba.nacos.persistence.model.Page; +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.sql.Timestamp; import java.util.ArrayList; @@ -35,7 +35,7 @@ import java.util.Date; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -46,13 +46,8 @@ * @date 2022/7/25 */ -@RunWith(MockitoJUnitRunner.class) -public class HistoryControllerV2Test { - - HistoryControllerV2 historyControllerV2; - - @Mock - private HistoryService historyService; +@ExtendWith(MockitoExtension.class) +class HistoryControllerV2Test { private static final String TEST_DATA_ID = "test"; @@ -64,13 +59,18 @@ public class HistoryControllerV2Test { private static final String TEST_CONTENT = "test config"; - @Before - public void setUp() { + HistoryControllerV2 historyControllerV2; + + @Mock + private HistoryService historyService; + + @BeforeEach + void setUp() { historyControllerV2 = new HistoryControllerV2(historyService); } @Test - public void testListConfigHistory() throws Exception { + void testListConfigHistory() throws Exception { ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo(); configHistoryInfo.setDataId(TEST_DATA_ID); @@ -89,8 +89,8 @@ public void testListConfigHistory() throws Exception { when(historyService.listConfigHistory(TEST_DATA_ID, TEST_GROUP, TEST_NAMESPACE_ID, 1, 10)).thenReturn(page); - Result> pageResult = historyControllerV2.listConfigHistory(TEST_DATA_ID, TEST_GROUP, - TEST_NAMESPACE_ID, 1, 10); + Result> pageResult = historyControllerV2.listConfigHistory(TEST_DATA_ID, TEST_GROUP, TEST_NAMESPACE_ID, 1, + 10); verify(historyService).listConfigHistory(TEST_DATA_ID, TEST_GROUP, TEST_NAMESPACE_ID, 1, 10); @@ -106,7 +106,7 @@ public void testListConfigHistory() throws Exception { } @Test - public void testListConfigHistoryWhenNameSpaceIsPublic() throws Exception { + void testListConfigHistoryWhenNameSpaceIsPublic() throws Exception { ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo(); configHistoryInfo.setDataId(TEST_DATA_ID); @@ -142,7 +142,7 @@ public void testListConfigHistoryWhenNameSpaceIsPublic() throws Exception { } @Test - public void testGetConfigHistoryInfoWhenNameSpaceIsPublic() throws Exception { + void testGetConfigHistoryInfoWhenNameSpaceIsPublic() throws Exception { ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo(); configHistoryInfo.setDataId(TEST_DATA_ID); @@ -152,11 +152,9 @@ public void testGetConfigHistoryInfoWhenNameSpaceIsPublic() throws Exception { configHistoryInfo.setCreatedTime(new Timestamp(new Date().getTime())); configHistoryInfo.setLastModifiedTime(new Timestamp(new Date().getTime())); - when(historyService.getConfigHistoryInfo(TEST_DATA_ID, TEST_GROUP, TEST_NAMESPACE_ID, 1L)).thenReturn( - configHistoryInfo); + when(historyService.getConfigHistoryInfo(TEST_DATA_ID, TEST_GROUP, TEST_NAMESPACE_ID, 1L)).thenReturn(configHistoryInfo); - Result result = historyControllerV2.getConfigHistoryInfo(TEST_DATA_ID, TEST_GROUP, - TEST_NAMESPACE_ID_PUBLIC, 1L); + Result result = historyControllerV2.getConfigHistoryInfo(TEST_DATA_ID, TEST_GROUP, TEST_NAMESPACE_ID_PUBLIC, 1L); verify(historyService).getConfigHistoryInfo(TEST_DATA_ID, TEST_GROUP, TEST_NAMESPACE_ID, 1L); @@ -170,7 +168,7 @@ public void testGetConfigHistoryInfoWhenNameSpaceIsPublic() throws Exception { } @Test - public void testGetConfigHistoryInfo() throws Exception { + void testGetConfigHistoryInfo() throws Exception { ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo(); configHistoryInfo.setDataId(TEST_DATA_ID); @@ -180,11 +178,9 @@ public void testGetConfigHistoryInfo() throws Exception { configHistoryInfo.setCreatedTime(new Timestamp(new Date().getTime())); configHistoryInfo.setLastModifiedTime(new Timestamp(new Date().getTime())); - when(historyService.getConfigHistoryInfo(TEST_DATA_ID, TEST_GROUP, TEST_NAMESPACE_ID, 1L)).thenReturn( - configHistoryInfo); + when(historyService.getConfigHistoryInfo(TEST_DATA_ID, TEST_GROUP, TEST_NAMESPACE_ID, 1L)).thenReturn(configHistoryInfo); - Result result = historyControllerV2.getConfigHistoryInfo(TEST_DATA_ID, TEST_GROUP, - TEST_NAMESPACE_ID, 1L); + Result result = historyControllerV2.getConfigHistoryInfo(TEST_DATA_ID, TEST_GROUP, TEST_NAMESPACE_ID, 1L); verify(historyService).getConfigHistoryInfo(TEST_DATA_ID, TEST_GROUP, TEST_NAMESPACE_ID, 1L); @@ -198,7 +194,7 @@ public void testGetConfigHistoryInfo() throws Exception { } @Test - public void testGetPreviousConfigHistoryInfo() throws Exception { + void testGetPreviousConfigHistoryInfo() throws Exception { ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo(); configHistoryInfo.setDataId(TEST_DATA_ID); @@ -208,11 +204,10 @@ public void testGetPreviousConfigHistoryInfo() throws Exception { configHistoryInfo.setCreatedTime(new Timestamp(new Date().getTime())); configHistoryInfo.setLastModifiedTime(new Timestamp(new Date().getTime())); - when(historyService.getPreviousConfigHistoryInfo(TEST_DATA_ID, TEST_GROUP, TEST_NAMESPACE_ID, 1L)).thenReturn( - configHistoryInfo); + when(historyService.getPreviousConfigHistoryInfo(TEST_DATA_ID, TEST_GROUP, TEST_NAMESPACE_ID, 1L)).thenReturn(configHistoryInfo); - Result result = historyControllerV2.getPreviousConfigHistoryInfo(TEST_DATA_ID, TEST_GROUP, - TEST_NAMESPACE_ID, 1L); + Result result = historyControllerV2.getPreviousConfigHistoryInfo(TEST_DATA_ID, TEST_GROUP, TEST_NAMESPACE_ID, + 1L); verify(historyService).getPreviousConfigHistoryInfo(TEST_DATA_ID, TEST_GROUP, TEST_NAMESPACE_ID, 1L); @@ -226,7 +221,7 @@ public void testGetPreviousConfigHistoryInfo() throws Exception { } @Test - public void testGetPreviousConfigHistoryInfoWhenNameSpaceIsPublic() throws Exception { + void testGetPreviousConfigHistoryInfoWhenNameSpaceIsPublic() throws Exception { ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo(); configHistoryInfo.setDataId(TEST_DATA_ID); @@ -236,8 +231,7 @@ public void testGetPreviousConfigHistoryInfoWhenNameSpaceIsPublic() throws Excep configHistoryInfo.setCreatedTime(new Timestamp(new Date().getTime())); configHistoryInfo.setLastModifiedTime(new Timestamp(new Date().getTime())); - when(historyService.getPreviousConfigHistoryInfo(TEST_DATA_ID, TEST_GROUP, TEST_NAMESPACE_ID, 1L)).thenReturn( - configHistoryInfo); + when(historyService.getPreviousConfigHistoryInfo(TEST_DATA_ID, TEST_GROUP, TEST_NAMESPACE_ID, 1L)).thenReturn(configHistoryInfo); Result result = historyControllerV2.getPreviousConfigHistoryInfo(TEST_DATA_ID, TEST_GROUP, TEST_NAMESPACE_ID_PUBLIC, 1L); @@ -254,7 +248,7 @@ public void testGetPreviousConfigHistoryInfoWhenNameSpaceIsPublic() throws Excep } @Test - public void testGetConfigListByNamespace() throws NacosApiException { + void testGetConfigListByNamespace() throws NacosApiException { ConfigInfoWrapper configInfoWrapper = new ConfigInfoWrapper(); configInfoWrapper.setDataId("test"); configInfoWrapper.setGroup("test"); @@ -275,7 +269,7 @@ public void testGetConfigListByNamespace() throws NacosApiException { } @Test - public void testGetConfigListByNamespaceWhenIsPublic() throws NacosApiException { + void testGetConfigListByNamespaceWhenIsPublic() throws NacosApiException { ConfigInfoWrapper configInfoWrapper = new ConfigInfoWrapper(); configInfoWrapper.setDataId("test"); configInfoWrapper.setGroup("test"); diff --git a/config/src/test/java/com/alibaba/nacos/config/server/exception/GlobalExceptionHandlerTest.java b/config/src/test/java/com/alibaba/nacos/config/server/exception/GlobalExceptionHandlerTest.java index 969f60e1a37..34e193a0627 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/exception/GlobalExceptionHandlerTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/exception/GlobalExceptionHandlerTest.java @@ -19,13 +19,11 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; import com.alibaba.nacos.config.server.controller.v2.HistoryControllerV2; -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.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; @@ -35,41 +33,39 @@ import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -@RunWith(SpringRunner.class) @WebMvcTest(GlobalExceptionHandlerTest.class) -public class GlobalExceptionHandlerTest { +class GlobalExceptionHandlerTest { + private MockMvc mockMvc; - + @Autowired private WebApplicationContext context; - + @MockBean private HistoryControllerV2 historyControllerV2; - - @Before - public void before() { + + @BeforeEach + void before() { mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); } - + @Test - public void testNacosRunTimeExceptionHandler() throws Exception { + void testNacosRunTimeExceptionHandler() throws Exception { // 设置HistoryControllerV2的行为,使其抛出NacosRuntimeException并被GlobalExceptionHandler捕获处理 - when(historyControllerV2.getConfigsByTenant("test")) - .thenThrow(new NacosRuntimeException(NacosException.INVALID_PARAM)) - .thenThrow(new NacosRuntimeException(NacosException.SERVER_ERROR)) - .thenThrow(new NacosRuntimeException(503)); - + when(historyControllerV2.getConfigsByTenant("test")).thenThrow(new NacosRuntimeException(NacosException.INVALID_PARAM)) + .thenThrow(new NacosRuntimeException(NacosException.SERVER_ERROR)).thenThrow(new NacosRuntimeException(503)); + // 执行请求并验证响应码 ResultActions resultActions = mockMvc.perform(get("/v2/cs/history/configs").param("namespaceId", "test")); resultActions.andExpect(MockMvcResultMatchers.status().is(NacosException.INVALID_PARAM)); - + // 执行请求并验证响应码 ResultActions resultActions1 = mockMvc.perform(get("/v2/cs/history/configs").param("namespaceId", "test")); resultActions1.andExpect(MockMvcResultMatchers.status().is(NacosException.SERVER_ERROR)); - + // 执行请求并验证响应码 ResultActions resultActions2 = mockMvc.perform(get("/v2/cs/history/configs").param("namespaceId", "test")); resultActions2.andExpect(MockMvcResultMatchers.status().is(503)); } - -} \ No newline at end of file + +} diff --git a/config/src/test/java/com/alibaba/nacos/config/server/manager/TaskManagerTest.java b/config/src/test/java/com/alibaba/nacos/config/server/manager/TaskManagerTest.java index 7cd1000946b..20b78c35b83 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/manager/TaskManagerTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/manager/TaskManagerTest.java @@ -19,28 +19,28 @@ import com.alibaba.nacos.common.task.AbstractDelayTask; import com.alibaba.nacos.common.task.NacosTaskProcessor; import com.alibaba.nacos.config.server.constant.Constants; -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.internal.verification.Times; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import javax.management.ObjectName; import java.lang.management.ManagementFactory; import java.util.Date; import java.util.concurrent.TimeUnit; -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; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class TaskManagerTest { +@ExtendWith(MockitoExtension.class) +class TaskManagerTest { private TaskManager taskManager; @@ -52,8 +52,8 @@ public class TaskManagerTest { private AbstractDelayTask abstractTask; - @Before - public void setUp() { + @BeforeEach + void setUp() { taskManager = new TaskManager(TaskManagerTest.class.getName()); taskManager.setDefaultTaskProcessor(taskProcessor); abstractTask = new AbstractDelayTask() { @@ -63,13 +63,13 @@ public void merge(AbstractDelayTask task) { }; } - @After - public void tearDown() { + @AfterEach + void tearDown() { taskManager.close(); } @Test - public void testSize() { + void testSize() { assertEquals(0, taskManager.size()); taskManager.addTask("test", abstractTask); assertEquals(1, taskManager.size()); @@ -78,7 +78,7 @@ public void testSize() { } @Test - public void testIsEmpty() { + void testIsEmpty() { assertTrue(taskManager.isEmpty()); taskManager.addTask("test", abstractTask); assertFalse(taskManager.isEmpty()); @@ -87,7 +87,7 @@ public void testIsEmpty() { } @Test - public void testAddProcessor() throws InterruptedException { + void testAddProcessor() throws InterruptedException { when(testTaskProcessor.process(abstractTask)).thenReturn(true); taskManager.addProcessor("test", testTaskProcessor); taskManager.addTask("test", abstractTask); @@ -97,7 +97,7 @@ public void testAddProcessor() throws InterruptedException { } @Test - public void testRemoveProcessor() throws InterruptedException { + void testRemoveProcessor() throws InterruptedException { when(taskProcessor.process(abstractTask)).thenReturn(true); taskManager.addProcessor("test", testTaskProcessor); taskManager.removeProcessor("test"); @@ -108,7 +108,7 @@ public void testRemoveProcessor() throws InterruptedException { } @Test - public void testRetryTaskAfterFail() throws InterruptedException { + void testRetryTaskAfterFail() throws InterruptedException { when(taskProcessor.process(abstractTask)).thenReturn(false, true); taskManager.addTask("test", abstractTask); TimeUnit.MILLISECONDS.sleep(300); @@ -116,7 +116,7 @@ public void testRetryTaskAfterFail() throws InterruptedException { } @Test - public void testGetTaskInfos() throws InterruptedException { + void testGetTaskInfos() throws InterruptedException { taskManager.addProcessor("test", testTaskProcessor); when(testTaskProcessor.process(abstractTask)).thenReturn(true); taskManager.addTask("test", abstractTask); @@ -126,10 +126,9 @@ public void testGetTaskInfos() throws InterruptedException { } @Test - public void testInit() throws Exception { + void testInit() throws Exception { taskManager.init(); - ObjectName oName = new ObjectName( - TaskManagerTest.class.getName() + ":type=" + TaskManager.class.getSimpleName()); + ObjectName oName = new ObjectName(TaskManagerTest.class.getName() + ":type=" + TaskManager.class.getSimpleName()); assertTrue(ManagementFactory.getPlatformMBeanServer().isRegistered(oName)); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/model/ConfigInfoTest.java b/config/src/test/java/com/alibaba/nacos/config/server/model/ConfigInfoTest.java index ae9efb9297a..686747463b1 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/model/ConfigInfoTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/model/ConfigInfoTest.java @@ -20,14 +20,15 @@ import com.alibaba.nacos.consistency.IdGenerator; import com.alibaba.nacos.core.distributed.id.SnowFlowerIdGenerator; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.env.StandardEnvironment; -public class ConfigInfoTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ConfigInfoTest { @Test - public void testPrecisionIssue() throws Exception { + void testPrecisionIssue() throws Exception { EnvUtil.setEnvironment(new StandardEnvironment()); IdGenerator generator = new SnowFlowerIdGenerator(); long expected = generator.nextId(); @@ -35,7 +36,7 @@ public void testPrecisionIssue() throws Exception { configInfo.setId(expected); String json = JacksonUtils.toJson(configInfo); ConfigInfo actual = JacksonUtils.toObj(json, ConfigInfo.class); - Assert.assertEquals(expected, actual.getId()); + assertEquals(expected, actual.getId()); } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/paramcheck/ConfigListenerHttpParamExtractorTest.java b/config/src/test/java/com/alibaba/nacos/config/server/paramcheck/ConfigListenerHttpParamExtractorTest.java index 4576cbdeb63..b97e40989b7 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/paramcheck/ConfigListenerHttpParamExtractorTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/paramcheck/ConfigListenerHttpParamExtractorTest.java @@ -18,12 +18,11 @@ import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.config.server.model.ConfigInfo; -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.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import javax.servlet.http.HttpServletRequest; import java.util.Arrays; @@ -31,11 +30,11 @@ import static com.alibaba.nacos.api.common.Constants.LINE_SEPARATOR; import static com.alibaba.nacos.api.common.Constants.WORD_SEPARATOR; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.eq; -@RunWith(MockitoJUnitRunner.class) - -public class ConfigListenerHttpParamExtractorTest { +@ExtendWith(MockitoExtension.class) +class ConfigListenerHttpParamExtractorTest { ConfigListenerHttpParamExtractor configListenerHttpParamExtractor; @@ -43,7 +42,7 @@ public class ConfigListenerHttpParamExtractorTest { HttpServletRequest httpServletRequest; @Test - public void testNormal() { + void testNormal() { String listenerConfigsString = getListenerConfigsString(); Mockito.when(httpServletRequest.getParameter(eq("Listening-Configs"))).thenReturn(listenerConfigsString); configListenerHttpParamExtractor = new ConfigListenerHttpParamExtractor(); @@ -51,16 +50,16 @@ public void testNormal() { } @Test - public void testError() { + void testError() { String listenerConfigsString = getErrorListenerConfigsString(); Mockito.when(httpServletRequest.getParameter(eq("Listening-Configs"))).thenReturn(listenerConfigsString); configListenerHttpParamExtractor = new ConfigListenerHttpParamExtractor(); try { configListenerHttpParamExtractor.extractParam(httpServletRequest); - Assert.assertTrue(false); + assertTrue(false); } catch (Throwable throwable) { throwable.printStackTrace(); - Assert.assertTrue(throwable instanceof IllegalArgumentException); + assertTrue(throwable instanceof IllegalArgumentException); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/paramcheck/ParamExtractorTest.java b/config/src/test/java/com/alibaba/nacos/config/server/paramcheck/ParamExtractorTest.java index dbed43d1522..bfb157b4fd9 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/paramcheck/ParamExtractorTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/paramcheck/ParamExtractorTest.java @@ -22,13 +22,13 @@ import com.alibaba.nacos.core.paramcheck.ExtractorManager; import com.alibaba.nacos.core.paramcheck.ParamCheckerFilter; import com.alibaba.nacos.sys.env.EnvUtil; -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.MockedStatic; import org.mockito.Mockito; import org.mockito.internal.verification.Times; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; @@ -36,7 +36,7 @@ import javax.servlet.http.HttpServletResponse; import java.lang.reflect.Method; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Param Config ExtractorTest. @@ -44,8 +44,8 @@ * @author 985492783@qq.com * @date 2023/11/9 16:04 */ -@RunWith(MockitoJUnitRunner.class) -public class ParamExtractorTest { +@ExtendWith(MockitoExtension.class) +class ParamExtractorTest { @Mock private ControllerMethodsCache methodsCache; @@ -53,16 +53,15 @@ public class ParamExtractorTest { private ParamCheckerFilter filter; @Test - public void testBlurFilter() throws Exception { + void testBlurFilter() throws Exception { MockedStatic mockedStatic = Mockito.mockStatic(EnvUtil.class); - final Method check = ConfigController.class.getMethod("fuzzySearchConfig", String.class, String.class, String.class, + final Method check = ConfigController.class.getMethod("fuzzySearchConfig", String.class, String.class, String.class, String.class, String.class, String.class, int.class, int.class); ExtractorManager.Extractor annotation = check.getAnnotation(ExtractorManager.Extractor.class); AbstractHttpParamExtractor httpExtractor = Mockito.spy(ExtractorManager.getHttpExtractor(annotation)); MockedStatic managerMockedStatic = Mockito.mockStatic(ExtractorManager.class); - mockedStatic.when(() -> EnvUtil.getProperty(Mockito.any(), Mockito.any(), Mockito.any())) - .thenAnswer((k) -> k.getArgument(2)); + mockedStatic.when(() -> EnvUtil.getProperty(Mockito.any(), Mockito.any(), Mockito.any())).thenAnswer((k) -> k.getArgument(2)); filter = new ParamCheckerFilter(methodsCache); managerMockedStatic.when(() -> ExtractorManager.getHttpExtractor(annotation)).thenReturn(httpExtractor); @@ -74,30 +73,28 @@ public void testBlurFilter() throws Exception { filter.doFilter(request, response, (servletRequest, servletResponse) -> { }); - assertEquals(response.getStatus(), 400); + assertEquals(400, response.getStatus()); response = new MockHttpServletResponse(); request.addParameter("search", "blur"); filter.doFilter(request, response, (servletRequest, servletResponse) -> { }); - assertEquals(response.getStatus(), 200); - assertEquals(httpExtractor.getClass(), ConfigBlurSearchHttpParamExtractor.class); + assertEquals(200, response.getStatus()); + assertEquals(ConfigBlurSearchHttpParamExtractor.class, httpExtractor.getClass()); Mockito.verify(httpExtractor, new Times(2)).extractParam(Mockito.any()); managerMockedStatic.close(); mockedStatic.close(); } @Test - public void testListenerFilter() throws Exception { + void testListenerFilter() throws Exception { MockedStatic mockedStatic = Mockito.mockStatic(EnvUtil.class); - final Method check = ConfigController.class.getMethod("listener", HttpServletRequest.class, - HttpServletResponse.class); + final Method check = ConfigController.class.getMethod("listener", HttpServletRequest.class, HttpServletResponse.class); ExtractorManager.Extractor annotation = check.getAnnotation(ExtractorManager.Extractor.class); AbstractHttpParamExtractor httpExtractor = Mockito.spy(ExtractorManager.getHttpExtractor(annotation)); MockedStatic managerMockedStatic = Mockito.mockStatic(ExtractorManager.class); - mockedStatic.when(() -> EnvUtil.getProperty(Mockito.any(), Mockito.any(), Mockito.any())) - .thenAnswer((k) -> k.getArgument(2)); + mockedStatic.when(() -> EnvUtil.getProperty(Mockito.any(), Mockito.any(), Mockito.any())).thenAnswer((k) -> k.getArgument(2)); filter = new ParamCheckerFilter(methodsCache); managerMockedStatic.when(() -> ExtractorManager.getHttpExtractor(annotation)).thenReturn(httpExtractor); @@ -108,23 +105,21 @@ public void testListenerFilter() throws Exception { filter.doFilter(request, response, (servletRequest, servletResponse) -> { }); - assertEquals(httpExtractor.getClass(), ConfigListenerHttpParamExtractor.class); + assertEquals(ConfigListenerHttpParamExtractor.class, httpExtractor.getClass()); Mockito.verify(httpExtractor, new Times(1)).extractParam(Mockito.any()); managerMockedStatic.close(); mockedStatic.close(); } @Test - public void testDefaultFilter() throws Exception { + void testDefaultFilter() throws Exception { MockedStatic mockedStatic = Mockito.mockStatic(EnvUtil.class); - final Method check = ConfigController.class.getMethod("getConfigAdvanceInfo", String.class, String.class, - String.class); + final Method check = ConfigController.class.getMethod("getConfigAdvanceInfo", String.class, String.class, String.class); ExtractorManager.Extractor annotation = ConfigController.class.getAnnotation(ExtractorManager.Extractor.class); AbstractHttpParamExtractor httpExtractor = Mockito.spy(ExtractorManager.getHttpExtractor(annotation)); MockedStatic managerMockedStatic = Mockito.mockStatic(ExtractorManager.class); - mockedStatic.when(() -> EnvUtil.getProperty(Mockito.any(), Mockito.any(), Mockito.any())) - .thenAnswer((k) -> k.getArgument(2)); + mockedStatic.when(() -> EnvUtil.getProperty(Mockito.any(), Mockito.any(), Mockito.any())).thenAnswer((k) -> k.getArgument(2)); filter = new ParamCheckerFilter(methodsCache); managerMockedStatic.when(() -> ExtractorManager.getHttpExtractor(annotation)).thenReturn(httpExtractor); @@ -135,7 +130,7 @@ public void testDefaultFilter() throws Exception { filter.doFilter(request, response, (servletRequest, servletResponse) -> { }); - assertEquals(httpExtractor.getClass(), ConfigDefaultHttpParamExtractor.class); + assertEquals(ConfigDefaultHttpParamExtractor.class, httpExtractor.getClass()); Mockito.verify(httpExtractor, new Times(1)).extractParam(Mockito.any()); managerMockedStatic.close(); mockedStatic.close(); diff --git a/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigChangeBatchListenRequestHandlerTest.java b/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigChangeBatchListenRequestHandlerTest.java index af522752cd3..84b627748f4 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigChangeBatchListenRequestHandlerTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigChangeBatchListenRequestHandlerTest.java @@ -23,39 +23,39 @@ import com.alibaba.nacos.config.server.service.ConfigCacheService; import com.alibaba.nacos.config.server.utils.GroupKey2; import com.alibaba.nacos.core.utils.StringPool; -import junit.framework.TestCase; -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.InjectMocks; import org.mockito.MockedStatic; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.util.ReflectionTestUtils; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.eq; -@RunWith(MockitoJUnitRunner.class) -public class ConfigChangeBatchListenRequestHandlerTest extends TestCase { - +@ExtendWith(MockitoExtension.class) +class ConfigChangeBatchListenRequestHandlerTest { + @InjectMocks private ConfigChangeBatchListenRequestHandler configQueryRequestHandler; - + @InjectMocks private ConfigChangeListenContext configChangeListenContext; - + private RequestMeta requestMeta; - - @Before - public void setUp() { + + @BeforeEach + void setUp() { configQueryRequestHandler = new ConfigChangeBatchListenRequestHandler(); ReflectionTestUtils.setField(configQueryRequestHandler, "configChangeListenContext", configChangeListenContext); requestMeta = new RequestMeta(); requestMeta.setClientIp("1.1.1.1"); } - + @Test - public void testHandle() { + void testHandle() { MockedStatic configCacheServiceMockedStatic = Mockito.mockStatic(ConfigCacheService.class); String dataId = "dataId"; @@ -63,16 +63,15 @@ public void testHandle() { String tenant = "tenant"; String groupKey = GroupKey2.getKey(dataId, group, tenant); groupKey = StringPool.get(groupKey); - + final String groupKeyCopy = groupKey; configCacheServiceMockedStatic.when( - () -> ConfigCacheService.isUptodate(eq(groupKeyCopy), Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn(false); + () -> ConfigCacheService.isUptodate(eq(groupKeyCopy), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(false); ConfigBatchListenRequest configChangeListenRequest = new ConfigBatchListenRequest(); configChangeListenRequest.addConfigListenContext(group, dataId, tenant, " "); try { - ConfigChangeBatchListenResponse configChangeBatchListenResponse = configQueryRequestHandler - .handle(configChangeListenRequest, requestMeta); + ConfigChangeBatchListenResponse configChangeBatchListenResponse = configQueryRequestHandler.handle(configChangeListenRequest, + requestMeta); boolean hasChange = false; for (ConfigChangeBatchListenResponse.ConfigContext changedConfig : configChangeBatchListenResponse.getChangedConfigs()) { if (changedConfig.getDataId().equals(dataId)) { @@ -87,5 +86,5 @@ public void testHandle() { configCacheServiceMockedStatic.close(); } } - + } \ No newline at end of file diff --git a/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigChangeClusterSyncRequestHandlerTest.java b/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigChangeClusterSyncRequestHandlerTest.java index 248ea461243..81e7aad105d 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigChangeClusterSyncRequestHandlerTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigChangeClusterSyncRequestHandlerTest.java @@ -22,30 +22,31 @@ import com.alibaba.nacos.api.remote.request.RequestMeta; import com.alibaba.nacos.api.remote.response.ResponseCode; import com.alibaba.nacos.config.server.service.dump.DumpService; -import junit.framework.TestCase; -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.io.IOException; -@RunWith(MockitoJUnitRunner.class) -public class ConfigChangeClusterSyncRequestHandlerTest extends TestCase { +import static org.junit.jupiter.api.Assertions.assertEquals; +@ExtendWith(MockitoExtension.class) +class ConfigChangeClusterSyncRequestHandlerTest { + private ConfigChangeClusterSyncRequestHandler configChangeClusterSyncRequestHandler; - + @Mock private DumpService dumpService; - - @Before - public void setUp() throws IOException { + + @BeforeEach + void setUp() throws IOException { configChangeClusterSyncRequestHandler = new ConfigChangeClusterSyncRequestHandler(dumpService); } - + @Test - public void testHandle() throws NacosException { + void testHandle() throws NacosException { ConfigChangeClusterSyncRequest configChangeSyncRequest = new ConfigChangeClusterSyncRequest(); configChangeSyncRequest.setRequestId(""); configChangeSyncRequest.setDataId("dataId"); @@ -54,7 +55,8 @@ public void testHandle() throws NacosException { configChangeSyncRequest.setBeta(false); RequestMeta meta = new RequestMeta(); meta.setClientIp("1.1.1.1"); - ConfigChangeClusterSyncResponse configChangeClusterSyncResponse = configChangeClusterSyncRequestHandler.handle(configChangeSyncRequest, meta); + ConfigChangeClusterSyncResponse configChangeClusterSyncResponse = configChangeClusterSyncRequestHandler.handle( + configChangeSyncRequest, meta); assertEquals(configChangeClusterSyncResponse.getResultCode(), ResponseCode.SUCCESS.getCode()); } } \ No newline at end of file diff --git a/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigChangeListenContextTest.java b/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigChangeListenContextTest.java index 57e7ae8dac6..eaa3134bff0 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigChangeListenContextTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigChangeListenContextTest.java @@ -16,69 +16,72 @@ package com.alibaba.nacos.config.server.remote; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Map; import java.util.Set; -@RunWith(MockitoJUnitRunner.class) -public class ConfigChangeListenContextTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +@ExtendWith(MockitoExtension.class) +class ConfigChangeListenContextTest { + private ConfigChangeListenContext configChangeListenContext; - - @Before - public void setUp() throws Exception { + + @BeforeEach + void setUp() throws Exception { configChangeListenContext = new ConfigChangeListenContext(); } - + @Test - public void testAddListen() { + void testAddListen() { configChangeListenContext.addListen("groupKey", "md5", "connectionId"); Set groupKey = configChangeListenContext.getListeners("groupKey"); - Assert.assertEquals(1, groupKey.size()); + assertEquals(1, groupKey.size()); } - + @Test - public void testRemoveListen() { + void testRemoveListen() { configChangeListenContext.addListen("groupKey", "md5", "connectionId"); configChangeListenContext.removeListen("groupKey", "connectionId"); Set groupKey = configChangeListenContext.getListeners("groupKey"); - Assert.assertNull(groupKey); + assertNull(groupKey); } - + @Test - public void testGetListeners() { + void testGetListeners() { configChangeListenContext.addListen("groupKey", "md5", "connectionId"); Set groupKey = configChangeListenContext.getListeners("groupKey"); - Assert.assertEquals(1, groupKey.size()); + assertEquals(1, groupKey.size()); } - + @Test - public void testClearContextForConnectionId() { + void testClearContextForConnectionId() { configChangeListenContext.addListen("groupKey", "md5", "connectionId"); Map connectionIdBefore = configChangeListenContext.getListenKeys("connectionId"); - Assert.assertNotNull(connectionIdBefore); + assertNotNull(connectionIdBefore); configChangeListenContext.clearContextForConnectionId("connectionId"); Map connectionIdAfter = configChangeListenContext.getListenKeys("connectionId"); - Assert.assertNull(connectionIdAfter); + assertNull(connectionIdAfter); } - + @Test - public void testGetListenKeys() { + void testGetListenKeys() { configChangeListenContext.addListen("groupKey", "md5", "connectionId"); Set groupKey = configChangeListenContext.getListeners("groupKey"); - Assert.assertEquals(1, groupKey.size()); + assertEquals(1, groupKey.size()); } - + @Test - public void testGetListenKeyMd5() { + void testGetListenKeyMd5() { configChangeListenContext.addListen("groupKey", "md5", "connectionId"); String listenKeyMd5 = configChangeListenContext.getListenKeyMd5("connectionId", "groupKey"); - Assert.assertEquals("md5", listenKeyMd5); + assertEquals("md5", listenKeyMd5); } - + } \ No newline at end of file diff --git a/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigPublishRequestHandlerTest.java b/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigPublishRequestHandlerTest.java index 49be3c12172..d5ffb5c0a38 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigPublishRequestHandlerTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigPublishRequestHandlerTest.java @@ -35,29 +35,28 @@ import com.alibaba.nacos.config.server.service.repository.ConfigInfoTagPersistService; import com.alibaba.nacos.persistence.configuration.DatasourceConfiguration; import com.alibaba.nacos.sys.env.EnvUtil; - -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.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; +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.ArgumentMatchers.eq; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class ConfigPublishRequestHandlerTest { - - private ConfigPublishRequestHandler configPublishRequestHandler; +@ExtendWith(MockitoExtension.class) +class ConfigPublishRequestHandlerTest { @Mock ConfigInfoPersistService configInfoPersistService; @@ -72,19 +71,21 @@ public class ConfigPublishRequestHandlerTest { MockedStatic envUtilMockedStatic; - @Before - public void setUp() { + private ConfigPublishRequestHandler configPublishRequestHandler; + + @BeforeEach + void setUp() { aggrWhitelistMockedStatic = Mockito.mockStatic(AggrWhitelist.class); envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); - configPublishRequestHandler = new ConfigPublishRequestHandler(configInfoPersistService, - configInfoTagPersistService, configInfoBetaPersistService); + configPublishRequestHandler = new ConfigPublishRequestHandler(configInfoPersistService, configInfoTagPersistService, + configInfoBetaPersistService); DatasourceConfiguration.setEmbeddedStorage(false); } - @After - public void after() { + @AfterEach + void after() { aggrWhitelistMockedStatic.close(); envUtilMockedStatic.close(); } @@ -95,7 +96,7 @@ public void after() { * @throws Exception exception. */ @Test - public void testNormalPublishConfigNotCas() throws Exception { + void testNormalPublishConfigNotCas() throws Exception { String dataId = "testNormalPublishConfigNotCas"; String group = "group"; String tenant = "tenant"; @@ -141,15 +142,15 @@ public Class subscribeType() { any(Map.class))).thenReturn(configOperateResult); ConfigPublishResponse response = configPublishRequestHandler.handle(configPublishRequest, requestMeta); - Assert.assertEquals(ResponseCode.SUCCESS.getCode(), response.getResultCode()); + assertEquals(ResponseCode.SUCCESS.getCode(), response.getResultCode()); Thread.sleep(500L); - Assert.assertTrue(reference.get() != null); - Assert.assertEquals(dataId, reference.get().dataId); - Assert.assertEquals(group, reference.get().group); - Assert.assertEquals(tenant, reference.get().tenant); - Assert.assertEquals(timestamp, reference.get().lastModifiedTs); - Assert.assertFalse(reference.get().isBatch); - Assert.assertFalse(reference.get().isBeta); + assertTrue(reference.get() != null); + assertEquals(dataId, reference.get().dataId); + assertEquals(group, reference.get().group); + assertEquals(tenant, reference.get().tenant); + assertEquals(timestamp, reference.get().lastModifiedTs); + assertFalse(reference.get().isBatch); + assertFalse(reference.get().isBeta); } @@ -159,7 +160,7 @@ public Class subscribeType() { * @throws Exception exception. */ @Test - public void testNormalPublishConfigCas() throws Exception { + void testNormalPublishConfigCas() throws Exception { String dataId = "testNormalPublishConfigCas"; String group = "group"; String tenant = "tenant"; @@ -202,19 +203,19 @@ public Class subscribeType() { long id = timestamp / 1000; configOperateResult.setId(id); configOperateResult.setLastModified(timestamp); - when(configInfoPersistService.insertOrUpdateCas(eq(requestMeta.getClientIp()), eq(srcUser), - any(ConfigInfo.class), any(Map.class))).thenReturn(configOperateResult); + when(configInfoPersistService.insertOrUpdateCas(eq(requestMeta.getClientIp()), eq(srcUser), any(ConfigInfo.class), + any(Map.class))).thenReturn(configOperateResult); ConfigPublishResponse response = configPublishRequestHandler.handle(configPublishRequest, requestMeta); - Assert.assertEquals(ResponseCode.SUCCESS.getCode(), response.getResultCode()); + assertEquals(ResponseCode.SUCCESS.getCode(), response.getResultCode()); Thread.sleep(500L); - Assert.assertTrue(reference.get() != null); - Assert.assertEquals(dataId, reference.get().dataId); - Assert.assertEquals(group, reference.get().group); - Assert.assertEquals(tenant, reference.get().tenant); - Assert.assertEquals(timestamp, reference.get().lastModifiedTs); - Assert.assertFalse(reference.get().isBatch); - Assert.assertFalse(reference.get().isBeta); + assertTrue(reference.get() != null); + assertEquals(dataId, reference.get().dataId); + assertEquals(group, reference.get().group); + assertEquals(tenant, reference.get().tenant); + assertEquals(timestamp, reference.get().lastModifiedTs); + assertFalse(reference.get().isBatch); + assertFalse(reference.get().isBeta); } /** @@ -223,7 +224,7 @@ public Class subscribeType() { * @throws Exception exception. */ @Test - public void testNormalPublishConfigCasError() throws Exception { + void testNormalPublishConfigCasError() throws Exception { String dataId = "testNormalPublishConfigCasError"; String group = "group"; String tenant = "tenant"; @@ -271,19 +272,19 @@ public Class subscribeType() { long id = timestamp / 1000; configOperateResult.setId(id); configOperateResult.setLastModified(timestamp); - when(configInfoPersistService.insertOrUpdateCas(eq(requestMeta.getClientIp()), eq(srcUser), - any(ConfigInfo.class), any(Map.class))).thenThrow(new NacosRuntimeException(502, "mock error")); + when(configInfoPersistService.insertOrUpdateCas(eq(requestMeta.getClientIp()), eq(srcUser), any(ConfigInfo.class), + any(Map.class))).thenThrow(new NacosRuntimeException(502, "mock error")); ConfigPublishResponse response = configPublishRequestHandler.handle(configPublishRequest, requestMeta); - Assert.assertEquals(ResponseCode.FAIL.getCode(), response.getResultCode()); - Assert.assertTrue(response.getMessage().contains("mock error")); + assertEquals(ResponseCode.FAIL.getCode(), response.getResultCode()); + assertTrue(response.getMessage().contains("mock error")); Thread.sleep(500L); - Assert.assertTrue(reference.get() == null); + assertTrue(reference.get() == null); } @Test - public void testPublishAggrCheckFail() throws NacosException, InterruptedException { + void testPublishAggrCheckFail() throws NacosException, InterruptedException { RequestMeta requestMeta = new RequestMeta(); String clientIp = "127.0.0.1"; @@ -318,14 +319,14 @@ public Class subscribeType() { }); ConfigPublishResponse response = configPublishRequestHandler.handle(configPublishRequest, requestMeta); - Assert.assertEquals(ResponseCode.FAIL.getCode(), response.getResultCode()); - Assert.assertTrue(response.getMessage().contains("is aggr")); + assertEquals(ResponseCode.FAIL.getCode(), response.getResultCode()); + assertTrue(response.getMessage().contains("is aggr")); Thread.sleep(500L); - Assert.assertTrue(reference.get() == null); + assertTrue(reference.get() == null); } @Test - public void testBetaPublishNotCas() throws NacosException, InterruptedException { + void testBetaPublishNotCas() throws NacosException, InterruptedException { String dataId = "testBetaPublish"; String group = "group"; String tenant = "tenant"; @@ -369,24 +370,24 @@ public Class subscribeType() { long id = timestamp / 1000; configOperateResult.setId(id); configOperateResult.setLastModified(timestamp); - when(configInfoBetaPersistService.insertOrUpdateBeta(any(ConfigInfo.class), eq(betaIps), - eq(requestMeta.getClientIp()), eq(srcUser))).thenReturn(configOperateResult); + when(configInfoBetaPersistService.insertOrUpdateBeta(any(ConfigInfo.class), eq(betaIps), eq(requestMeta.getClientIp()), + eq(srcUser))).thenReturn(configOperateResult); ConfigPublishResponse response = configPublishRequestHandler.handle(configPublishRequest, requestMeta); - Assert.assertEquals(ResponseCode.SUCCESS.getCode(), response.getResultCode()); + assertEquals(ResponseCode.SUCCESS.getCode(), response.getResultCode()); Thread.sleep(500L); - Assert.assertTrue(reference.get() != null); - Assert.assertEquals(dataId, reference.get().dataId); - Assert.assertEquals(group, reference.get().group); - Assert.assertEquals(tenant, reference.get().tenant); - Assert.assertEquals(timestamp, reference.get().lastModifiedTs); - Assert.assertFalse(reference.get().isBatch); - Assert.assertTrue(reference.get().isBeta); + assertTrue(reference.get() != null); + assertEquals(dataId, reference.get().dataId); + assertEquals(group, reference.get().group); + assertEquals(tenant, reference.get().tenant); + assertEquals(timestamp, reference.get().lastModifiedTs); + assertFalse(reference.get().isBatch); + assertTrue(reference.get().isBeta); } @Test - public void testBetaPublishCas() throws NacosException, InterruptedException { + void testBetaPublishCas() throws NacosException, InterruptedException { String dataId = "testBetaPublishCas"; String group = "group"; String tenant = "tenant"; @@ -431,24 +432,24 @@ public Class subscribeType() { long id = timestamp / 1000; configOperateResult.setId(id); configOperateResult.setLastModified(timestamp); - when(configInfoBetaPersistService.insertOrUpdateBetaCas(any(ConfigInfo.class), eq(betaIps), - eq(requestMeta.getClientIp()), eq(srcUser))).thenReturn(configOperateResult); + when(configInfoBetaPersistService.insertOrUpdateBetaCas(any(ConfigInfo.class), eq(betaIps), eq(requestMeta.getClientIp()), + eq(srcUser))).thenReturn(configOperateResult); ConfigPublishResponse response = configPublishRequestHandler.handle(configPublishRequest, requestMeta); - Assert.assertEquals(ResponseCode.SUCCESS.getCode(), response.getResultCode()); + assertEquals(ResponseCode.SUCCESS.getCode(), response.getResultCode()); Thread.sleep(500L); - Assert.assertTrue(reference.get() != null); - Assert.assertEquals(dataId, reference.get().dataId); - Assert.assertEquals(group, reference.get().group); - Assert.assertEquals(tenant, reference.get().tenant); - Assert.assertEquals(timestamp, reference.get().lastModifiedTs); - Assert.assertFalse(reference.get().isBatch); - Assert.assertTrue(reference.get().isBeta); + assertTrue(reference.get() != null); + assertEquals(dataId, reference.get().dataId); + assertEquals(group, reference.get().group); + assertEquals(tenant, reference.get().tenant); + assertEquals(timestamp, reference.get().lastModifiedTs); + assertFalse(reference.get().isBatch); + assertTrue(reference.get().isBeta); } @Test - public void testTagPublishNotCas() throws NacosException, InterruptedException { + void testTagPublishNotCas() throws NacosException, InterruptedException { ConfigPublishRequest configPublishRequest = new ConfigPublishRequest(); String dataId = "testTagPublishNotCas"; @@ -494,26 +495,26 @@ public Class subscribeType() { long id = timestamp / 1000; configOperateResult.setId(id); configOperateResult.setLastModified(timestamp); - when(configInfoTagPersistService.insertOrUpdateTag(any(ConfigInfo.class), eq(tag), - eq(requestMeta.getClientIp()), eq(srcUser))).thenReturn(configOperateResult); + when(configInfoTagPersistService.insertOrUpdateTag(any(ConfigInfo.class), eq(tag), eq(requestMeta.getClientIp()), + eq(srcUser))).thenReturn(configOperateResult); ConfigPublishResponse response = configPublishRequestHandler.handle(configPublishRequest, requestMeta); - Assert.assertEquals(ResponseCode.SUCCESS.getCode(), response.getResultCode()); + assertEquals(ResponseCode.SUCCESS.getCode(), response.getResultCode()); Thread.sleep(500L); - Assert.assertTrue(reference.get() != null); - Assert.assertEquals(dataId, reference.get().dataId); - Assert.assertEquals(group, reference.get().group); - Assert.assertEquals(tenant, reference.get().tenant); - Assert.assertEquals(timestamp, reference.get().lastModifiedTs); - Assert.assertFalse(reference.get().isBatch); - Assert.assertFalse(reference.get().isBeta); - Assert.assertEquals(tag, reference.get().tag); + assertTrue(reference.get() != null); + assertEquals(dataId, reference.get().dataId); + assertEquals(group, reference.get().group); + assertEquals(tenant, reference.get().tenant); + assertEquals(timestamp, reference.get().lastModifiedTs); + assertFalse(reference.get().isBatch); + assertFalse(reference.get().isBeta); + assertEquals(tag, reference.get().tag); } @Test - public void testTagPublishCas() throws NacosException, InterruptedException { + void testTagPublishCas() throws NacosException, InterruptedException { String dataId = "testTagPublishCas"; String group = "group"; ConfigPublishRequest configPublishRequest = new ConfigPublishRequest(); @@ -553,21 +554,21 @@ public Class subscribeType() { long id = timestamp / 1000; configOperateResult.setId(id); configOperateResult.setLastModified(timestamp); - when(configInfoTagPersistService.insertOrUpdateTagCas(any(ConfigInfo.class), eq(tag), - eq(requestMeta.getClientIp()), eq(srcUser))).thenReturn(configOperateResult); + when(configInfoTagPersistService.insertOrUpdateTagCas(any(ConfigInfo.class), eq(tag), eq(requestMeta.getClientIp()), + eq(srcUser))).thenReturn(configOperateResult); ConfigPublishResponse response = configPublishRequestHandler.handle(configPublishRequest, requestMeta); - Assert.assertEquals(ResponseCode.SUCCESS.getCode(), response.getResultCode()); + assertEquals(ResponseCode.SUCCESS.getCode(), response.getResultCode()); Thread.sleep(500L); - Assert.assertTrue(reference.get() != null); - Assert.assertEquals(dataId, reference.get().dataId); - Assert.assertEquals(group, reference.get().group); - Assert.assertEquals(tenant, reference.get().tenant); - Assert.assertEquals(timestamp, reference.get().lastModifiedTs); - Assert.assertFalse(reference.get().isBatch); - Assert.assertFalse(reference.get().isBeta); - Assert.assertEquals(tag, reference.get().tag); + assertTrue(reference.get() != null); + assertEquals(dataId, reference.get().dataId); + assertEquals(group, reference.get().group); + assertEquals(tenant, reference.get().tenant); + assertEquals(timestamp, reference.get().lastModifiedTs); + assertFalse(reference.get().isBatch); + assertFalse(reference.get().isBeta); + assertEquals(tag, reference.get().tag); } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigQueryRequestHandlerTest.java b/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigQueryRequestHandlerTest.java index b6edcde5707..6467ad8e948 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigQueryRequestHandlerTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigQueryRequestHandlerTest.java @@ -28,14 +28,13 @@ import com.alibaba.nacos.config.server.utils.GroupKey2; import com.alibaba.nacos.config.server.utils.PropertyUtil; import com.alibaba.nacos.sys.env.EnvUtil; -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.MockedStatic; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.core.env.StandardEnvironment; import java.io.IOException; @@ -43,13 +42,15 @@ import static com.alibaba.nacos.api.common.Constants.VIPSERVER_TAG; import static com.alibaba.nacos.api.config.remote.response.ConfigQueryResponse.CONFIG_NOT_FOUND; +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.eq; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class ConfigQueryRequestHandlerTest { - - private ConfigQueryRequestHandler configQueryRequestHandler; +@ExtendWith(MockitoExtension.class) +class ConfigQueryRequestHandlerTest { static MockedStatic configCacheServiceMockedStatic; @@ -65,16 +66,18 @@ public class ConfigQueryRequestHandlerTest { String content = "content" + System.currentTimeMillis(); - @After - public void after() { + private ConfigQueryRequestHandler configQueryRequestHandler; + + @AfterEach + void after() { configCacheServiceMockedStatic.close(); propertyUtilMockedStatic.close(); configDiskServiceFactoryMockedStatic.close(); EnvUtil.setEnvironment(null); } - @Before - public void setUp() throws IOException { + @BeforeEach + void setUp() throws IOException { EnvUtil.setEnvironment(new StandardEnvironment()); configCacheServiceMockedStatic = Mockito.mockStatic(ConfigCacheService.class); propertyUtilMockedStatic = Mockito.mockStatic(PropertyUtil.class); @@ -92,7 +95,7 @@ public void setUp() throws IOException { * @throws Exception Exception. */ @Test - public void testGetNormal() throws Exception { + void testGetNormal() throws Exception { final String groupKey = GroupKey2.getKey(dataId, group, ""); String content = "content_from_notdirectreadÄãºÃ" + System.currentTimeMillis(); @@ -113,14 +116,14 @@ public void testGetNormal() throws Exception { when(configRocksDbDiskService.getContent(eq(dataId), eq(group), eq(null))).thenReturn(content); ConfigQueryResponse response = configQueryRequestHandler.handle(configQueryRequest, requestMeta); - Assert.assertEquals(content, response.getContent()); - Assert.assertEquals(MD5Utils.md5Hex(content, "UTF-8"), response.getMd5()); - Assert.assertEquals("key_testGetNormal_NotDirectRead", response.getEncryptedDataKey()); + assertEquals(content, response.getContent()); + assertEquals(MD5Utils.md5Hex(content, "UTF-8"), response.getMd5()); + assertEquals("key_testGetNormal_NotDirectRead", response.getEncryptedDataKey()); - Assert.assertFalse(response.isBeta()); - Assert.assertNull(response.getTag()); + assertFalse(response.isBeta()); + assertNull(response.getTag()); - Assert.assertEquals(content, response.getContent()); + assertEquals(content, response.getContent()); } @@ -130,7 +133,7 @@ public void testGetNormal() throws Exception { * @throws Exception Exception. */ @Test - public void testGetBeta() throws Exception { + void testGetBeta() throws Exception { final String groupKey = GroupKey2.getKey(dataId, group, ""); ConfigRocksDbDiskService configRocksDbDiskService = Mockito.mock(ConfigRocksDbDiskService.class); @@ -156,11 +159,11 @@ public void testGetBeta() throws Exception { when(configRocksDbDiskService.getBetaContent(eq(dataId), eq(group), eq(null))).thenReturn(content); ConfigQueryResponse response = configQueryRequestHandler.handle(configQueryRequest, requestMeta); //check content&md5 - Assert.assertEquals(content, response.getContent()); - Assert.assertEquals(MD5Utils.md5Hex(content, "UTF-8"), response.getMd5()); + assertEquals(content, response.getContent()); + assertEquals(MD5Utils.md5Hex(content, "UTF-8"), response.getMd5()); //check flags. - Assert.assertTrue(response.isBeta()); - Assert.assertNull(response.getTag()); + assertTrue(response.isBeta()); + assertNull(response.getTag()); } @@ -170,7 +173,7 @@ public void testGetBeta() throws Exception { * @throws Exception Exception. */ @Test - public void testGetTagNotFound() throws Exception { + void testGetTagNotFound() throws Exception { final String groupKey = GroupKey2.getKey(dataId, group, ""); String content = "content_from_tag_withtagÄãºÃ" + System.currentTimeMillis(); @@ -197,14 +200,14 @@ public void testGetTagNotFound() throws Exception { ConfigQueryResponse response = configQueryRequestHandler.handle(configQueryRequest, requestMeta); //check content&md5 - Assert.assertNull(response.getContent()); - Assert.assertNull(response.getMd5()); - Assert.assertEquals(response.getErrorCode(), CONFIG_NOT_FOUND); - Assert.assertNull(response.getEncryptedDataKey()); + assertNull(response.getContent()); + assertNull(response.getMd5()); + assertEquals(CONFIG_NOT_FOUND, response.getErrorCode()); + assertNull(response.getEncryptedDataKey()); //check flags. - Assert.assertFalse(response.isBeta()); - Assert.assertEquals(response.getTag(), specificTag); + assertFalse(response.isBeta()); + assertEquals(response.getTag(), specificTag); } @@ -214,7 +217,7 @@ public void testGetTagNotFound() throws Exception { * @throws Exception Exception. */ @Test - public void testGetTagWithTag() throws Exception { + void testGetTagWithTag() throws Exception { final String groupKey = GroupKey2.getKey(dataId, group, ""); String content = "content_from_tag_notdirectreadÄãºÃ" + System.currentTimeMillis(); @@ -248,17 +251,16 @@ public void testGetTagWithTag() throws Exception { requestMeta.setClientIp("127.0.0.1"); //mock disk read. - when(configRocksDbDiskService.getTagContent(eq(dataId), eq(group), eq(null), eq(specificTag))).thenReturn( - tagContent); + when(configRocksDbDiskService.getTagContent(eq(dataId), eq(group), eq(null), eq(specificTag))).thenReturn(tagContent); ConfigQueryResponse response = configQueryRequestHandler.handle(configQueryRequest, requestMeta); //check content&md5 - Assert.assertEquals(tagContent, response.getContent()); - Assert.assertEquals(MD5Utils.md5Hex(tagContent, "UTF-8"), response.getMd5()); - Assert.assertEquals("key_testGetTag_NotDirectRead", response.getEncryptedDataKey()); + assertEquals(tagContent, response.getContent()); + assertEquals(MD5Utils.md5Hex(tagContent, "UTF-8"), response.getMd5()); + assertEquals("key_testGetTag_NotDirectRead", response.getEncryptedDataKey()); //check flags. - Assert.assertFalse(response.isBeta()); - Assert.assertEquals(response.getTag(), specificTag); + assertFalse(response.isBeta()); + assertEquals(response.getTag(), specificTag); } @@ -268,7 +270,7 @@ public void testGetTagWithTag() throws Exception { * @throws Exception Exception. */ @Test - public void testGetTagAutoTag() throws Exception { + void testGetTagAutoTag() throws Exception { final String groupKey = GroupKey2.getKey(dataId, group, ""); String content = "content_from_tag_notdirectreadÄãºÃ" + System.currentTimeMillis(); @@ -296,18 +298,17 @@ public void testGetTagAutoTag() throws Exception { requestMeta.setClientIp("127.0.0.1"); //mock disk read. - when(configRocksDbDiskService.getTagContent(eq(dataId), eq(group), eq(null), eq(autoTag))).thenReturn( - tagContent); + when(configRocksDbDiskService.getTagContent(eq(dataId), eq(group), eq(null), eq(autoTag))).thenReturn(tagContent); ConfigQueryResponse response = configQueryRequestHandler.handle(configQueryRequest, requestMeta); //check content&md5 - Assert.assertEquals(tagContent, response.getContent()); - Assert.assertEquals(MD5Utils.md5Hex(tagContent, "UTF-8"), response.getMd5()); - Assert.assertEquals("key_testGetTag_AutoTag_NotDirectRead", response.getEncryptedDataKey()); + assertEquals(tagContent, response.getContent()); + assertEquals(MD5Utils.md5Hex(tagContent, "UTF-8"), response.getMd5()); + assertEquals("key_testGetTag_AutoTag_NotDirectRead", response.getEncryptedDataKey()); //check flags. - Assert.assertFalse(response.isBeta()); - Assert.assertEquals(response.getTag(), autoTag); + assertFalse(response.isBeta()); + assertEquals(response.getTag(), autoTag); } @@ -317,14 +318,14 @@ public void testGetTagAutoTag() throws Exception { * @throws Exception Exception. */ @Test - public void testGetConfigNotExistAndConflict() throws Exception { + void testGetConfigNotExistAndConflict() throws Exception { String dataId = "dataId" + System.currentTimeMillis(); String group = "group" + System.currentTimeMillis(); String tenant = "tenant" + System.currentTimeMillis(); //test config not exist - configCacheServiceMockedStatic.when( - () -> ConfigCacheService.tryConfigReadLock(GroupKey2.getKey(dataId, group, tenant))).thenReturn(0); + configCacheServiceMockedStatic.when(() -> ConfigCacheService.tryConfigReadLock(GroupKey2.getKey(dataId, group, tenant))) + .thenReturn(0); final String groupKey = GroupKey2.getKey(dataId, group, tenant); when(ConfigCacheService.getContentCache(eq(groupKey))).thenReturn(null); @@ -336,22 +337,22 @@ public void testGetConfigNotExistAndConflict() throws Exception { requestMeta.setClientIp("127.0.0.1"); ConfigQueryResponse response = configQueryRequestHandler.handle(configQueryRequest, requestMeta); - Assert.assertEquals(CONFIG_NOT_FOUND, response.getErrorCode()); - Assert.assertEquals(null, response.getContent()); - Assert.assertEquals(null, response.getMd5()); - Assert.assertFalse(response.isBeta()); - Assert.assertNull(response.getTag()); + assertEquals(CONFIG_NOT_FOUND, response.getErrorCode()); + assertNull(response.getContent()); + assertNull(response.getMd5()); + assertFalse(response.isBeta()); + assertNull(response.getTag()); //test config conflict when(ConfigCacheService.getContentCache(eq(groupKey))).thenReturn(new CacheItem(groupKey)); - configCacheServiceMockedStatic.when( - () -> ConfigCacheService.tryConfigReadLock(GroupKey2.getKey(dataId, group, tenant))).thenReturn(-1); + configCacheServiceMockedStatic.when(() -> ConfigCacheService.tryConfigReadLock(GroupKey2.getKey(dataId, group, tenant))) + .thenReturn(-1); ConfigQueryResponse responseConflict = configQueryRequestHandler.handle(configQueryRequest, requestMeta); - Assert.assertEquals(ConfigQueryResponse.CONFIG_QUERY_CONFLICT, responseConflict.getErrorCode()); - Assert.assertEquals(null, responseConflict.getContent()); - Assert.assertEquals(null, responseConflict.getMd5()); - Assert.assertFalse(responseConflict.isBeta()); - Assert.assertNull(responseConflict.getTag()); + assertEquals(ConfigQueryResponse.CONFIG_QUERY_CONFLICT, responseConflict.getErrorCode()); + assertNull(responseConflict.getContent()); + assertNull(responseConflict.getMd5()); + assertFalse(responseConflict.isBeta()); + assertNull(responseConflict.getTag()); } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigRemoveRequestHandlerTest.java b/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigRemoveRequestHandlerTest.java index f63c294e9d2..f489b112a83 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigRemoveRequestHandlerTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/remote/ConfigRemoveRequestHandlerTest.java @@ -24,16 +24,18 @@ import com.alibaba.nacos.config.server.service.repository.ConfigInfoPersistService; import com.alibaba.nacos.config.server.service.repository.ConfigInfoTagPersistService; import com.alibaba.nacos.config.server.service.trace.ConfigTraceService; -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; -@RunWith(MockitoJUnitRunner.class) -public class ConfigRemoveRequestHandlerTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@ExtendWith(MockitoExtension.class) +class ConfigRemoveRequestHandlerTest { private ConfigRemoveRequestHandler configRemoveRequestHandler; @@ -43,15 +45,14 @@ public class ConfigRemoveRequestHandlerTest { @Mock private ConfigInfoTagPersistService configInfoTagPersistService; - @Before - public void setUp() throws Exception { - configRemoveRequestHandler = new ConfigRemoveRequestHandler(configInfoPersistService, - configInfoTagPersistService); + @BeforeEach + void setUp() throws Exception { + configRemoveRequestHandler = new ConfigRemoveRequestHandler(configInfoPersistService, configInfoTagPersistService); Mockito.mockStatic(ConfigTraceService.class); } @Test - public void testHandle() { + void testHandle() { ConfigRemoveRequest configRemoveRequest = new ConfigRemoveRequest(); configRemoveRequest.setRequestId("requestId"); configRemoveRequest.setGroup("group"); @@ -61,10 +62,10 @@ public void testHandle() { meta.setClientIp("1.1.1.1"); try { ConfigRemoveResponse configRemoveResponse = configRemoveRequestHandler.handle(configRemoveRequest, meta); - Assert.assertEquals(ResponseCode.SUCCESS.getCode(), configRemoveResponse.getResultCode()); + assertEquals(ResponseCode.SUCCESS.getCode(), configRemoveResponse.getResultCode()); } catch (NacosException e) { e.printStackTrace(); - Assert.assertTrue(false); + assertTrue(false); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/remote/RpcConfigChangeNotifierTest.java b/config/src/test/java/com/alibaba/nacos/config/server/remote/RpcConfigChangeNotifierTest.java index 3a25134745b..98e0806b46f 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/remote/RpcConfigChangeNotifierTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/remote/RpcConfigChangeNotifierTest.java @@ -29,14 +29,14 @@ import com.alibaba.nacos.plugin.control.tps.request.TpsCheckRequest; import com.alibaba.nacos.plugin.control.tps.response.TpsCheckResponse; import com.alibaba.nacos.sys.env.EnvUtil; -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.MockedStatic; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.util.ReflectionTestUtils; import java.util.ArrayList; @@ -52,19 +52,14 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; -@RunWith(MockitoJUnitRunner.class) -public class RpcConfigChangeNotifierTest { +@ExtendWith(MockitoExtension.class) +class RpcConfigChangeNotifierTest { - private RpcConfigChangeNotifier rpcConfigChangeNotifier; - - @Mock - private ConfigChangeListenContext configChangeListenContext; + static final String POINT_CONFIG_PUSH = "CONFIG_PUSH_COUNT"; - @Mock - private RpcPushService rpcPushService; + static final String POINT_CONFIG_PUSH_SUCCESS = "CONFIG_PUSH_SUCCESS"; - @Mock - private ConnectionManager connectionManager; + static final String POINT_CONFIG_PUSH_FAIL = "CONFIG_PUSH_FAIL"; @Mock ControlManagerCenter controlManagerCenter; @@ -76,12 +71,22 @@ public class RpcConfigChangeNotifierTest { MockedStatic envUtilMockedStatic; - @Before - public void setUp() { + private RpcConfigChangeNotifier rpcConfigChangeNotifier; + + @Mock + private ConfigChangeListenContext configChangeListenContext; + + @Mock + private RpcPushService rpcPushService; + + @Mock + private ConnectionManager connectionManager; + + @BeforeEach + void setUp() { envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); - envUtilMockedStatic.when( - () -> EnvUtil.getProperty(eq("nacos.config.push.maxRetryTime"), eq(Integer.class), anyInt())) + envUtilMockedStatic.when(() -> EnvUtil.getProperty(eq("nacos.config.push.maxRetryTime"), eq(Integer.class), anyInt())) .thenReturn(3); controlManagerCenterMockedStatic = Mockito.mockStatic(ControlManagerCenter.class); Mockito.when(ControlManagerCenter.getInstance()).thenReturn(controlManagerCenter); @@ -93,14 +98,14 @@ public void setUp() { } - @After - public void after() { + @AfterEach + void after() { envUtilMockedStatic.close(); controlManagerCenterMockedStatic.close(); } @Test - public void testOnDataEvent() throws InterruptedException { + void testOnDataEvent() throws InterruptedException { final String groupKey = GroupKey2.getKey("nacos.internal.tps.control_rule_1", "nacos", "tenant"); @@ -115,40 +120,38 @@ public void testOnDataEvent() throws InterruptedException { GrpcConnection mockConn3 = Mockito.mock(GrpcConnection.class); //mock con1 push normal Mockito.when(connectionManager.getConnection(eq("con1"))).thenReturn(mockConn1); - Mockito.when(mockConn1.getMetaInfo()).thenReturn( - new ConnectionMeta("con1", "192.168.0.1", "192.168.0.2", 34567, 9848, "GRPC", "2.2.0", null, - new HashMap<>())); + Mockito.when(mockConn1.getMetaInfo()) + .thenReturn(new ConnectionMeta("con1", "192.168.0.1", "192.168.0.2", 34567, 9848, "GRPC", "2.2.0", null, new HashMap<>())); //mock con1 noy exist Mockito.when(connectionManager.getConnection(eq("con2"))).thenReturn(null); Mockito.when(connectionManager.getConnection(eq("con3"))).thenReturn(mockConn3); - Mockito.when(mockConn3.getMetaInfo()).thenReturn( - new ConnectionMeta("con3", "192.168.0.1", "192.168.0.2", 34567, 9848, "GRPC", "2.2.0", null, - new HashMap<>())); + Mockito.when(mockConn3.getMetaInfo()) + .thenReturn(new ConnectionMeta("con3", "192.168.0.1", "192.168.0.2", 34567, 9848, "GRPC", "2.2.0", null, new HashMap<>())); Mockito.when(configChangeListenContext.getListeners(eq(groupKey))).thenReturn(mockConnectionIds); //mock push tps passed - Mockito.when(tpsControlManager.check(any(TpsCheckRequest.class))) - .thenReturn(new TpsCheckResponse(true, 200, "success")); + Mockito.when(tpsControlManager.check(any(TpsCheckRequest.class))).thenReturn(new TpsCheckResponse(true, 200, "success")); rpcConfigChangeNotifier.onEvent(new LocalDataChangeEvent(groupKey, true, betaIps)); //wait rpc push executed. Thread.sleep(50L); //expect rpc push task run. - Mockito.verify(rpcPushService, times(1)).pushWithCallback(eq("con1"), any(ConfigChangeNotifyRequest.class), - any(RpcConfigChangeNotifier.RpcPushCallback.class), any(Executor.class)); - Mockito.verify(rpcPushService, times(1)).pushWithCallback(eq("con3"), any(ConfigChangeNotifyRequest.class), - any(RpcConfigChangeNotifier.RpcPushCallback.class), any(Executor.class)); + Mockito.verify(rpcPushService, times(1)) + .pushWithCallback(eq("con1"), any(ConfigChangeNotifyRequest.class), any(RpcConfigChangeNotifier.RpcPushCallback.class), + any(Executor.class)); + Mockito.verify(rpcPushService, times(1)) + .pushWithCallback(eq("con3"), any(ConfigChangeNotifyRequest.class), any(RpcConfigChangeNotifier.RpcPushCallback.class), + any(Executor.class)); } @Test - public void testRpcCallBack() { + void testRpcCallBack() { MockedStatic configExecutorMockedStatic = Mockito.mockStatic(ConfigExecutor.class); try { RpcConfigChangeNotifier.RpcPushTask task = Mockito.mock(RpcConfigChangeNotifier.RpcPushTask.class); Mockito.when(task.getConnectionId()).thenReturn("testconn1"); - Mockito.when(connectionManager.getConnection(eq("testconn1"))) - .thenReturn(Mockito.mock(GrpcConnection.class)); + Mockito.when(connectionManager.getConnection(eq("testconn1"))).thenReturn(Mockito.mock(GrpcConnection.class)); ConfigChangeNotifyRequest notifyRequest = new ConfigChangeNotifyRequest(); notifyRequest.setDataId("d1"); notifyRequest.setGroup("g1"); @@ -156,16 +159,16 @@ public void testRpcCallBack() { //mock task not overtimes and receive exception on callback Mockito.when(task.isOverTimes()).thenReturn(false); Mockito.when(task.getTryTimes()).thenReturn(2); - RpcConfigChangeNotifier.RpcPushCallback rpcPushCallback = new RpcConfigChangeNotifier.RpcPushCallback(task, - tpsControlManager, connectionManager); + RpcConfigChangeNotifier.RpcPushCallback rpcPushCallback = new RpcConfigChangeNotifier.RpcPushCallback(task, tpsControlManager, + connectionManager); rpcPushCallback.onFail(new RuntimeException()); //expect config push fail be recorded. Mockito.verify(tpsControlManager, times(1)).check(any(TpsCheckRequest.class)); //expect schedule this task next retry times configExecutorMockedStatic.verify( - () -> ConfigExecutor.scheduleClientConfigNotifier(any(RpcConfigChangeNotifier.RpcPushTask.class), - eq(2 * 2L), eq(TimeUnit.SECONDS))); + () -> ConfigExecutor.scheduleClientConfigNotifier(any(RpcConfigChangeNotifier.RpcPushTask.class), eq(2 * 2L), + eq(TimeUnit.SECONDS))); //mock rpcPushCallback.onSuccess(); //expect config push success be recorded. @@ -182,14 +185,8 @@ public void testRpcCallBack() { } - static final String POINT_CONFIG_PUSH = "CONFIG_PUSH_COUNT"; - - static final String POINT_CONFIG_PUSH_SUCCESS = "CONFIG_PUSH_SUCCESS"; - - static final String POINT_CONFIG_PUSH_FAIL = "CONFIG_PUSH_FAIL"; - @Test - public void testRegisterTpsPoint() { + void testRegisterTpsPoint() { rpcConfigChangeNotifier.registerTpsPoint(); Mockito.verify(tpsControlManager, Mockito.times(1)).registerTpsPoint(eq(POINT_CONFIG_PUSH)); diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/AggrWhitelistTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/AggrWhitelistTest.java index 4958704b2cc..dbda0ad4bf9 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/AggrWhitelistTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/AggrWhitelistTest.java @@ -16,18 +16,18 @@ package com.alibaba.nacos.config.server.service; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class AggrWhitelistTest { +class AggrWhitelistTest { @Test - public void testIsAggrDataId() { + void testIsAggrDataId() { List list = new ArrayList(); list.add("com.taobao.jiuren.*"); list.add("NS_NACOS_SUBSCRIPTION_TOPIC_*"); diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/ClientTrackServiceTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/ClientTrackServiceTest.java index 7d2be2e3231..edb32244646 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/ClientTrackServiceTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/ClientTrackServiceTest.java @@ -17,24 +17,27 @@ package com.alibaba.nacos.config.server.service; import com.alibaba.nacos.config.server.utils.GroupKey2; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.web.WebAppConfiguration; -@RunWith(SpringJUnit4ClassRunner.class) +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@ExtendWith(SpringExtension.class) @WebAppConfiguration -public class ClientTrackServiceTest { +class ClientTrackServiceTest { - @Before - public void before() { + @BeforeEach + void before() { ClientTrackService.clientRecords.clear(); } @Test - public void testTrackClientMd5() { + void testTrackClientMd5() { String clientIp = "1.1.1.1"; String dataId = "com.taobao.session.xml"; String group = "online"; @@ -46,13 +49,13 @@ public void testTrackClientMd5() { ClientTrackService.trackClientMd5(clientIp, groupKey, md5); ClientTrackService.trackClientMd5(clientIp, groupKey, md5); - Assert.assertEquals(true, ClientTrackService.isClientUptodate(clientIp).get(groupKey)); - Assert.assertEquals(1, ClientTrackService.subscribeClientCount()); - Assert.assertEquals(1, ClientTrackService.subscriberCount()); + assertTrue(ClientTrackService.isClientUptodate(clientIp).get(groupKey)); + assertEquals(1, ClientTrackService.subscribeClientCount()); + assertEquals(1, ClientTrackService.subscriberCount()); //服务端数据更新 ConfigCacheService.updateMd5(groupKey, md5 + "111", System.currentTimeMillis(), ""); - Assert.assertEquals(false, ClientTrackService.isClientUptodate(clientIp).get(groupKey)); + assertFalse(ClientTrackService.isClientUptodate(clientIp).get(groupKey)); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/ConfigCacheServiceTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/ConfigCacheServiceTest.java index 040eb13bb7e..fccdb2e5b90 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/ConfigCacheServiceTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/ConfigCacheServiceTest.java @@ -25,16 +25,15 @@ import com.alibaba.nacos.config.server.utils.PropertyUtil; import com.alibaba.nacos.config.server.utils.SimpleReadWriteLock; import com.alibaba.nacos.sys.env.EnvUtil; -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.stubbing.OngoingStubbing; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import java.io.IOException; import java.lang.reflect.Field; @@ -43,13 +42,17 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +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.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; -@RunWith(SpringJUnit4ClassRunner.class) -public class ConfigCacheServiceTest { +@ExtendWith(SpringExtension.class) +class ConfigCacheServiceTest { MockedStatic propertyUtilMockedStatic; @@ -60,24 +63,23 @@ public class ConfigCacheServiceTest { MockedStatic envUtilMockedStatic; - @Before - public void before() { + @BeforeEach + void before() { envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); configDiskServiceFactoryMockedStatic = Mockito.mockStatic(ConfigDiskServiceFactory.class); - configDiskServiceFactoryMockedStatic.when(() -> ConfigDiskServiceFactory.getInstance()) - .thenReturn(configDiskService); + configDiskServiceFactoryMockedStatic.when(() -> ConfigDiskServiceFactory.getInstance()).thenReturn(configDiskService); propertyUtilMockedStatic = Mockito.mockStatic(PropertyUtil.class); } - @After - public void after() { + @AfterEach + void after() { envUtilMockedStatic.close(); propertyUtilMockedStatic.close(); configDiskServiceFactoryMockedStatic.close(); } @Test - public void testDumpFormal() throws Exception { + void testDumpFormal() throws Exception { String dataId = "dataIdtestDumpMd5NewTsNewMd5123"; String group = "group11"; String tenant = "tenant112"; @@ -86,19 +88,18 @@ public void testDumpFormal() throws Exception { String groupKey = GroupKey2.getKey(dataId, group, tenant); //make sure not exist prev cache. CacheItem contentCache = ConfigCacheService.getContentCache(groupKey); - Assert.assertTrue(contentCache == null); + assertTrue(contentCache == null); long ts = System.currentTimeMillis(); String type = "json"; String encryptedDataKey = "key12345"; - boolean result = ConfigCacheService.dumpWithMd5(dataId, group, tenant, content, md5, ts, type, - encryptedDataKey); - Assert.assertTrue(result); + boolean result = ConfigCacheService.dumpWithMd5(dataId, group, tenant, content, md5, ts, type, encryptedDataKey); + assertTrue(result); //verify cache. CacheItem contentCache1 = ConfigCacheService.getContentCache(groupKey); - Assert.assertEquals(ts, contentCache1.getConfigCache().getLastModifiedTs()); - Assert.assertEquals(md5, contentCache1.getConfigCache().getMd5Utf8()); - Assert.assertEquals(type, contentCache1.getType()); - Assert.assertEquals(encryptedDataKey, contentCache1.getConfigCache().getEncryptedDataKey()); + assertEquals(ts, contentCache1.getConfigCache().getLastModifiedTs()); + assertEquals(md5, contentCache1.getConfigCache().getMd5Utf8()); + assertEquals(type, contentCache1.getType()); + assertEquals(encryptedDataKey, contentCache1.getConfigCache().getEncryptedDataKey()); Mockito.verify(configDiskService, times(1)).saveToDisk(eq(dataId), eq(group), eq(tenant), eq(content)); //modified ts and content and md5 @@ -107,9 +108,9 @@ public void testDumpFormal() throws Exception { ConfigCacheService.dump(dataId, group, tenant, contentNew, newTs, type, encryptedDataKey); //expect save to disk invoked. Mockito.verify(configDiskService, times(1)).saveToDisk(eq(dataId), eq(group), eq(tenant), eq(contentNew)); - Assert.assertEquals(newTs, contentCache1.getConfigCache().getLastModifiedTs()); + assertEquals(newTs, contentCache1.getConfigCache().getLastModifiedTs()); String newMd5 = MD5Utils.md5Hex(contentNew, "UTF-8"); - Assert.assertEquals(newMd5, contentCache1.getConfigCache().getMd5Utf8()); + assertEquals(newMd5, contentCache1.getConfigCache().getMd5Utf8()); //modified ts old long oldTs2 = newTs - 123L; @@ -118,38 +119,37 @@ public void testDumpFormal() throws Exception { //expect save to disk invoked. Mockito.verify(configDiskService, times(0)).saveToDisk(eq(dataId), eq(group), eq(tenant), eq(contentWithOldTs)); //not change ts and md5 - Assert.assertEquals(newTs, contentCache1.getConfigCache().getLastModifiedTs()); - Assert.assertEquals(newMd5, contentCache1.getConfigCache().getMd5Utf8()); + assertEquals(newTs, contentCache1.getConfigCache().getLastModifiedTs()); + assertEquals(newMd5, contentCache1.getConfigCache().getMd5Utf8()); //modified ts new only long newTs2 = newTs + 123L; ConfigCacheService.dump(dataId, group, tenant, contentNew, newTs2, type, encryptedDataKey); - Assert.assertEquals(newTs2, contentCache1.getConfigCache().getLastModifiedTs()); + assertEquals(newTs2, contentCache1.getConfigCache().getLastModifiedTs()); //save to disk error doThrow(new IOException("No space left on device")).when(configDiskService) .saveToDisk(anyString(), anyString(), anyString(), anyString()); try { long newTs3 = newTs2 + 123L; - boolean dumpErrorResult = ConfigCacheService.dump(dataId, group, tenant, contentNew + "234567", newTs3, - type, encryptedDataKey); + boolean dumpErrorResult = ConfigCacheService.dump(dataId, group, tenant, contentNew + "234567", newTs3, type, encryptedDataKey); envUtilMockedStatic.verify(() -> EnvUtil.systemExit(), times(1)); - Assert.assertFalse(dumpErrorResult); + assertFalse(dumpErrorResult); } catch (Throwable throwable) { - Assert.assertFalse(true); + assertFalse(true); } //test remove boolean remove = ConfigCacheService.remove(dataId, group, tenant); - Assert.assertTrue(remove); + assertTrue(remove); Mockito.verify(configDiskService, times(1)).removeConfigInfo(dataId, group, tenant); CacheItem contentCacheAfterRemove = ConfigCacheService.getContentCache(groupKey); - Assert.assertNull(contentCacheAfterRemove); + assertNull(contentCacheAfterRemove); } @Test - public void testDumpBeta() throws Exception { + void testDumpBeta() throws Exception { String dataId = "dataIdtestDumpBetaNewCache123"; String group = "group11"; String tenant = "tenant112"; @@ -160,14 +160,13 @@ public void testDumpBeta() throws Exception { List betaIps = Arrays.asList("127.0.0.1", "127.0.0.2"); long ts = System.currentTimeMillis(); //init beta cache - boolean result = ConfigCacheService.dumpBeta(dataId, group, tenant, content, ts, String.join(",", betaIps), - encryptedDataKey); - Assert.assertTrue(result); + boolean result = ConfigCacheService.dumpBeta(dataId, group, tenant, content, ts, String.join(",", betaIps), encryptedDataKey); + assertTrue(result); CacheItem contentCache = ConfigCacheService.getContentCache(groupKey); - Assert.assertEquals(md5, contentCache.getConfigCacheBeta().getMd5Utf8()); - Assert.assertEquals(ts, contentCache.getConfigCacheBeta().getLastModifiedTs()); - Assert.assertEquals(betaIps, contentCache.getIps4Beta()); - Assert.assertEquals(encryptedDataKey, contentCache.getConfigCacheBeta().getEncryptedDataKey()); + assertEquals(md5, contentCache.getConfigCacheBeta().getMd5Utf8()); + assertEquals(ts, contentCache.getConfigCacheBeta().getLastModifiedTs()); + assertEquals(betaIps, contentCache.getIps4Beta()); + assertEquals(encryptedDataKey, contentCache.getConfigCacheBeta().getEncryptedDataKey()); Mockito.verify(configDiskService, times(1)).saveBetaToDisk(eq(dataId), eq(group), eq(tenant), eq(content)); //ts newer ,md5 update @@ -175,75 +174,74 @@ public void testDumpBeta() throws Exception { String contentNew = content + tsNew; String md5New = MD5Utils.md5Hex(contentNew, "UTF-8"); List betaIpsNew = Arrays.asList("127.0.0.1", "127.0.0.2", "127.0.0.3"); - boolean resultNew = ConfigCacheService.dumpBeta(dataId, group, tenant, contentNew, tsNew, - String.join(",", betaIpsNew), encryptedDataKey); - Assert.assertTrue(resultNew); - Assert.assertEquals(md5New, contentCache.getConfigCacheBeta().getMd5Utf8()); - Assert.assertEquals(tsNew, contentCache.getConfigCacheBeta().getLastModifiedTs()); - Assert.assertEquals(encryptedDataKey, contentCache.getConfigCacheBeta().getEncryptedDataKey()); - Assert.assertEquals(betaIpsNew, contentCache.getIps4Beta()); + boolean resultNew = ConfigCacheService.dumpBeta(dataId, group, tenant, contentNew, tsNew, String.join(",", betaIpsNew), + encryptedDataKey); + assertTrue(resultNew); + assertEquals(md5New, contentCache.getConfigCacheBeta().getMd5Utf8()); + assertEquals(tsNew, contentCache.getConfigCacheBeta().getLastModifiedTs()); + assertEquals(encryptedDataKey, contentCache.getConfigCacheBeta().getEncryptedDataKey()); + assertEquals(betaIpsNew, contentCache.getIps4Beta()); Mockito.verify(configDiskService, times(1)).saveBetaToDisk(eq(dataId), eq(group), eq(tenant), eq(contentNew)); //ts old ,md5 update long tsOld = tsNew - 1; String contentWithOldTs = "contentWithOldTs" + tsOld; List betaIpsWithOldTs = Arrays.asList("127.0.0.1", "127.0.0.2", "127.0.0.4"); - boolean resultOld = ConfigCacheService.dumpBeta(dataId, group, tenant, contentWithOldTs, tsOld, - String.join(",", betaIpsWithOldTs), encryptedDataKey); - Assert.assertTrue(resultOld); - Assert.assertEquals(md5New, contentCache.getConfigCacheBeta().getMd5Utf8()); - Assert.assertEquals(tsNew, contentCache.getConfigCacheBeta().getLastModifiedTs()); - Assert.assertEquals(encryptedDataKey, contentCache.getConfigCacheBeta().getEncryptedDataKey()); - Assert.assertEquals(betaIpsNew, contentCache.getIps4Beta()); - Mockito.verify(configDiskService, times(0)) - .saveBetaToDisk(eq(dataId), eq(group), eq(tenant), eq(contentWithOldTs)); + boolean resultOld = ConfigCacheService.dumpBeta(dataId, group, tenant, contentWithOldTs, tsOld, String.join(",", betaIpsWithOldTs), + encryptedDataKey); + assertTrue(resultOld); + assertEquals(md5New, contentCache.getConfigCacheBeta().getMd5Utf8()); + assertEquals(tsNew, contentCache.getConfigCacheBeta().getLastModifiedTs()); + assertEquals(encryptedDataKey, contentCache.getConfigCacheBeta().getEncryptedDataKey()); + assertEquals(betaIpsNew, contentCache.getIps4Beta()); + Mockito.verify(configDiskService, times(0)).saveBetaToDisk(eq(dataId), eq(group), eq(tenant), eq(contentWithOldTs)); //ts new ,md5 not update,beta ips list changes long tsNew2 = tsNew + 1; String contentWithPrev = contentNew; List betaIpsNew2 = Arrays.asList("127.0.0.1", "127.0.0.2", "127.0.0.4", "127.0.0.5"); - boolean resultNew2 = ConfigCacheService.dumpBeta(dataId, group, tenant, contentWithPrev, tsNew2, - String.join(",", betaIpsNew2), encryptedDataKey); - Assert.assertTrue(resultNew2); - Assert.assertEquals(md5New, contentCache.getConfigCacheBeta().getMd5Utf8()); - Assert.assertEquals(tsNew2, contentCache.getConfigCacheBeta().getLastModifiedTs()); - Assert.assertEquals(encryptedDataKey, contentCache.getConfigCacheBeta().getEncryptedDataKey()); - Assert.assertEquals(betaIpsNew2, contentCache.getIps4Beta()); + boolean resultNew2 = ConfigCacheService.dumpBeta(dataId, group, tenant, contentWithPrev, tsNew2, String.join(",", betaIpsNew2), + encryptedDataKey); + assertTrue(resultNew2); + assertEquals(md5New, contentCache.getConfigCacheBeta().getMd5Utf8()); + assertEquals(tsNew2, contentCache.getConfigCacheBeta().getLastModifiedTs()); + assertEquals(encryptedDataKey, contentCache.getConfigCacheBeta().getEncryptedDataKey()); + assertEquals(betaIpsNew2, contentCache.getIps4Beta()); //ts new only,md5 not update,beta ips not change long tsNew3 = tsNew2 + 1; String contentWithPrev2 = contentNew; List betaIpsNew3 = betaIpsNew2; - boolean resultNew3 = ConfigCacheService.dumpBeta(dataId, group, tenant, contentWithPrev2, tsNew3, - String.join(",", betaIpsNew3), encryptedDataKey); - Assert.assertTrue(resultNew3); - Assert.assertEquals(md5New, contentCache.getConfigCacheBeta().getMd5Utf8()); - Assert.assertEquals(tsNew3, contentCache.getConfigCacheBeta().getLastModifiedTs()); - Assert.assertEquals(encryptedDataKey, contentCache.getConfigCacheBeta().getEncryptedDataKey()); - Assert.assertEquals(betaIpsNew2, contentCache.getIps4Beta()); + boolean resultNew3 = ConfigCacheService.dumpBeta(dataId, group, tenant, contentWithPrev2, tsNew3, String.join(",", betaIpsNew3), + encryptedDataKey); + assertTrue(resultNew3); + assertEquals(md5New, contentCache.getConfigCacheBeta().getMd5Utf8()); + assertEquals(tsNew3, contentCache.getConfigCacheBeta().getLastModifiedTs()); + assertEquals(encryptedDataKey, contentCache.getConfigCacheBeta().getEncryptedDataKey()); + assertEquals(betaIpsNew2, contentCache.getIps4Beta()); //ts not update,md5 not update,beta ips not change long tsNew4 = tsNew3; String contentWithPrev4 = contentNew; List betaIpsNew4 = betaIpsNew2; - boolean resultNew4 = ConfigCacheService.dumpBeta(dataId, group, tenant, contentWithPrev4, tsNew4, - String.join(",", betaIpsNew4), encryptedDataKey); - Assert.assertTrue(resultNew4); - Assert.assertEquals(md5New, contentCache.getConfigCacheBeta().getMd5Utf8()); - Assert.assertEquals(tsNew3, contentCache.getConfigCacheBeta().getLastModifiedTs()); - Assert.assertEquals(encryptedDataKey, contentCache.getConfigCacheBeta().getEncryptedDataKey()); - Assert.assertEquals(betaIpsNew4, contentCache.getIps4Beta()); + boolean resultNew4 = ConfigCacheService.dumpBeta(dataId, group, tenant, contentWithPrev4, tsNew4, String.join(",", betaIpsNew4), + encryptedDataKey); + assertTrue(resultNew4); + assertEquals(md5New, contentCache.getConfigCacheBeta().getMd5Utf8()); + assertEquals(tsNew3, contentCache.getConfigCacheBeta().getLastModifiedTs()); + assertEquals(encryptedDataKey, contentCache.getConfigCacheBeta().getEncryptedDataKey()); + assertEquals(betaIpsNew4, contentCache.getIps4Beta()); //test remove boolean removeBeta = ConfigCacheService.removeBeta(dataId, group, tenant); - Assert.assertTrue(removeBeta); + assertTrue(removeBeta); Mockito.verify(configDiskService, times(1)).removeConfigInfo4Beta(dataId, group, tenant); ConfigCache betaCacheAfterRemove = ConfigCacheService.getContentCache(groupKey).getConfigCacheBeta(); - Assert.assertNull(betaCacheAfterRemove); + assertNull(betaCacheAfterRemove); } @Test - public void testDumpTag() throws Exception { + void testDumpTag() throws Exception { String dataId = "dataIdtestDumpTag133323"; String group = "group11"; String tenant = "tenant112"; @@ -255,69 +253,63 @@ public void testDumpTag() throws Exception { //init dump tag boolean dumpTagResult = ConfigCacheService.dumpTag(dataId, group, tenant, tag, content, ts, encryptedDataKey); - Assert.assertTrue(dumpTagResult); - Mockito.verify(configDiskService, times(1)) - .saveTagToDisk(eq(dataId), eq(group), eq(tenant), eq(tag), eq(content)); + assertTrue(dumpTagResult); + Mockito.verify(configDiskService, times(1)).saveTagToDisk(eq(dataId), eq(group), eq(tenant), eq(tag), eq(content)); CacheItem contentCache = ConfigCacheService.getContentCache(groupKey); ConfigCache configCacheTag = contentCache.getConfigCacheTags().get(tag); - Assert.assertEquals(ts, configCacheTag.getLastModifiedTs()); + assertEquals(ts, configCacheTag.getLastModifiedTs()); String md5 = MD5Utils.md5Hex(content, "UTF-8"); - Assert.assertEquals(md5, configCacheTag.getMd5Utf8()); + assertEquals(md5, configCacheTag.getMd5Utf8()); //ts newer ,md5 update long tsNew = System.currentTimeMillis(); String contentNew = content + tsNew; String md5New = MD5Utils.md5Hex(contentNew, "UTF-8"); boolean resultNew = ConfigCacheService.dumpTag(dataId, group, tenant, tag, contentNew, tsNew, encryptedDataKey); - Assert.assertTrue(resultNew); - Assert.assertEquals(md5New, configCacheTag.getMd5Utf8()); - Assert.assertEquals(tsNew, configCacheTag.getLastModifiedTs()); - Assert.assertEquals(encryptedDataKey, configCacheTag.getEncryptedDataKey()); - Mockito.verify(configDiskService, times(1)) - .saveTagToDisk(eq(dataId), eq(group), eq(tenant), eq(tag), eq(contentNew)); + assertTrue(resultNew); + assertEquals(md5New, configCacheTag.getMd5Utf8()); + assertEquals(tsNew, configCacheTag.getLastModifiedTs()); + assertEquals(encryptedDataKey, configCacheTag.getEncryptedDataKey()); + Mockito.verify(configDiskService, times(1)).saveTagToDisk(eq(dataId), eq(group), eq(tenant), eq(tag), eq(contentNew)); //ts old ,md5 update long tsOld = tsNew - 1; String contentWithOldTs = "contentWithOldTs" + tsOld; - boolean resultOld = ConfigCacheService.dumpTag(dataId, group, tenant, tag, contentWithOldTs, tsOld, - encryptedDataKey); - Assert.assertTrue(resultOld); - Assert.assertEquals(md5New, configCacheTag.getMd5Utf8()); - Assert.assertEquals(tsNew, configCacheTag.getLastModifiedTs()); - Assert.assertEquals(encryptedDataKey, configCacheTag.getEncryptedDataKey()); - Mockito.verify(configDiskService, times(0)) - .saveTagToDisk(eq(dataId), eq(group), eq(tenant), eq(tag), eq(contentWithOldTs)); + boolean resultOld = ConfigCacheService.dumpTag(dataId, group, tenant, tag, contentWithOldTs, tsOld, encryptedDataKey); + assertTrue(resultOld); + assertEquals(md5New, configCacheTag.getMd5Utf8()); + assertEquals(tsNew, configCacheTag.getLastModifiedTs()); + assertEquals(encryptedDataKey, configCacheTag.getEncryptedDataKey()); + Mockito.verify(configDiskService, times(0)).saveTagToDisk(eq(dataId), eq(group), eq(tenant), eq(tag), eq(contentWithOldTs)); //ts new only,md5 not update long tsNew2 = tsNew + 1; String contentWithPrev2 = contentNew; - boolean resultNew2 = ConfigCacheService.dumpTag(dataId, group, tenant, tag, contentWithPrev2, tsNew2, - encryptedDataKey); - Assert.assertTrue(resultNew2); - Assert.assertEquals(md5New, configCacheTag.getMd5Utf8()); - Assert.assertEquals(tsNew2, configCacheTag.getLastModifiedTs()); - Assert.assertEquals(encryptedDataKey, configCacheTag.getEncryptedDataKey()); + boolean resultNew2 = ConfigCacheService.dumpTag(dataId, group, tenant, tag, contentWithPrev2, tsNew2, encryptedDataKey); + assertTrue(resultNew2); + assertEquals(md5New, configCacheTag.getMd5Utf8()); + assertEquals(tsNew2, configCacheTag.getLastModifiedTs()); + assertEquals(encryptedDataKey, configCacheTag.getEncryptedDataKey()); //ts not update,md5 not update long tsNew3 = tsNew2; String contentWithPrev3 = contentNew; - boolean resultNew3 = ConfigCacheService.dumpTag(dataId, group, tenant, tag, contentWithPrev3, tsNew3, - encryptedDataKey); - Assert.assertTrue(resultNew3); - Assert.assertEquals(md5New, configCacheTag.getMd5Utf8()); - Assert.assertEquals(tsNew3, configCacheTag.getLastModifiedTs()); - Assert.assertEquals(encryptedDataKey, configCacheTag.getEncryptedDataKey()); + boolean resultNew3 = ConfigCacheService.dumpTag(dataId, group, tenant, tag, contentWithPrev3, tsNew3, encryptedDataKey); + assertTrue(resultNew3); + assertEquals(md5New, configCacheTag.getMd5Utf8()); + assertEquals(tsNew3, configCacheTag.getLastModifiedTs()); + assertEquals(encryptedDataKey, configCacheTag.getEncryptedDataKey()); //test remove boolean removeTag = ConfigCacheService.removeTag(dataId, group, tenant, tag); - Assert.assertTrue(removeTag); + assertTrue(removeTag); Mockito.verify(configDiskService, times(1)).removeConfigInfo4Tag(dataId, group, tenant, tag); Map configCacheTags = ConfigCacheService.getContentCache(groupKey).getConfigCacheTags(); - Assert.assertNull(configCacheTags); + assertNull(configCacheTags); } @Test - public void testTryConfigReadLock() throws Exception { + void testTryConfigReadLock() throws Exception { String dataId = "123testTryConfigReadLock"; String group = "1234"; String tenant = "1234"; @@ -332,12 +324,12 @@ public void testTryConfigReadLock() throws Exception { // lock ==0,not exist int readLock = ConfigCacheService.tryConfigReadLock(groupKey + "3245"); - Assert.assertEquals(0, readLock); + assertEquals(0, readLock); //lock == 1 , success get lock Mockito.when(lock.tryReadLock()).thenReturn(true); int readLockSuccess = ConfigCacheService.tryConfigReadLock(groupKey); - Assert.assertEquals(1, readLockSuccess); + assertEquals(1, readLockSuccess); //lock ==-1 fail after spin all times; OngoingStubbing when = Mockito.when(lock.tryReadLock()); @@ -345,7 +337,7 @@ public void testTryConfigReadLock() throws Exception { when = when.thenReturn(false); } int readLockFail = ConfigCacheService.tryConfigReadLock(groupKey); - Assert.assertEquals(-1, readLockFail); + assertEquals(-1, readLockFail); //lock ==1 success after serval spin times; OngoingStubbing when2 = Mockito.when(lock.tryReadLock()); @@ -354,6 +346,6 @@ public void testTryConfigReadLock() throws Exception { } when2.thenReturn(true); int readLockSuccessAfterRetry = ConfigCacheService.tryConfigReadLock(groupKey); - Assert.assertEquals(1, readLockSuccessAfterRetry); + assertEquals(1, readLockSuccessAfterRetry); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/ConfigChangePublisherTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/ConfigChangePublisherTest.java index 6e3f464567b..79f4e065631 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/ConfigChangePublisherTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/ConfigChangePublisherTest.java @@ -22,23 +22,25 @@ import com.alibaba.nacos.config.server.model.event.ConfigDataChangeEvent; import com.alibaba.nacos.persistence.configuration.DatasourceConfiguration; import com.alibaba.nacos.sys.env.EnvUtil; -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.util.concurrent.atomic.AtomicReference; -public class ConfigChangePublisherTest { +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +class ConfigChangePublisherTest { - @Before - public void startUP() { + @BeforeEach + void startUP() { EnvUtil.setIsStandalone(true); DatasourceConfiguration.setEmbeddedStorage(true); } @Test - public void testConfigChangeNotify() throws InterruptedException { + void testConfigChangeNotify() throws InterruptedException { AtomicReference reference = new AtomicReference<>(); @@ -60,43 +62,39 @@ public Class subscribeType() { EnvUtil.setIsStandalone(true); DatasourceConfiguration.setEmbeddedStorage(true); - ConfigChangePublisher - .notifyConfigChange(new ConfigDataChangeEvent("chuntaojun", "chuntaojun", System.currentTimeMillis())); + ConfigChangePublisher.notifyConfigChange(new ConfigDataChangeEvent("chuntaojun", "chuntaojun", System.currentTimeMillis())); Thread.sleep(2000); - Assert.assertNotNull(reference.get()); + assertNotNull(reference.get()); reference.set(null); // nacos is standalone mode and use external storage EnvUtil.setIsStandalone(true); DatasourceConfiguration.setEmbeddedStorage(false); - ConfigChangePublisher - .notifyConfigChange(new ConfigDataChangeEvent("chuntaojun", "chuntaojun", System.currentTimeMillis())); + ConfigChangePublisher.notifyConfigChange(new ConfigDataChangeEvent("chuntaojun", "chuntaojun", System.currentTimeMillis())); Thread.sleep(2000); - Assert.assertNotNull(reference.get()); + assertNotNull(reference.get()); reference.set(null); // nacos is cluster mode and use embedded storage EnvUtil.setIsStandalone(false); DatasourceConfiguration.setEmbeddedStorage(true); - ConfigChangePublisher - .notifyConfigChange(new ConfigDataChangeEvent("chuntaojun", "chuntaojun", System.currentTimeMillis())); + ConfigChangePublisher.notifyConfigChange(new ConfigDataChangeEvent("chuntaojun", "chuntaojun", System.currentTimeMillis())); Thread.sleep(2000); - Assert.assertNull(reference.get()); + assertNull(reference.get()); reference.set(null); // nacos is cluster mode and use external storage EnvUtil.setIsStandalone(false); DatasourceConfiguration.setEmbeddedStorage(false); - ConfigChangePublisher - .notifyConfigChange(new ConfigDataChangeEvent("chuntaojun", "chuntaojun", System.currentTimeMillis())); + ConfigChangePublisher.notifyConfigChange(new ConfigDataChangeEvent("chuntaojun", "chuntaojun", System.currentTimeMillis())); Thread.sleep(2000); - Assert.assertNotNull(reference.get()); + assertNotNull(reference.get()); reference.set(null); - + } - @After - public void tearDown() { + @AfterEach + void tearDown() { EnvUtil.setIsStandalone(true); DatasourceConfiguration.setEmbeddedStorage(true); } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/ConfigOperationServiceTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/ConfigOperationServiceTest.java index c23aedaf9f0..7451b7214dc 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/ConfigOperationServiceTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/ConfigOperationServiceTest.java @@ -25,14 +25,14 @@ import com.alibaba.nacos.config.server.service.repository.ConfigInfoPersistService; import com.alibaba.nacos.config.server.service.repository.ConfigInfoTagPersistService; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.core.env.StandardEnvironment; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; @@ -45,8 +45,8 @@ * @date 2022/8/11 */ -@RunWith(MockitoJUnitRunner.class) -public class ConfigOperationServiceTest { +@ExtendWith(MockitoExtension.class) +class ConfigOperationServiceTest { private ConfigOperationService configOperationService; @@ -59,15 +59,15 @@ public class ConfigOperationServiceTest { @Mock private ConfigInfoBetaPersistService configInfoBetaPersistService; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { EnvUtil.setEnvironment(new StandardEnvironment()); this.configOperationService = new ConfigOperationService(configInfoPersistService, configInfoTagPersistService, configInfoBetaPersistService); } @Test - public void testPublishConfig() throws NacosException { + void testPublishConfig() throws NacosException { ConfigForm configForm = new ConfigForm(); configForm.setDataId("test"); configForm.setGroup("test"); @@ -76,72 +76,67 @@ public void testPublishConfig() throws NacosException { ConfigRequestInfo configRequestInfo = new ConfigRequestInfo(); // if betaIps is blank, tag is blank and casMd5 is blank - when(configInfoPersistService.insertOrUpdate(any(), any(), any(ConfigInfo.class), any())).thenReturn( - new ConfigOperateResult()); + when(configInfoPersistService.insertOrUpdate(any(), any(), any(ConfigInfo.class), any())).thenReturn(new ConfigOperateResult()); Boolean aResult = configOperationService.publishConfig(configForm, configRequestInfo, ""); verify(configInfoPersistService).insertOrUpdate(any(), any(), any(ConfigInfo.class), any()); - Assert.assertEquals(true, aResult); + assertTrue(aResult); // if betaIps is blank, tag is blank and casMd5 is not blank configRequestInfo.setCasMd5("test casMd5"); - when(configInfoPersistService.insertOrUpdateCas(any(), any(), any(ConfigInfo.class), any())).thenReturn( - new ConfigOperateResult()); + when(configInfoPersistService.insertOrUpdateCas(any(), any(), any(ConfigInfo.class), any())).thenReturn(new ConfigOperateResult()); Boolean bResult = configOperationService.publishConfig(configForm, configRequestInfo, ""); verify(configInfoPersistService).insertOrUpdateCas(any(), any(), any(ConfigInfo.class), any()); - Assert.assertEquals(true, bResult); + assertTrue(bResult); configRequestInfo.setCasMd5(""); // if betaIps is blank, tag is not blank and casMd5 is blank configForm.setTag("test tag"); - when(configInfoTagPersistService.insertOrUpdateTag(any(ConfigInfo.class), eq("test tag"), any(), - any())).thenReturn(new ConfigOperateResult()); + when(configInfoTagPersistService.insertOrUpdateTag(any(ConfigInfo.class), eq("test tag"), any(), any())).thenReturn( + new ConfigOperateResult()); Boolean cResult = configOperationService.publishConfig(configForm, configRequestInfo, ""); verify(configInfoTagPersistService).insertOrUpdateTag(any(ConfigInfo.class), eq("test tag"), any(), any()); - Assert.assertEquals(true, cResult); + assertTrue(cResult); // if betaIps is blank, tag is not blank and casMd5 is not blank configForm.setTag("test tag"); configRequestInfo.setCasMd5("test casMd5"); - when(configInfoTagPersistService.insertOrUpdateTagCas(any(ConfigInfo.class), eq("test tag"), any(), - any())).thenReturn(new ConfigOperateResult()); + when(configInfoTagPersistService.insertOrUpdateTagCas(any(ConfigInfo.class), eq("test tag"), any(), any())).thenReturn( + new ConfigOperateResult()); Boolean dResult = configOperationService.publishConfig(configForm, configRequestInfo, ""); verify(configInfoTagPersistService).insertOrUpdateTagCas(any(ConfigInfo.class), eq("test tag"), any(), any()); - Assert.assertEquals(true, dResult); + assertTrue(dResult); configRequestInfo.setCasMd5(""); configForm.setTag(""); // if betaIps is not blank and casMd5 is blank configRequestInfo.setBetaIps("test-betaIps"); - when(configInfoBetaPersistService.insertOrUpdateBeta(any(ConfigInfo.class), eq("test-betaIps"), any(), - any())).thenReturn(new ConfigOperateResult()); + when(configInfoBetaPersistService.insertOrUpdateBeta(any(ConfigInfo.class), eq("test-betaIps"), any(), any())).thenReturn( + new ConfigOperateResult()); Boolean eResult = configOperationService.publishConfig(configForm, configRequestInfo, ""); - verify(configInfoBetaPersistService).insertOrUpdateBeta(any(ConfigInfo.class), eq("test-betaIps"), any(), - any()); - Assert.assertEquals(true, eResult); + verify(configInfoBetaPersistService).insertOrUpdateBeta(any(ConfigInfo.class), eq("test-betaIps"), any(), any()); + assertTrue(eResult); // if betaIps is not blank and casMd5 is not blank configRequestInfo.setBetaIps("test-betaIps"); configRequestInfo.setCasMd5("test casMd5"); - when(configInfoBetaPersistService.insertOrUpdateBetaCas(any(ConfigInfo.class), eq("test-betaIps"), any(), - any())).thenReturn(new ConfigOperateResult()); + when(configInfoBetaPersistService.insertOrUpdateBetaCas(any(ConfigInfo.class), eq("test-betaIps"), any(), any())).thenReturn( + new ConfigOperateResult()); Boolean fResult = configOperationService.publishConfig(configForm, configRequestInfo, ""); - verify(configInfoBetaPersistService).insertOrUpdateBetaCas(any(ConfigInfo.class), eq("test-betaIps"), any(), - any()); - Assert.assertEquals(true, fResult); + verify(configInfoBetaPersistService).insertOrUpdateBetaCas(any(ConfigInfo.class), eq("test-betaIps"), any(), any()); + assertTrue(fResult); } @Test - public void testDeleteConfig() { + void testDeleteConfig() { // if tag is blank Boolean aResult = configOperationService.deleteConfig("test", "test", "", "", "1.1.1.1", "test"); verify(configInfoPersistService).removeConfigInfo(eq("test"), eq("test"), eq(""), any(), any()); - Assert.assertEquals(true, aResult); + assertTrue(aResult); // if tag is not blank Boolean bResult = configOperationService.deleteConfig("test", "test", "", "test", "1.1.1.1", "test"); - verify(configInfoTagPersistService) - .removeConfigInfoTag(eq("test"), eq("test"), eq(""), eq("test"), any(), any()); - Assert.assertEquals(true, bResult); + verify(configInfoTagPersistService).removeConfigInfoTag(eq("test"), eq("test"), eq(""), eq("test"), any(), any()); + assertTrue(bResult); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/ConfigSubServiceTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/ConfigSubServiceTest.java index a83cc60f358..e6494a6f3f5 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/ConfigSubServiceTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/ConfigSubServiceTest.java @@ -29,16 +29,15 @@ import com.alibaba.nacos.core.cluster.Member; import com.alibaba.nacos.core.cluster.ServerMemberManager; import com.alibaba.nacos.sys.env.EnvUtil; -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.springframework.core.env.ConfigurableEnvironment; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.ArrayList; import java.util.HashMap; @@ -48,15 +47,17 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +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.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; -@RunWith(SpringJUnit4ClassRunner.class) -public class ConfigSubServiceTest { - - private ConfigSubService configSubService; +@ExtendWith(SpringExtension.class) +class ConfigSubServiceTest { @Mock ServerMemberManager serverMemberManager; @@ -71,8 +72,10 @@ public class ConfigSubServiceTest { @Mock NacosAsyncRestTemplate nacosAsyncRestTemplate; - @Before - public void startUP() { + private ConfigSubService configSubService; + + @BeforeEach + void startUP() { httpClientManagerMockedStatic = Mockito.mockStatic(HttpClientManager.class); envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); @@ -80,14 +83,12 @@ public void startUP() { envUtilMockedStatic.when(() -> EnvUtil.getContextPath()).thenReturn("/nacos"); envUtilMockedStatic.when(() -> EnvUtil.getProperty(anyString(), anyString())).thenReturn("mock string"); EnvUtil.setContextPath("/nacos"); - httpClientManagerMockedStatic.when(() -> HttpClientManager.getNacosRestTemplate()) - .thenReturn(nacosRestTemplate); - httpClientManagerMockedStatic.when(() -> HttpClientManager.getNacosAsyncRestTemplate()) - .thenReturn(nacosAsyncRestTemplate); + httpClientManagerMockedStatic.when(() -> HttpClientManager.getNacosRestTemplate()).thenReturn(nacosRestTemplate); + httpClientManagerMockedStatic.when(() -> HttpClientManager.getNacosAsyncRestTemplate()).thenReturn(nacosAsyncRestTemplate); } - @After - public void after() { + @AfterEach + void after() { if (!envUtilMockedStatic.isClosed()) { envUtilMockedStatic.close(); } @@ -95,7 +96,7 @@ public void after() { } @Test - public void testGetCollectSampleResult() throws Exception { + void testGetCollectSampleResult() throws Exception { envUtilMockedStatic.close(); EnvUtil.setContextPath("/nacos"); ConfigurableEnvironment environment = Mockito.mock(ConfigurableEnvironment.class); @@ -120,7 +121,7 @@ public void testGetCollectSampleResult() throws Exception { } @Test - public void testRunSingleJob() throws Exception { + void testRunSingleJob() throws Exception { Map params = new HashMap<>(); params.put("dataId", "d1"); params.put("group", "g1"); @@ -138,31 +139,26 @@ public void testRunSingleJob() throws Exception { String mockJsonString = JacksonUtils.toJson(sampleResult1); httpRestResult.setData(mockJsonString); //mock success - Mockito.when(nacosRestTemplate.get(anyString(), any(Header.class), eq(Query.EMPTY), eq(String.class))) - .thenReturn(httpRestResult); + Mockito.when(nacosRestTemplate.get(anyString(), any(Header.class), eq(Query.EMPTY), eq(String.class))).thenReturn(httpRestResult); String url = "url"; - SampleResult returnObj = (SampleResult) ConfigSubService.runSingleJob("127.0.0.1", params, url, - SampleResult.class); - Assert.assertEquals(sampleResult1.getLisentersGroupkeyStatus(), returnObj.getLisentersGroupkeyStatus()); + SampleResult returnObj = (SampleResult) ConfigSubService.runSingleJob("127.0.0.1", params, url, SampleResult.class); + assertEquals(sampleResult1.getLisentersGroupkeyStatus(), returnObj.getLisentersGroupkeyStatus()); //mock fail response httpRestResult.setCode(500); - Mockito.when(nacosRestTemplate.get(anyString(), any(Header.class), eq(Query.EMPTY), eq(String.class))) - .thenReturn(httpRestResult); - SampleResult returnObj500 = (SampleResult) ConfigSubService.runSingleJob("127.0.0.1", params, url, - SampleResult.class); - Assert.assertEquals(null, returnObj500); + Mockito.when(nacosRestTemplate.get(anyString(), any(Header.class), eq(Query.EMPTY), eq(String.class))).thenReturn(httpRestResult); + SampleResult returnObj500 = (SampleResult) ConfigSubService.runSingleJob("127.0.0.1", params, url, SampleResult.class); + assertNull(returnObj500); //mock get url throw exception Mockito.when(nacosRestTemplate.get(anyString(), any(Header.class), eq(Query.EMPTY), eq(String.class))) .thenThrow(new NacosRuntimeException(500, "timeout")); - SampleResult returnObjTimeout = (SampleResult) ConfigSubService.runSingleJob("127.0.0.1", params, url, - SampleResult.class); - Assert.assertEquals(null, returnObjTimeout); + SampleResult returnObjTimeout = (SampleResult) ConfigSubService.runSingleJob("127.0.0.1", params, url, SampleResult.class); + assertNull(returnObjTimeout); } @Test - public void testClusterListenerJob() throws Exception { + void testClusterListenerJob() throws Exception { Map mockedMembers = new HashMap<>(); mockedMembers.put("127.0.0.1", createMember("127.0.0.1")); mockedMembers.put("127.0.0.2", createMember("127.0.0.2")); @@ -177,26 +173,26 @@ public void testClusterListenerJob() throws Exception { .thenReturn(createSampleResultFuture(true, true), createSampleResultFuture(true, true), createSampleResultFuture(true, true)); Map params = new HashMap<>(); - ConfigSubService.ClusterListenerJob clusterListenerJob = new ConfigSubService.ClusterListenerJob(params, - mockService, serverMemberManager); + ConfigSubService.ClusterListenerJob clusterListenerJob = new ConfigSubService.ClusterListenerJob(params, mockService, + serverMemberManager); List sampleResults = clusterListenerJob.runJobs(); - Assert.assertEquals(3, sampleResults.size()); + assertEquals(3, sampleResults.size()); //mock success with exception Mockito.when(mockService.poll(anyLong(), any(TimeUnit.class))) .thenReturn(createSampleResultFuture(true, true), createSampleResultFuture(false, false)) .thenThrow(new NacosRuntimeException(500, "13")); Map params2 = new HashMap<>(); - ConfigSubService.ClusterListenerJob clusterListenerJob2 = new ConfigSubService.ClusterListenerJob(params2, - mockService, serverMemberManager); + ConfigSubService.ClusterListenerJob clusterListenerJob2 = new ConfigSubService.ClusterListenerJob(params2, mockService, + serverMemberManager); List sampleResults2 = clusterListenerJob2.runJobs(); - Assert.assertEquals(1, sampleResults2.size()); - Assert.assertEquals(false, sampleResults2.get(0).getLisentersGroupkeyStatus().isEmpty()); + assertEquals(1, sampleResults2.size()); + assertFalse(sampleResults2.get(0).getLisentersGroupkeyStatus().isEmpty()); } @Test - public void testMergeSampleResult() throws Exception { + void testMergeSampleResult() throws Exception { SampleResult sampleResult1 = new SampleResult(); Map listener1 = new HashMap<>(); listener1.put("config1", "md51123"); @@ -217,14 +213,14 @@ public void testMergeSampleResult() throws Exception { sampleResults.add(sampleResult3); //sampleResult ips is null SampleResult sampleResultMerge1 = configSubService.mergeSampleResult(sampleResult1, sampleResults); - Assert.assertEquals(6, sampleResultMerge1.getLisentersGroupkeyStatus().size()); + assertEquals(6, sampleResultMerge1.getLisentersGroupkeyStatus().size()); SampleResult sampleResultMerge2 = configSubService.mergeSampleResult(new SampleResult(), sampleResults); - Assert.assertEquals(4, sampleResultMerge2.getLisentersGroupkeyStatus().size()); + assertEquals(4, sampleResultMerge2.getLisentersGroupkeyStatus().size()); } @Test - public void testMergeListenerCheckResult() throws Exception { + void testMergeListenerCheckResult() throws Exception { ListenerCheckResult sampleResult2 = new ListenerCheckResult(); sampleResult2.setHasListener(true); sampleResult2.setCode(200); @@ -236,18 +232,16 @@ public void testMergeListenerCheckResult() throws Exception { sampleResults.add(sampleResult3); ListenerCheckResult sampleResult1 = new ListenerCheckResult(); //one ip return true - ListenerCheckResult sampleResultMerge1 = configSubService.mergeListenerCheckResult(sampleResult1, sampleResults, - 2); - Assert.assertEquals(200, sampleResultMerge1.getCode()); - Assert.assertEquals(true, sampleResultMerge1.isHasListener()); + ListenerCheckResult sampleResultMerge1 = configSubService.mergeListenerCheckResult(sampleResult1, sampleResults, 2); + assertEquals(200, sampleResultMerge1.getCode()); + assertTrue(sampleResultMerge1.isHasListener()); //all ip return false,but not equals member size sampleResult2.setHasListener(false); sampleResult3.setHasListener(false); sampleResult1.setHasListener(false); - ListenerCheckResult sampleResultMerge2 = configSubService.mergeListenerCheckResult(sampleResult1, sampleResults, - 3); - Assert.assertEquals(201, sampleResultMerge2.getCode()); - Assert.assertEquals(false, sampleResultMerge2.isHasListener()); + ListenerCheckResult sampleResultMerge2 = configSubService.mergeListenerCheckResult(sampleResult1, sampleResults, 3); + assertEquals(201, sampleResultMerge2.getCode()); + assertFalse(sampleResultMerge2.isHasListener()); } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/HistoryServiceTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/HistoryServiceTest.java index e3e656f80e0..0d2b29e8f7c 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/HistoryServiceTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/HistoryServiceTest.java @@ -18,14 +18,14 @@ import com.alibaba.nacos.config.server.model.ConfigHistoryInfo; import com.alibaba.nacos.config.server.model.ConfigInfoWrapper; -import com.alibaba.nacos.persistence.model.Page; import com.alibaba.nacos.config.server.service.repository.ConfigInfoPersistService; import com.alibaba.nacos.config.server.service.repository.HistoryConfigInfoPersistService; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import com.alibaba.nacos.persistence.model.Page; +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.sql.Timestamp; import java.util.ArrayList; @@ -33,26 +33,19 @@ import java.util.Date; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * HistoryServiceTest. + * * @author dongyafei * @date 2022/8/11 */ -@RunWith(MockitoJUnitRunner.class) -public class HistoryServiceTest { - - private HistoryService historyService; - - @Mock - private HistoryConfigInfoPersistService historyConfigInfoPersistService; - - @Mock - private ConfigInfoPersistService configInfoPersistService; +@ExtendWith(MockitoExtension.class) +class HistoryServiceTest { private static final String TEST_DATA_ID = "test"; @@ -62,13 +55,21 @@ public class HistoryServiceTest { private static final String TEST_CONTENT = "test config"; - @Before - public void setUp() throws Exception { + private HistoryService historyService; + + @Mock + private HistoryConfigInfoPersistService historyConfigInfoPersistService; + + @Mock + private ConfigInfoPersistService configInfoPersistService; + + @BeforeEach + void setUp() throws Exception { this.historyService = new HistoryService(historyConfigInfoPersistService, configInfoPersistService); } @Test - public void testListConfigHistory() { + void testListConfigHistory() { ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo(); configHistoryInfo.setDataId(TEST_DATA_ID); configHistoryInfo.setGroup(TEST_GROUP); @@ -77,23 +78,22 @@ public void testListConfigHistory() { configHistoryInfo.setLastModifiedTime(new Timestamp(new Date().getTime())); List configHistoryInfoList = new ArrayList<>(); configHistoryInfoList.add(configHistoryInfo); - + Page page = new Page<>(); page.setTotalCount(15); page.setPageNumber(1); page.setPagesAvailable(2); page.setPageItems(configHistoryInfoList); - + when(historyConfigInfoPersistService.findConfigHistory(TEST_DATA_ID, TEST_GROUP, TEST_TENANT, 1, 10)).thenReturn(page); - - Page pageResult = historyService - .listConfigHistory(TEST_DATA_ID, TEST_GROUP, TEST_TENANT, 1, 10); - + + Page pageResult = historyService.listConfigHistory(TEST_DATA_ID, TEST_GROUP, TEST_TENANT, 1, 10); + verify(historyConfigInfoPersistService).findConfigHistory(TEST_DATA_ID, TEST_GROUP, TEST_TENANT, 1, 10); - + List resultList = pageResult.getPageItems(); ConfigHistoryInfo resConfigHistoryInfo = resultList.get(0); - + assertEquals(configHistoryInfoList.size(), resultList.size()); assertEquals(configHistoryInfo.getDataId(), resConfigHistoryInfo.getDataId()); assertEquals(configHistoryInfo.getGroup(), resConfigHistoryInfo.getGroup()); @@ -101,7 +101,7 @@ public void testListConfigHistory() { } @Test - public void testGetConfigHistoryInfo() throws Exception { + void testGetConfigHistoryInfo() throws Exception { ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo(); configHistoryInfo.setDataId(TEST_DATA_ID); @@ -113,8 +113,7 @@ public void testGetConfigHistoryInfo() throws Exception { when(historyConfigInfoPersistService.detailConfigHistory(1L)).thenReturn(configHistoryInfo); - ConfigHistoryInfo resConfigHistoryInfo = historyService - .getConfigHistoryInfo(TEST_DATA_ID, TEST_GROUP, TEST_TENANT, 1L); + ConfigHistoryInfo resConfigHistoryInfo = historyService.getConfigHistoryInfo(TEST_DATA_ID, TEST_GROUP, TEST_TENANT, 1L); verify(historyConfigInfoPersistService).detailConfigHistory(1L); @@ -125,7 +124,7 @@ public void testGetConfigHistoryInfo() throws Exception { } @Test - public void testGetPreviousConfigHistoryInfo() throws Exception { + void testGetPreviousConfigHistoryInfo() throws Exception { ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo(); configHistoryInfo.setDataId(TEST_DATA_ID); @@ -137,8 +136,7 @@ public void testGetPreviousConfigHistoryInfo() throws Exception { when(historyConfigInfoPersistService.detailPreviousConfigHistory(1L)).thenReturn(configHistoryInfo); - ConfigHistoryInfo resConfigHistoryInfo = historyService - .getPreviousConfigHistoryInfo(TEST_DATA_ID, TEST_GROUP, TEST_TENANT, 1L); + ConfigHistoryInfo resConfigHistoryInfo = historyService.getPreviousConfigHistoryInfo(TEST_DATA_ID, TEST_GROUP, TEST_TENANT, 1L); verify(historyConfigInfoPersistService).detailPreviousConfigHistory(1L); @@ -149,7 +147,7 @@ public void testGetPreviousConfigHistoryInfo() throws Exception { } @Test - public void testGetConfigListByNamespace() { + void testGetConfigListByNamespace() { ConfigInfoWrapper configInfoWrapper = new ConfigInfoWrapper(); configInfoWrapper.setDataId("test"); configInfoWrapper.setGroup("test"); @@ -157,7 +155,7 @@ public void testGetConfigListByNamespace() { List configInfoWrappers = Collections.singletonList(configInfoWrapper); when(configInfoPersistService.queryConfigInfoByNamespace("test")).thenReturn(configInfoWrappers); - + List actualList = historyService.getConfigListByNamespace("test"); verify(configInfoPersistService).queryConfigInfoByNamespace("test"); diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/LongPollingServiceTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/LongPollingServiceTest.java index c1c04529d06..79409b7cfa9 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/LongPollingServiceTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/LongPollingServiceTest.java @@ -26,15 +26,16 @@ import com.alibaba.nacos.plugin.control.ControlManagerCenter; import com.alibaba.nacos.plugin.control.connection.ConnectionControlManager; import com.alibaba.nacos.plugin.control.connection.response.ConnectionCheckResponse; -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 org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import javax.servlet.AsyncContext; import javax.servlet.http.HttpServletRequest; @@ -45,14 +46,18 @@ import java.util.HashMap; import java.util.Map; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; -@RunWith(MockitoJUnitRunner.class) -public class LongPollingServiceTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class LongPollingServiceTest { LongPollingService longPollingService; @@ -70,21 +75,20 @@ public class LongPollingServiceTest { MockedStatic switchServiceMockedStatic; - @Before - public void before() { + @BeforeEach + void before() { longPollingService = new LongPollingService(); switchServiceMockedStatic = Mockito.mockStatic(SwitchService.class); configCacheServiceMockedStatic = Mockito.mockStatic(ConfigCacheService.class); configExecutorMocked = Mockito.mockStatic(ConfigExecutor.class); connectionControlManagerMockedStatic = Mockito.mockStatic(ControlManagerCenter.class); - connectionControlManagerMockedStatic.when(() -> ControlManagerCenter.getInstance()) - .thenReturn(controlManagerCenter); + connectionControlManagerMockedStatic.when(() -> ControlManagerCenter.getInstance()).thenReturn(controlManagerCenter); Mockito.when(controlManagerCenter.getConnectionControlManager()).thenReturn(connectionControlManager); } - @After - public void after() { + @AfterEach + void after() { configCacheServiceMockedStatic.close(); if (!configExecutorMocked.isClosed()) { configExecutorMocked.close(); @@ -94,7 +98,7 @@ public void after() { } @Test - public void testAddLongPollingClientHasNotEqualsMd5() throws IOException { + void testAddLongPollingClientHasNotEqualsMd5() throws IOException { Map clientMd5Map = new HashMap<>(); String group = "group"; @@ -109,16 +113,13 @@ public void testAddLongPollingClientHasNotEqualsMd5() throws IOException { clientMd5Map.put(groupKeyNotEquals, md5NotEquals1); HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class); - Mockito.when(httpServletRequest.getHeader(eq(LongPollingService.LONG_POLLING_NO_HANG_UP_HEADER))) - .thenReturn(null); + Mockito.when(httpServletRequest.getHeader(eq(LongPollingService.LONG_POLLING_NO_HANG_UP_HEADER))).thenReturn(null); String clientIp = "192.168.0.1"; Mockito.when(httpServletRequest.getHeader(eq("X-Forwarded-For"))).thenReturn(clientIp); configCacheServiceMockedStatic.when( - () -> ConfigCacheService.isUptodate(eq(groupKeyNotEquals), eq(md5NotEquals1), eq(clientIp), eq(null))) - .thenReturn(false); - configCacheServiceMockedStatic.when( - () -> ConfigCacheService.isUptodate(eq(groupKeyEquals), eq(md5Equals0), eq(clientIp), eq(null))) + () -> ConfigCacheService.isUptodate(eq(groupKeyNotEquals), eq(md5NotEquals1), eq(clientIp), eq(null))).thenReturn(false); + configCacheServiceMockedStatic.when(() -> ConfigCacheService.isUptodate(eq(groupKeyEquals), eq(md5Equals0), eq(clientIp), eq(null))) .thenReturn(true); HttpServletResponse httpServletResponse = Mockito.mock(HttpServletResponse.class); PrintWriter printWriter = Mockito.mock(PrintWriter.class); @@ -134,7 +135,7 @@ public void testAddLongPollingClientHasNotEqualsMd5() throws IOException { } @Test - public void testRejectByConnectionLimit() throws Exception { + void testRejectByConnectionLimit() throws Exception { //mock connection no limit ConnectionCheckResponse connectionCheckResponse = new ConnectionCheckResponse(); connectionCheckResponse.setSuccess(false); @@ -144,8 +145,7 @@ public void testRejectByConnectionLimit() throws Exception { Mockito.when(httpServletResponse.getWriter()).thenReturn(printWriter); HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class); - Mockito.when(httpServletRequest.getHeader(eq(LongPollingService.LONG_POLLING_NO_HANG_UP_HEADER))) - .thenReturn(null); + Mockito.when(httpServletRequest.getHeader(eq(LongPollingService.LONG_POLLING_NO_HANG_UP_HEADER))).thenReturn(null); String clientIp = "192.168.0.1"; Mockito.when(httpServletRequest.getHeader(eq("X-Forwarded-For"))).thenReturn(clientIp); Mockito.when(httpServletRequest.startAsync()).thenReturn(Mockito.mock(AsyncContext.class)); @@ -159,7 +159,7 @@ public void testRejectByConnectionLimit() throws Exception { } @Test - public void testAddLongPollingClientAllEqualsMd5() throws IOException { + void testAddLongPollingClientAllEqualsMd5() throws IOException { //mock connection no limit ConnectionCheckResponse connectionCheckResponse = new ConnectionCheckResponse(); connectionCheckResponse.setSuccess(true); @@ -179,16 +179,13 @@ public void testAddLongPollingClientAllEqualsMd5() throws IOException { HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class); Mockito.when(httpServletRequest.getHeader(eq(LongPollingService.LONG_POLLING_HEADER))).thenReturn("5000"); - Mockito.when(httpServletRequest.getHeader(eq(LongPollingService.LONG_POLLING_NO_HANG_UP_HEADER))) - .thenReturn(null); + Mockito.when(httpServletRequest.getHeader(eq(LongPollingService.LONG_POLLING_NO_HANG_UP_HEADER))).thenReturn(null); String clientIp = "192.168.0.1"; Mockito.when(httpServletRequest.getHeader(eq("X-Forwarded-For"))).thenReturn(clientIp); Mockito.when(httpServletRequest.startAsync()).thenReturn(Mockito.mock(AsyncContext.class)); configCacheServiceMockedStatic.when( - () -> ConfigCacheService.isUptodate(eq(groupKeyNotEquals), eq(md5NotEquals1), eq(clientIp), eq(null))) - .thenReturn(true); - configCacheServiceMockedStatic.when( - () -> ConfigCacheService.isUptodate(eq(groupKeyEquals), eq(md5Equals0), eq(clientIp), eq(null))) + () -> ConfigCacheService.isUptodate(eq(groupKeyNotEquals), eq(md5NotEquals1), eq(clientIp), eq(null))).thenReturn(true); + configCacheServiceMockedStatic.when(() -> ConfigCacheService.isUptodate(eq(groupKeyEquals), eq(md5Equals0), eq(clientIp), eq(null))) .thenReturn(true); int propSize = 3; HttpServletResponse httpServletResponse = Mockito.mock(HttpServletResponse.class); @@ -197,13 +194,12 @@ public void testAddLongPollingClientAllEqualsMd5() throws IOException { //expect response not returned Mockito.verify(httpServletResponse, times(0)).setStatus(anyInt()); //expect to schedule a task - configExecutorMocked.verify( - () -> ConfigExecutor.executeLongPolling(any(LongPollingService.ClientLongPolling.class)), times(1)); + configExecutorMocked.verify(() -> ConfigExecutor.executeLongPolling(any(LongPollingService.ClientLongPolling.class)), times(1)); } @Test - public void testReceiveDataChangeEventAndNotify() throws Exception { + void testReceiveDataChangeEventAndNotify() throws Exception { configExecutorMocked.close(); //mock connection no limit @@ -223,8 +219,7 @@ public void testReceiveDataChangeEventAndNotify() throws Exception { Mockito.when(httpServletResponse.getWriter()).thenReturn(printWriter); Mockito.when(httpServletRequest.getHeader(eq(LongPollingService.LONG_POLLING_HEADER))).thenReturn("5000"); - Mockito.when(httpServletRequest.getHeader(eq(LongPollingService.LONG_POLLING_NO_HANG_UP_HEADER))) - .thenReturn(null); + Mockito.when(httpServletRequest.getHeader(eq(LongPollingService.LONG_POLLING_NO_HANG_UP_HEADER))).thenReturn(null); String clientIp = "192.168.0.1"; Mockito.when(httpServletRequest.getHeader(eq("X-Forwarded-For"))).thenReturn(clientIp); AsyncContext asyncContext = Mockito.mock(AsyncContext.class); @@ -232,20 +227,20 @@ public void testReceiveDataChangeEventAndNotify() throws Exception { Mockito.when(asyncContext.getRequest()).thenReturn(httpServletRequest); Mockito.when(asyncContext.getResponse()).thenReturn(httpServletResponse); - configCacheServiceMockedStatic.when( - () -> ConfigCacheService.isUptodate(anyString(), anyString(), anyString(), eq(null))).thenReturn(true); + configCacheServiceMockedStatic.when(() -> ConfigCacheService.isUptodate(anyString(), anyString(), anyString(), eq(null))) + .thenReturn(true); longPollingService.addLongPollingClient(httpServletRequest, httpServletResponse, clientMd5Map, 3); //test getSubscribleInfo by groupKey SampleResult subscribleInfo = longPollingService.getCollectSubscribleInfo(dataIdChanged, group, tenant); Map lisentersGroupkeyStatus = subscribleInfo.getLisentersGroupkeyStatus(); - Assert.assertFalse(lisentersGroupkeyStatus.isEmpty()); - Assert.assertEquals("mockMd5", lisentersGroupkeyStatus.get(clientIp)); + assertFalse(lisentersGroupkeyStatus.isEmpty()); + assertEquals("mockMd5", lisentersGroupkeyStatus.get(clientIp)); SampleResult collectSubscribleInfoByIp = longPollingService.getCollectSubscribleInfoByIp(clientIp); Map lisentersGroupkeyStatus1 = collectSubscribleInfoByIp.getLisentersGroupkeyStatus(); - Assert.assertFalse(lisentersGroupkeyStatus1.isEmpty()); - Assert.assertEquals("mockMd5", lisentersGroupkeyStatus1.get(groupKeyChanged)); + assertFalse(lisentersGroupkeyStatus1.isEmpty()); + assertEquals("mockMd5", lisentersGroupkeyStatus1.get(groupKeyChanged)); //test receive config change event LocalDataChangeEvent localDataChangeEvent = new LocalDataChangeEvent(groupKeyChanged); @@ -260,7 +255,7 @@ public void testReceiveDataChangeEventAndNotify() throws Exception { } @Test - public void testLongPollingTimeout() throws Exception { + void testLongPollingTimeout() throws Exception { configExecutorMocked.close(); String dataIdChanged = "dataIdChanged"; String group = "group"; @@ -274,21 +269,19 @@ public void testLongPollingTimeout() throws Exception { Map clientMd5Map = new HashMap<>(); clientMd5Map.put(groupKeyChanged, "md5"); - switchServiceMockedStatic.when(() -> SwitchService.getSwitchInteger(eq("MIN_LONG_POOLING_TIMEOUT"), eq(10000))) - .thenReturn(1000); + switchServiceMockedStatic.when(() -> SwitchService.getSwitchInteger(eq("MIN_LONG_POOLING_TIMEOUT"), eq(10000))).thenReturn(1000); HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class); Mockito.when(httpServletRequest.getHeader(eq(LongPollingService.LONG_POLLING_HEADER))).thenReturn("1000"); - Mockito.when(httpServletRequest.getHeader(eq(LongPollingService.LONG_POLLING_NO_HANG_UP_HEADER))) - .thenReturn(null); + Mockito.when(httpServletRequest.getHeader(eq(LongPollingService.LONG_POLLING_NO_HANG_UP_HEADER))).thenReturn(null); String clientIp = "192.168.0.1"; Mockito.when(httpServletRequest.getHeader(eq("X-Forwarded-For"))).thenReturn(clientIp); AsyncContext asyncContext = Mockito.mock(AsyncContext.class); Mockito.when(httpServletRequest.startAsync()).thenReturn(asyncContext); Mockito.when(asyncContext.getRequest()).thenReturn(httpServletRequest); - configCacheServiceMockedStatic.when( - () -> ConfigCacheService.isUptodate(anyString(), anyString(), anyString(), eq(null))).thenReturn(true); + configCacheServiceMockedStatic.when(() -> ConfigCacheService.isUptodate(anyString(), anyString(), anyString(), eq(null))) + .thenReturn(true); HttpServletResponse httpServletResponse = Mockito.mock(HttpServletResponse.class); longPollingService.addLongPollingClient(httpServletRequest, httpServletResponse, clientMd5Map, 3); diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/capacity/CapacityServiceTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/capacity/CapacityServiceTest.java index abd6d435cda..88396b71d4f 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/capacity/CapacityServiceTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/capacity/CapacityServiceTest.java @@ -22,31 +22,31 @@ import com.alibaba.nacos.config.server.model.capacity.TenantCapacity; import com.alibaba.nacos.config.server.service.repository.ConfigInfoPersistService; import com.alibaba.nacos.config.server.utils.PropertyUtil; -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.springframework.mock.web.MockServletContext; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.util.ReflectionTestUtils; import java.util.ArrayList; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; -@RunWith(SpringJUnit4ClassRunner.class) +@ExtendWith(SpringExtension.class) @ContextConfiguration(classes = MockServletContext.class) @WebAppConfiguration -public class CapacityServiceTest { +class CapacityServiceTest { private CapacityService service; @@ -59,8 +59,8 @@ public class CapacityServiceTest { @Mock private ConfigInfoPersistService configInfoPersistService; - @Before - public void setUp() { + @BeforeEach + void setUp() { service = new CapacityService(); ReflectionTestUtils.setField(service, "groupCapacityPersistService", groupCapacityPersistService); ReflectionTestUtils.setField(service, "tenantCapacityPersistService", tenantCapacityPersistService); @@ -68,12 +68,12 @@ public void setUp() { } @Test - public void testInit() { + void testInit() { service.init(); } @Test - public void testCorrectUsage() { + void testCorrectUsage() { List groupCapacityList = new ArrayList<>(); GroupCapacity groupCapacity = new GroupCapacity(); groupCapacity.setId(1L); @@ -104,21 +104,21 @@ public void testCorrectUsage() { } @Test - public void testCorrectGroupUsage() { + void testCorrectGroupUsage() { when(groupCapacityPersistService.correctUsage(eq("testGroup"), any())).thenReturn(true); service.correctGroupUsage("testGroup"); Mockito.verify(groupCapacityPersistService, times(1)).correctUsage(eq("testGroup"), any()); } @Test - public void testCorrectTenantUsage() { + void testCorrectTenantUsage() { when(tenantCapacityPersistService.correctUsage(eq("testTenant"), any())).thenReturn(true); service.correctTenantUsage("testTenant"); Mockito.verify(tenantCapacityPersistService, times(1)).correctUsage(eq("testTenant"), any()); } @Test - public void testInitAllCapacity() { + void testInitAllCapacity() { List groupList = new ArrayList<>(); groupList.add("testGroup"); when(configInfoPersistService.getGroupIdList(eq(1), eq(500))).thenReturn(groupList); @@ -152,7 +152,7 @@ public void testInitAllCapacity() { } @Test - public void testInsertAndUpdateClusterUsage() { + void testInsertAndUpdateClusterUsage() { when(groupCapacityPersistService.insertGroupCapacity(any())).thenReturn(true); when(groupCapacityPersistService.incrementUsage(any())).thenReturn(true); when(groupCapacityPersistService.incrementUsageWithDefaultQuotaLimit(any())).thenReturn(true); @@ -169,7 +169,7 @@ public void testInsertAndUpdateClusterUsage() { } @Test - public void testUpdateClusterUsage() { + void testUpdateClusterUsage() { when(groupCapacityPersistService.incrementUsageWithDefaultQuotaLimit(any())).thenReturn(true); when(groupCapacityPersistService.decrementUsage(any())).thenReturn(true); @@ -181,7 +181,7 @@ public void testUpdateClusterUsage() { } @Test - public void testInsertAndUpdateGroupUsage() { + void testInsertAndUpdateGroupUsage() { GroupCapacity groupCapacity = new GroupCapacity(); groupCapacity.setGroup("testGroup"); groupCapacity.setUsage(300); @@ -201,7 +201,7 @@ public void testInsertAndUpdateGroupUsage() { } @Test - public void testUpdateGroupUsage() { + void testUpdateGroupUsage() { when(groupCapacityPersistService.incrementUsageWithDefaultQuotaLimit(any())).thenReturn(true); when(groupCapacityPersistService.decrementUsage(any())).thenReturn(true); @@ -213,19 +213,19 @@ public void testUpdateGroupUsage() { } @Test - public void testGetGroupCapacity() { + void testGetGroupCapacity() { GroupCapacity groupCapacity = new GroupCapacity(); groupCapacity.setId(1L); groupCapacity.setGroup("testGroup"); when(groupCapacityPersistService.getGroupCapacity(eq("testGroup"))).thenReturn(groupCapacity); GroupCapacity resGroupCapacity = service.getGroupCapacity("testGroup"); - Assert.assertEquals(groupCapacity.getId(), resGroupCapacity.getId()); - Assert.assertEquals(groupCapacity.getGroup(), resGroupCapacity.getGroup()); + assertEquals(groupCapacity.getId(), resGroupCapacity.getId()); + assertEquals(groupCapacity.getGroup(), resGroupCapacity.getGroup()); } @Test - public void testInitGroupCapacity() { + void testInitGroupCapacity() { GroupCapacity groupCapacity = new GroupCapacity(); groupCapacity.setGroup("testGroup"); groupCapacity.setUsage(300); @@ -240,7 +240,7 @@ public void testInitGroupCapacity() { } @Test - public void testGetCapacity() { + void testGetCapacity() { GroupCapacity groupCapacity = new GroupCapacity(); groupCapacity.setId(1L); when(groupCapacityPersistService.getGroupCapacity(eq("testGroup"))).thenReturn(groupCapacity); @@ -250,14 +250,14 @@ public void testGetCapacity() { when(tenantCapacityPersistService.getTenantCapacity(eq("testTenant"))).thenReturn(tenantCapacity); Capacity resCapacity1 = service.getCapacity("testGroup", null); - Assert.assertEquals(1L, resCapacity1.getId().longValue()); + assertEquals(1L, resCapacity1.getId().longValue()); Capacity resCapacity2 = service.getCapacity(null, "testTenant"); - Assert.assertEquals(2L, resCapacity2.getId().longValue()); + assertEquals(2L, resCapacity2.getId().longValue()); } @Test - public void testGetCapacityWithDefault() { + void testGetCapacityWithDefault() { TenantCapacity tenantCapacity = new TenantCapacity(); tenantCapacity.setQuota(0); tenantCapacity.setMaxSize(0); @@ -274,17 +274,17 @@ public void testGetCapacityWithDefault() { //group is null Capacity resCapacity1 = service.getCapacityWithDefault(null, "testTenant"); - Assert.assertEquals(PropertyUtil.getDefaultGroupQuota(), resCapacity1.getQuota().intValue()); - Assert.assertEquals(PropertyUtil.getDefaultMaxSize(), resCapacity1.getMaxSize().intValue()); - Assert.assertEquals(PropertyUtil.getDefaultMaxAggrCount(), resCapacity1.getMaxAggrCount().intValue()); - Assert.assertEquals(PropertyUtil.getDefaultMaxAggrSize(), resCapacity1.getMaxAggrSize().intValue()); + assertEquals(PropertyUtil.getDefaultGroupQuota(), resCapacity1.getQuota().intValue()); + assertEquals(PropertyUtil.getDefaultMaxSize(), resCapacity1.getMaxSize().intValue()); + assertEquals(PropertyUtil.getDefaultMaxAggrCount(), resCapacity1.getMaxAggrCount().intValue()); + assertEquals(PropertyUtil.getDefaultMaxAggrSize(), resCapacity1.getMaxAggrSize().intValue()); //group is GroupCapacityPersistService.CLUSTER Capacity resCapacity2 = service.getCapacityWithDefault(GroupCapacityPersistService.CLUSTER, null); - Assert.assertEquals(PropertyUtil.getDefaultClusterQuota(), resCapacity2.getQuota().intValue()); - Assert.assertEquals(PropertyUtil.getDefaultMaxSize(), resCapacity2.getMaxSize().intValue()); - Assert.assertEquals(PropertyUtil.getDefaultMaxAggrCount(), resCapacity2.getMaxAggrCount().intValue()); - Assert.assertEquals(PropertyUtil.getDefaultMaxAggrSize(), resCapacity2.getMaxAggrSize().intValue()); + assertEquals(PropertyUtil.getDefaultClusterQuota(), resCapacity2.getQuota().intValue()); + assertEquals(PropertyUtil.getDefaultMaxSize(), resCapacity2.getMaxSize().intValue()); + assertEquals(PropertyUtil.getDefaultMaxAggrCount(), resCapacity2.getMaxAggrCount().intValue()); + assertEquals(PropertyUtil.getDefaultMaxAggrSize(), resCapacity2.getMaxAggrSize().intValue()); GroupCapacity groupCapacity2 = new GroupCapacity(); groupCapacity2.setQuota(0); @@ -295,14 +295,14 @@ public void testGetCapacityWithDefault() { //tenant is null Capacity resCapacity3 = service.getCapacityWithDefault("testGroup", null); - Assert.assertEquals(PropertyUtil.getDefaultGroupQuota(), resCapacity3.getQuota().intValue()); - Assert.assertEquals(PropertyUtil.getDefaultMaxSize(), resCapacity3.getMaxSize().intValue()); - Assert.assertEquals(PropertyUtil.getDefaultMaxAggrCount(), resCapacity3.getMaxAggrCount().intValue()); - Assert.assertEquals(PropertyUtil.getDefaultMaxAggrSize(), resCapacity3.getMaxAggrSize().intValue()); + assertEquals(PropertyUtil.getDefaultGroupQuota(), resCapacity3.getQuota().intValue()); + assertEquals(PropertyUtil.getDefaultMaxSize(), resCapacity3.getMaxSize().intValue()); + assertEquals(PropertyUtil.getDefaultMaxAggrCount(), resCapacity3.getMaxAggrCount().intValue()); + assertEquals(PropertyUtil.getDefaultMaxAggrSize(), resCapacity3.getMaxAggrSize().intValue()); } @Test - public void testInitCapacityV1() { + void testInitCapacityV1() { GroupCapacity groupCapacity = new GroupCapacity(); groupCapacity.setUsage(300); when(groupCapacityPersistService.getGroupCapacity(eq("testGroup"))).thenReturn(groupCapacity); @@ -327,7 +327,7 @@ public void testInitCapacityV1() { } @Test - public void testInitCapacityV2() { + void testInitCapacityV2() { when(groupCapacityPersistService.insertGroupCapacity(any())).thenReturn(true); service.initCapacity(GroupCapacityPersistService.CLUSTER, null); @@ -335,7 +335,7 @@ public void testInitCapacityV2() { } @Test - public void testInsertAndUpdateTenantUsage() { + void testInsertAndUpdateTenantUsage() { TenantCapacity tenantCapacity = new TenantCapacity(); tenantCapacity.setTenant("testTenant"); tenantCapacity.setUsage(300); @@ -355,7 +355,7 @@ public void testInsertAndUpdateTenantUsage() { } @Test - public void testUpdateTenantUsage() { + void testUpdateTenantUsage() { when(tenantCapacityPersistService.incrementUsageWithDefaultQuotaLimit(any())).thenReturn(true); when(tenantCapacityPersistService.decrementUsage(any())).thenReturn(true); @@ -367,7 +367,7 @@ public void testUpdateTenantUsage() { } @Test - public void testInitTenantCapacityV1() { + void testInitTenantCapacityV1() { TenantCapacity tenantCapacity = new TenantCapacity(); tenantCapacity.setTenant("testTenant"); tenantCapacity.setUsage(300); @@ -382,7 +382,7 @@ public void testInitTenantCapacityV1() { } @Test - public void testInitTenantCapacityV2() { + void testInitTenantCapacityV2() { TenantCapacity tenantCapacity = new TenantCapacity(); tenantCapacity.setTenant("testTenant"); tenantCapacity.setUsage(300); @@ -393,44 +393,40 @@ public void testInitTenantCapacityV2() { } @Test - public void testGetTenantCapacity() { + void testGetTenantCapacity() { TenantCapacity tenantCapacity = new TenantCapacity(); tenantCapacity.setId(1L); tenantCapacity.setTenant("testTenant"); when(tenantCapacityPersistService.getTenantCapacity(eq("testTenant"))).thenReturn(tenantCapacity); TenantCapacity resTenantCapacity = service.getTenantCapacity("testTenant"); - Assert.assertEquals(tenantCapacity.getId(), resTenantCapacity.getId()); - Assert.assertEquals(tenantCapacity.getTenant(), resTenantCapacity.getTenant()); + assertEquals(tenantCapacity.getId(), resTenantCapacity.getId()); + assertEquals(tenantCapacity.getTenant(), resTenantCapacity.getTenant()); } @Test - public void testInsertOrUpdateCapacityV1() { + void testInsertOrUpdateCapacityV1() { //tenant is null GroupCapacity groupCapacity = new GroupCapacity(); groupCapacity.setUsage(300); when(groupCapacityPersistService.getGroupCapacity(eq("testGroup"))).thenReturn(groupCapacity); - when(groupCapacityPersistService.updateGroupCapacity(eq("testGroup"), eq(0), eq(0), eq(0), eq(0))) - .thenReturn(true); + when(groupCapacityPersistService.updateGroupCapacity(eq("testGroup"), eq(0), eq(0), eq(0), eq(0))).thenReturn(true); service.insertOrUpdateCapacity("testGroup", null, 0, 0, 0, 0); Mockito.verify(groupCapacityPersistService, times(1)).getGroupCapacity(eq("testGroup")); - Mockito.verify(groupCapacityPersistService, times(1)) - .updateGroupCapacity(eq("testGroup"), eq(0), eq(0), eq(0), eq(0)); + Mockito.verify(groupCapacityPersistService, times(1)).updateGroupCapacity(eq("testGroup"), eq(0), eq(0), eq(0), eq(0)); //tenant is not null TenantCapacity tenantCapacity = new TenantCapacity(); tenantCapacity.setTenant("testTenant"); when(tenantCapacityPersistService.getTenantCapacity(eq("testTenant"))).thenReturn(tenantCapacity); - when(tenantCapacityPersistService.updateTenantCapacity(eq("testTenant"), eq(0), eq(0), eq(0), eq(0))) - .thenReturn(true); + when(tenantCapacityPersistService.updateTenantCapacity(eq("testTenant"), eq(0), eq(0), eq(0), eq(0))).thenReturn(true); service.insertOrUpdateCapacity(null, "testTenant", 0, 0, 0, 0); Mockito.verify(tenantCapacityPersistService, times(1)).getTenantCapacity(eq("testTenant")); - Mockito.verify(tenantCapacityPersistService, times(1)) - .updateTenantCapacity(eq("testTenant"), eq(0), eq(0), eq(0), eq(0)); + Mockito.verify(tenantCapacityPersistService, times(1)).updateTenantCapacity(eq("testTenant"), eq(0), eq(0), eq(0), eq(0)); } @Test - public void testInsertOrUpdateCapacityV2() { + void testInsertOrUpdateCapacityV2() { when(groupCapacityPersistService.getGroupCapacity(eq("testGroup"))).thenReturn(null); when(groupCapacityPersistService.insertGroupCapacity(any())).thenReturn(true); service.insertOrUpdateCapacity("testGroup", null, 0, 0, 0, 0); diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/capacity/GroupCapacityPersistServiceTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/capacity/GroupCapacityPersistServiceTest.java index d076f52ae32..a8aa5f0a32d 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/capacity/GroupCapacityPersistServiceTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/capacity/GroupCapacityPersistServiceTest.java @@ -25,11 +25,10 @@ import com.alibaba.nacos.plugin.datasource.constants.TableConstant; import com.alibaba.nacos.plugin.datasource.impl.mysql.ConfigInfoMapperByMySql; import com.alibaba.nacos.plugin.datasource.impl.mysql.GroupCapacityMapperByMysql; -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.InjectMocks; import org.mockito.Mock; import org.mockito.MockedStatic; @@ -41,7 +40,7 @@ import org.springframework.jdbc.core.RowMapper; import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.util.ReflectionTestUtils; import java.sql.ResultSet; @@ -50,15 +49,19 @@ import java.util.ArrayList; import java.util.List; +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.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; -@RunWith(SpringJUnit4ClassRunner.class) +@ExtendWith(SpringExtension.class) @ContextConfiguration(classes = MockServletContext.class) -public class GroupCapacityPersistServiceTest { +class GroupCapacityPersistServiceTest { + + MockedStatic timeUtilsMockedStatic; @InjectMocks private GroupCapacityPersistService service; @@ -72,27 +75,24 @@ public class GroupCapacityPersistServiceTest { @Mock private MapperManager mapperManager; - MockedStatic timeUtilsMockedStatic; - - @After - public void after() { + @AfterEach + void after() { timeUtilsMockedStatic.close(); } - @Before - public void setUp() { + @BeforeEach + void setUp() { ReflectionTestUtils.setField(service, "jdbcTemplate", jdbcTemplate); ReflectionTestUtils.setField(service, "dataSourceService", dataSourceService); ReflectionTestUtils.setField(service, "mapperManager", mapperManager); when(dataSourceService.getJdbcTemplate()).thenReturn(jdbcTemplate); - doReturn(new GroupCapacityMapperByMysql()).when(mapperManager) - .findMapper(any(), eq(TableConstant.GROUP_CAPACITY)); + doReturn(new GroupCapacityMapperByMysql()).when(mapperManager).findMapper(any(), eq(TableConstant.GROUP_CAPACITY)); timeUtilsMockedStatic = Mockito.mockStatic(TimeUtils.class); } @Test - public void testGetGroupCapacity() { + void testGetGroupCapacity() { List list = new ArrayList<>(); GroupCapacity groupCapacity = new GroupCapacity(); @@ -103,11 +103,11 @@ public void testGetGroupCapacity() { when(jdbcTemplate.query(anyString(), eq(new Object[] {groupId}), any(RowMapper.class))).thenReturn(list); GroupCapacity ret = service.getGroupCapacity(groupId); - Assert.assertEquals(groupCapacity.getGroup(), ret.getGroup()); + assertEquals(groupCapacity.getGroup(), ret.getGroup()); } @Test - public void testGetClusterCapacity() { + void testGetClusterCapacity() { List list = new ArrayList<>(); GroupCapacity groupCapacity = new GroupCapacity(); @@ -118,30 +118,28 @@ public void testGetClusterCapacity() { when(jdbcTemplate.query(anyString(), eq(new Object[] {groupId}), any(RowMapper.class))).thenReturn(list); Capacity ret = service.getClusterCapacity(); - Assert.assertEquals(groupCapacity.getId(), ret.getId()); + assertEquals(groupCapacity.getId(), ret.getId()); } @Test - public void testInsertGroupCapacity() { + void testInsertGroupCapacity() { - doReturn(1).when(jdbcTemplate) - .update(anyString(), eq(""), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null)); + doReturn(1).when(jdbcTemplate).update(anyString(), eq(""), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null)); // when(jdbcTemplate.update(anyString(), eq(timestamp), eq("test3"))).thenReturn(1); GroupCapacity capacity = new GroupCapacity(); capacity.setGroup(GroupCapacityPersistService.CLUSTER); - Assert.assertTrue(service.insertGroupCapacity(capacity)); + assertTrue(service.insertGroupCapacity(capacity)); capacity.setGroup("test"); doReturn(1).when(jdbcTemplate) - .update(anyString(), eq("test"), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null), - eq("test")); + .update(anyString(), eq("test"), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null), eq("test")); - Assert.assertTrue(service.insertGroupCapacity(capacity)); + assertTrue(service.insertGroupCapacity(capacity)); } @Test - public void testGetClusterUsage() { + void testGetClusterUsage() { doReturn(new ConfigInfoMapperByMySql()).when(mapperManager).findMapper(any(), eq(TableConstant.CONFIG_INFO)); List list = new ArrayList<>(); @@ -152,16 +150,15 @@ public void testGetClusterUsage() { String groupId = GroupCapacityPersistService.CLUSTER; when(jdbcTemplate.query(anyString(), eq(new Object[] {groupId}), any(RowMapper.class))).thenReturn(list); - Assert.assertEquals(groupCapacity.getUsage().intValue(), service.getClusterUsage()); + assertEquals(groupCapacity.getUsage().intValue(), service.getClusterUsage()); - when(jdbcTemplate.query(anyString(), eq(new Object[] {groupId}), any(RowMapper.class))).thenReturn( - new ArrayList<>()); + when(jdbcTemplate.query(anyString(), eq(new Object[] {groupId}), any(RowMapper.class))).thenReturn(new ArrayList<>()); when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class))).thenReturn(20); - Assert.assertEquals(20, service.getClusterUsage()); + assertEquals(20, service.getClusterUsage()); } @Test - public void testIncrementUsageWithDefaultQuotaLimit() { + void testIncrementUsageWithDefaultQuotaLimit() { GroupCapacity groupCapacity = new GroupCapacity(); Timestamp timestamp = new Timestamp(System.currentTimeMillis()); groupCapacity.setGmtModified(timestamp); @@ -169,42 +166,41 @@ public void testIncrementUsageWithDefaultQuotaLimit() { groupCapacity.setQuota(1); when(jdbcTemplate.update(anyString(), eq(timestamp), eq("test"), eq(1))).thenReturn(1); - Assert.assertTrue(service.incrementUsageWithDefaultQuotaLimit(groupCapacity)); + assertTrue(service.incrementUsageWithDefaultQuotaLimit(groupCapacity)); //mock get connection fail when(jdbcTemplate.update(anyString(), eq(timestamp), eq("test"), eq(1))).thenThrow( new CannotGetJdbcConnectionException("conn fail")); try { service.incrementUsageWithDefaultQuotaLimit(groupCapacity); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("conn fail", e.getMessage()); + assertEquals("conn fail", e.getMessage()); } } @Test - public void testIncrementUsageWithQuotaLimit() { + void testIncrementUsageWithQuotaLimit() { GroupCapacity groupCapacity = new GroupCapacity(); Timestamp timestamp = new Timestamp(System.currentTimeMillis()); groupCapacity.setGmtModified(timestamp); groupCapacity.setGroup("test2"); when(jdbcTemplate.update(anyString(), eq(timestamp), eq("test2"))).thenReturn(1); - Assert.assertTrue(service.incrementUsageWithQuotaLimit(groupCapacity)); + assertTrue(service.incrementUsageWithQuotaLimit(groupCapacity)); //mock get connection fail - when(jdbcTemplate.update(anyString(), eq(timestamp), eq("test2"))).thenThrow( - new CannotGetJdbcConnectionException("conn fail")); + when(jdbcTemplate.update(anyString(), eq(timestamp), eq("test2"))).thenThrow(new CannotGetJdbcConnectionException("conn fail")); try { service.incrementUsageWithQuotaLimit(groupCapacity); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("conn fail", e.getMessage()); + assertEquals("conn fail", e.getMessage()); } } @Test - public void testIncrementUsage() { + void testIncrementUsage() { GroupCapacity groupCapacity = new GroupCapacity(); Timestamp timestamp = new Timestamp(System.currentTimeMillis()); @@ -212,42 +208,40 @@ public void testIncrementUsage() { groupCapacity.setGroup("test3"); when(jdbcTemplate.update(anyString(), eq(timestamp), eq("test3"))).thenReturn(1); - Assert.assertTrue(service.incrementUsage(groupCapacity)); + assertTrue(service.incrementUsage(groupCapacity)); //mock get connection fail - when(jdbcTemplate.update(anyString(), eq(timestamp), eq("test3"))).thenThrow( - new CannotGetJdbcConnectionException("conn fail")); + when(jdbcTemplate.update(anyString(), eq(timestamp), eq("test3"))).thenThrow(new CannotGetJdbcConnectionException("conn fail")); try { service.incrementUsage(groupCapacity); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("conn fail", e.getMessage()); + assertEquals("conn fail", e.getMessage()); } } @Test - public void testDecrementUsage() { + void testDecrementUsage() { GroupCapacity groupCapacity = new GroupCapacity(); Timestamp timestamp = new Timestamp(System.currentTimeMillis()); groupCapacity.setGmtModified(timestamp); groupCapacity.setGroup("test4"); when(jdbcTemplate.update(anyString(), eq(timestamp), eq("test4"))).thenReturn(1); - Assert.assertTrue(service.decrementUsage(groupCapacity)); + assertTrue(service.decrementUsage(groupCapacity)); //mock get connection fail - when(jdbcTemplate.update(anyString(), eq(timestamp), eq("test4"))).thenThrow( - new CannotGetJdbcConnectionException("conn fail")); + when(jdbcTemplate.update(anyString(), eq(timestamp), eq("test4"))).thenThrow(new CannotGetJdbcConnectionException("conn fail")); try { service.decrementUsage(groupCapacity); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("conn fail", e.getMessage()); + assertEquals("conn fail", e.getMessage()); } } @Test - public void testUpdateGroupCapacity() { + void testUpdateGroupCapacity() { List argList = CollectionUtils.list(); @@ -272,28 +266,26 @@ public void testUpdateGroupCapacity() { when(jdbcTemplate.update(anyString(), any(Object.class))).thenAnswer((Answer) invocationOnMock -> { if (invocationOnMock.getArgument(1).equals(quota) && invocationOnMock.getArgument(2).equals(maxSize) - && invocationOnMock.getArgument(3).equals(maxAggrCount) && invocationOnMock.getArgument(4) - .equals(maxAggrSize) && invocationOnMock.getArgument(5).equals(timestamp) - && invocationOnMock.getArgument(6).equals(group)) { + && invocationOnMock.getArgument(3).equals(maxAggrCount) && invocationOnMock.getArgument(4).equals(maxAggrSize) + && invocationOnMock.getArgument(5).equals(timestamp) && invocationOnMock.getArgument(6).equals(group)) { return 1; } return 0; }); - Assert.assertTrue(service.updateGroupCapacity(group, quota, maxSize, maxAggrCount, maxAggrSize)); + assertTrue(service.updateGroupCapacity(group, quota, maxSize, maxAggrCount, maxAggrSize)); //mock get connection fail - when(jdbcTemplate.update(anyString(), any(Object.class))).thenThrow( - new CannotGetJdbcConnectionException("conn fail")); + when(jdbcTemplate.update(anyString(), any(Object.class))).thenThrow(new CannotGetJdbcConnectionException("conn fail")); try { service.updateGroupCapacity(group, quota, maxSize, maxAggrCount, maxAggrSize); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("conn fail", e.getMessage()); + assertEquals("conn fail", e.getMessage()); } } @Test - public void testGroupCapacityRowMapper() throws SQLException { + void testGroupCapacityRowMapper() throws SQLException { GroupCapacityPersistService.GroupCapacityRowMapper groupCapacityRowMapper = new GroupCapacityPersistService.GroupCapacityRowMapper(); ResultSet rs = Mockito.mock(ResultSet.class); int quota = 12345; @@ -310,16 +302,16 @@ public void testGroupCapacityRowMapper() throws SQLException { Mockito.when(rs.getString(eq("group_id"))).thenReturn(group); GroupCapacity groupCapacity = groupCapacityRowMapper.mapRow(rs, 1); - Assert.assertEquals(quota, groupCapacity.getQuota().intValue()); - Assert.assertEquals(usage, groupCapacity.getUsage().intValue()); - Assert.assertEquals(maxSize, groupCapacity.getMaxSize().intValue()); - Assert.assertEquals(maxAggrCount, groupCapacity.getMaxAggrCount().intValue()); - Assert.assertEquals(maxAggrSize, groupCapacity.getMaxAggrSize().intValue()); - Assert.assertEquals(group, groupCapacity.getGroup()); + assertEquals(quota, groupCapacity.getQuota().intValue()); + assertEquals(usage, groupCapacity.getUsage().intValue()); + assertEquals(maxSize, groupCapacity.getMaxSize().intValue()); + assertEquals(maxAggrCount, groupCapacity.getMaxAggrCount().intValue()); + assertEquals(maxAggrSize, groupCapacity.getMaxAggrSize().intValue()); + assertEquals(group, groupCapacity.getGroup()); } @Test - public void testUpdateQuota() { + void testUpdateQuota() { Timestamp timestamp = new Timestamp(System.currentTimeMillis()); when(TimeUtils.getCurrentTime()).thenReturn(timestamp); List argList = CollectionUtils.list(); @@ -332,11 +324,11 @@ public void testUpdateQuota() { when(jdbcTemplate.update(anyString(), eq(2), eq(timestamp), eq(group))).thenReturn(1); - Assert.assertTrue(service.updateQuota(group, quota)); + assertTrue(service.updateQuota(group, quota)); } @Test - public void testUpdateMaxSize() { + void testUpdateMaxSize() { List argList = CollectionUtils.list(); Timestamp timestamp = new Timestamp(System.currentTimeMillis()); @@ -348,35 +340,35 @@ public void testUpdateMaxSize() { argList.add(group); when(jdbcTemplate.update(anyString(), eq(3), eq(timestamp), eq(group))).thenReturn(1); - Assert.assertTrue(service.updateMaxSize(group, maxSize)); + assertTrue(service.updateMaxSize(group, maxSize)); } @Test - public void testCorrectUsage() { + void testCorrectUsage() { String group = GroupCapacityPersistService.CLUSTER; Timestamp timestamp = new Timestamp(System.currentTimeMillis()); when(jdbcTemplate.update(anyString(), eq(timestamp), eq(group))).thenReturn(1); - Assert.assertTrue(service.correctUsage(group, timestamp)); + assertTrue(service.correctUsage(group, timestamp)); group = "test"; when(jdbcTemplate.update(anyString(), eq(group), eq(timestamp), eq(group))).thenReturn(1); - Assert.assertTrue(service.correctUsage(group, timestamp)); + assertTrue(service.correctUsage(group, timestamp)); //mock get connection fail when(jdbcTemplate.update(anyString(), eq(group), eq(timestamp), eq(group))).thenThrow( new CannotGetJdbcConnectionException("conn fail")); try { service.correctUsage(group, timestamp); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("conn fail", e.getMessage()); + assertEquals("conn fail", e.getMessage()); } } @Test - public void testGetCapacityList4CorrectUsage() { + void testGetCapacityList4CorrectUsage() { List list = new ArrayList<>(); GroupCapacity groupCapacity = new GroupCapacity(); @@ -385,38 +377,36 @@ public void testGetCapacityList4CorrectUsage() { long lastId = 1; int pageSize = 1; - when(jdbcTemplate.query(anyString(), eq(new Object[] {lastId, pageSize}), any(RowMapper.class))).thenReturn( - list); + when(jdbcTemplate.query(anyString(), eq(new Object[] {lastId, pageSize}), any(RowMapper.class))).thenReturn(list); List ret = service.getCapacityList4CorrectUsage(lastId, pageSize); - Assert.assertEquals(list.size(), ret.size()); - Assert.assertEquals(groupCapacity.getGroup(), ret.get(0).getGroup()); + assertEquals(list.size(), ret.size()); + assertEquals(groupCapacity.getGroup(), ret.get(0).getGroup()); //mock get connection fail when(jdbcTemplate.query(anyString(), eq(new Object[] {lastId, pageSize}), any(RowMapper.class))).thenThrow( new CannotGetJdbcConnectionException("conn fail")); try { service.getCapacityList4CorrectUsage(lastId, pageSize); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("conn fail", e.getMessage()); + assertEquals("conn fail", e.getMessage()); } } @Test - public void testDeleteGroupCapacity() { + void testDeleteGroupCapacity() { when(jdbcTemplate.update(any(PreparedStatementCreator.class))).thenReturn(1); - Assert.assertTrue(service.deleteGroupCapacity("test")); + assertTrue(service.deleteGroupCapacity("test")); //mock get connection fail - when(jdbcTemplate.update(any(PreparedStatementCreator.class))).thenThrow( - new CannotGetJdbcConnectionException("conn fail")); + when(jdbcTemplate.update(any(PreparedStatementCreator.class))).thenThrow(new CannotGetJdbcConnectionException("conn fail")); try { service.deleteGroupCapacity("test"); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("conn fail", e.getMessage()); + assertEquals("conn fail", e.getMessage()); } } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/capacity/TenantCapacityPersistServiceTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/capacity/TenantCapacityPersistServiceTest.java index b1efc63cba2..dfd57828fcf 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/capacity/TenantCapacityPersistServiceTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/capacity/TenantCapacityPersistServiceTest.java @@ -23,10 +23,9 @@ import com.alibaba.nacos.plugin.datasource.MapperManager; import com.alibaba.nacos.plugin.datasource.constants.TableConstant; import com.alibaba.nacos.plugin.datasource.impl.mysql.TenantCapacityMapperByMySql; -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.InjectMocks; import org.mockito.Mock; import org.mockito.MockedStatic; @@ -38,7 +37,7 @@ import org.springframework.jdbc.core.RowMapper; import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.util.ReflectionTestUtils; import java.sql.ResultSet; @@ -47,15 +46,17 @@ import java.util.ArrayList; import java.util.List; +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.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; -@RunWith(SpringJUnit4ClassRunner.class) +@ExtendWith(SpringExtension.class) @ContextConfiguration(classes = MockServletContext.class) -public class TenantCapacityPersistServiceTest { +class TenantCapacityPersistServiceTest { @Mock private JdbcTemplate jdbcTemplate; @@ -69,18 +70,17 @@ public class TenantCapacityPersistServiceTest { @InjectMocks private TenantCapacityPersistService service; - @Before - public void setUp() { + @BeforeEach + void setUp() { ReflectionTestUtils.setField(service, "jdbcTemplate", jdbcTemplate); ReflectionTestUtils.setField(service, "dataSourceService", dataSourceService); ReflectionTestUtils.setField(service, "mapperManager", mapperManager); when(dataSourceService.getJdbcTemplate()).thenReturn(jdbcTemplate); - doReturn(new TenantCapacityMapperByMySql()).when(mapperManager) - .findMapper(any(), eq(TableConstant.TENANT_CAPACITY)); + doReturn(new TenantCapacityMapperByMySql()).when(mapperManager).findMapper(any(), eq(TableConstant.TENANT_CAPACITY)); } @Test - public void testGetTenantCapacity() { + void testGetTenantCapacity() { List list = new ArrayList<>(); TenantCapacity tenantCapacity = new TenantCapacity(); @@ -91,32 +91,32 @@ public void testGetTenantCapacity() { when(jdbcTemplate.query(anyString(), eq(new Object[] {tenantId}), any(RowMapper.class))).thenReturn(list); TenantCapacity ret = service.getTenantCapacity(tenantId); - Assert.assertEquals(tenantCapacity.getTenant(), ret.getTenant()); + assertEquals(tenantCapacity.getTenant(), ret.getTenant()); } @Test - public void testInsertTenantCapacity() { + void testInsertTenantCapacity() { when(jdbcTemplate.update(anyString(), eq("test"), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null), eq("test"))).thenReturn(1); TenantCapacity capacity = new TenantCapacity(); capacity.setTenant("test"); - Assert.assertTrue(service.insertTenantCapacity(capacity)); + assertTrue(service.insertTenantCapacity(capacity)); //mock get connection fail when(jdbcTemplate.update(anyString(), eq("test"), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null), eq("test"))).thenThrow(new CannotGetJdbcConnectionException("conn fail")); try { service.insertTenantCapacity(capacity); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("conn fail", e.getMessage()); + assertEquals("conn fail", e.getMessage()); } } @Test - public void testIncrementUsageWithDefaultQuotaLimit() { + void testIncrementUsageWithDefaultQuotaLimit() { TenantCapacity tenantCapacity = new TenantCapacity(); Timestamp timestamp = new Timestamp(System.currentTimeMillis()); @@ -125,21 +125,21 @@ public void testIncrementUsageWithDefaultQuotaLimit() { tenantCapacity.setQuota(1); when(jdbcTemplate.update(anyString(), eq(timestamp), eq("test"), eq(1))).thenReturn(1); - Assert.assertTrue(service.incrementUsageWithDefaultQuotaLimit(tenantCapacity)); + assertTrue(service.incrementUsageWithDefaultQuotaLimit(tenantCapacity)); //mock get connection fail when(jdbcTemplate.update(anyString(), eq(timestamp), eq("test"), eq(1))).thenThrow( new CannotGetJdbcConnectionException("conn fail")); try { service.incrementUsageWithDefaultQuotaLimit(tenantCapacity); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("conn fail", e.getMessage()); + assertEquals("conn fail", e.getMessage()); } } @Test - public void testIncrementUsageWithQuotaLimit() { + void testIncrementUsageWithQuotaLimit() { TenantCapacity tenantCapacity = new TenantCapacity(); Timestamp timestamp = new Timestamp(System.currentTimeMillis()); @@ -147,21 +147,20 @@ public void testIncrementUsageWithQuotaLimit() { tenantCapacity.setTenant("test2"); when(jdbcTemplate.update(anyString(), eq(timestamp), eq("test2"))).thenReturn(1); - Assert.assertTrue(service.incrementUsageWithQuotaLimit(tenantCapacity)); + assertTrue(service.incrementUsageWithQuotaLimit(tenantCapacity)); //mock get connection fail - when(jdbcTemplate.update(anyString(), eq(timestamp), eq("test2"))).thenThrow( - new CannotGetJdbcConnectionException("conn fail")); + when(jdbcTemplate.update(anyString(), eq(timestamp), eq("test2"))).thenThrow(new CannotGetJdbcConnectionException("conn fail")); try { service.incrementUsageWithQuotaLimit(tenantCapacity); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("conn fail", e.getMessage()); + assertEquals("conn fail", e.getMessage()); } } @Test - public void testIncrementUsage() { + void testIncrementUsage() { TenantCapacity tenantCapacity = new TenantCapacity(); Timestamp timestamp = new Timestamp(System.currentTimeMillis()); @@ -169,21 +168,20 @@ public void testIncrementUsage() { tenantCapacity.setTenant("test3"); when(jdbcTemplate.update(anyString(), eq(timestamp), eq("test3"))).thenReturn(1); - Assert.assertTrue(service.incrementUsage(tenantCapacity)); + assertTrue(service.incrementUsage(tenantCapacity)); //mock get connection fail - when(jdbcTemplate.update(anyString(), eq(timestamp), eq("test3"))).thenThrow( - new CannotGetJdbcConnectionException("conn fail")); + when(jdbcTemplate.update(anyString(), eq(timestamp), eq("test3"))).thenThrow(new CannotGetJdbcConnectionException("conn fail")); try { service.incrementUsage(tenantCapacity); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("conn fail", e.getMessage()); + assertEquals("conn fail", e.getMessage()); } } @Test - public void testDecrementUsage() { + void testDecrementUsage() { TenantCapacity tenantCapacity = new TenantCapacity(); Timestamp timestamp = new Timestamp(System.currentTimeMillis()); @@ -191,21 +189,20 @@ public void testDecrementUsage() { tenantCapacity.setTenant("test4"); when(jdbcTemplate.update(anyString(), eq(timestamp), eq("test4"))).thenReturn(1); - Assert.assertTrue(service.decrementUsage(tenantCapacity)); + assertTrue(service.decrementUsage(tenantCapacity)); //mock get connection fail - when(jdbcTemplate.update(anyString(), eq(timestamp), eq("test4"))).thenThrow( - new CannotGetJdbcConnectionException("conn fail")); + when(jdbcTemplate.update(anyString(), eq(timestamp), eq("test4"))).thenThrow(new CannotGetJdbcConnectionException("conn fail")); try { service.decrementUsage(tenantCapacity); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("conn fail", e.getMessage()); + assertEquals("conn fail", e.getMessage()); } } @Test - public void testUpdateTenantCapacity() { + void testUpdateTenantCapacity() { final MockedStatic timeUtilsMockedStatic = Mockito.mockStatic(TimeUtils.class); List argList = CollectionUtils.list(); @@ -231,20 +228,19 @@ public void testUpdateTenantCapacity() { when(jdbcTemplate.update(anyString(), any(Object.class))).thenAnswer((Answer) invocationOnMock -> { if (invocationOnMock.getArgument(1).equals(quota) && invocationOnMock.getArgument(2).equals(maxSize) - && invocationOnMock.getArgument(3).equals(maxAggrCount) && invocationOnMock.getArgument(4) - .equals(maxAggrSize) && invocationOnMock.getArgument(5).equals(timestamp) - && invocationOnMock.getArgument(6).equals(tenant)) { + && invocationOnMock.getArgument(3).equals(maxAggrCount) && invocationOnMock.getArgument(4).equals(maxAggrSize) + && invocationOnMock.getArgument(5).equals(timestamp) && invocationOnMock.getArgument(6).equals(tenant)) { return 1; } return 0; }); - Assert.assertTrue(service.updateTenantCapacity(tenant, quota, maxSize, maxAggrCount, maxAggrSize)); + assertTrue(service.updateTenantCapacity(tenant, quota, maxSize, maxAggrCount, maxAggrSize)); timeUtilsMockedStatic.close(); } @Test - public void testUpdateQuota() { + void testUpdateQuota() { List argList = CollectionUtils.list(); Integer quota = 2; @@ -259,41 +255,40 @@ public void testUpdateQuota() { } return 0; }); - Assert.assertTrue(service.updateQuota(tenant, quota)); + assertTrue(service.updateQuota(tenant, quota)); //mock get connection fail - when(jdbcTemplate.update(anyString(), any(Object.class))).thenThrow( - new CannotGetJdbcConnectionException("conn fail")); + when(jdbcTemplate.update(anyString(), any(Object.class))).thenThrow(new CannotGetJdbcConnectionException("conn fail")); try { service.updateQuota(tenant, quota); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("conn fail", e.getMessage()); + assertEquals("conn fail", e.getMessage()); } } @Test - public void testCorrectUsage() { + void testCorrectUsage() { String tenant = "test"; Timestamp timestamp = new Timestamp(System.currentTimeMillis()); when(jdbcTemplate.update(anyString(), eq(tenant), eq(timestamp), eq(tenant))).thenReturn(1); - Assert.assertTrue(service.correctUsage(tenant, timestamp)); + assertTrue(service.correctUsage(tenant, timestamp)); //mock get connection fail when(jdbcTemplate.update(anyString(), eq(tenant), eq(timestamp), eq(tenant))).thenThrow( new CannotGetJdbcConnectionException("conn fail")); try { service.correctUsage(tenant, timestamp); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("conn fail", e.getMessage()); + assertEquals("conn fail", e.getMessage()); } } @Test - public void testGetCapacityList4CorrectUsage() { + void testGetCapacityList4CorrectUsage() { List list = new ArrayList<>(); TenantCapacity tenantCapacity = new TenantCapacity(); @@ -302,43 +297,41 @@ public void testGetCapacityList4CorrectUsage() { long lastId = 1; int pageSize = 1; - when(jdbcTemplate.query(anyString(), eq(new Object[] {lastId, pageSize}), any(RowMapper.class))).thenReturn( - list); + when(jdbcTemplate.query(anyString(), eq(new Object[] {lastId, pageSize}), any(RowMapper.class))).thenReturn(list); List ret = service.getCapacityList4CorrectUsage(lastId, pageSize); - Assert.assertEquals(list.size(), ret.size()); - Assert.assertEquals(tenantCapacity.getTenant(), ret.get(0).getTenant()); + assertEquals(list.size(), ret.size()); + assertEquals(tenantCapacity.getTenant(), ret.get(0).getTenant()); //mock get connection fail when(jdbcTemplate.query(anyString(), eq(new Object[] {lastId, pageSize}), any(RowMapper.class))).thenThrow( new CannotGetJdbcConnectionException("conn fail")); try { service.getCapacityList4CorrectUsage(lastId, pageSize); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("conn fail", e.getMessage()); + assertEquals("conn fail", e.getMessage()); } } @Test - public void testDeleteTenantCapacity() { + void testDeleteTenantCapacity() { when(jdbcTemplate.update(any(PreparedStatementCreator.class))).thenReturn(1); - Assert.assertTrue(service.deleteTenantCapacity("test")); + assertTrue(service.deleteTenantCapacity("test")); //mock get connection fail - when(jdbcTemplate.update(any(PreparedStatementCreator.class))).thenThrow( - new CannotGetJdbcConnectionException("conn fail")); + when(jdbcTemplate.update(any(PreparedStatementCreator.class))).thenThrow(new CannotGetJdbcConnectionException("conn fail")); try { service.deleteTenantCapacity("test"); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("conn fail", e.getMessage()); + assertEquals("conn fail", e.getMessage()); } } @Test - public void testTenantCapacityRowMapper() throws SQLException { + void testTenantCapacityRowMapper() throws SQLException { TenantCapacityPersistService.TenantCapacityRowMapper groupCapacityRowMapper = new TenantCapacityPersistService.TenantCapacityRowMapper(); ResultSet rs = Mockito.mock(ResultSet.class); int quota = 12345; @@ -355,11 +348,11 @@ public void testTenantCapacityRowMapper() throws SQLException { Mockito.when(rs.getString(eq("tenant_id"))).thenReturn(tenant); TenantCapacity groupCapacity = groupCapacityRowMapper.mapRow(rs, 1); - Assert.assertEquals(quota, groupCapacity.getQuota().intValue()); - Assert.assertEquals(usage, groupCapacity.getUsage().intValue()); - Assert.assertEquals(maxSize, groupCapacity.getMaxSize().intValue()); - Assert.assertEquals(maxAggrCount, groupCapacity.getMaxAggrCount().intValue()); - Assert.assertEquals(maxAggrSize, groupCapacity.getMaxAggrSize().intValue()); - Assert.assertEquals(tenant, groupCapacity.getTenant()); + assertEquals(quota, groupCapacity.getQuota().intValue()); + assertEquals(usage, groupCapacity.getUsage().intValue()); + assertEquals(maxSize, groupCapacity.getMaxSize().intValue()); + assertEquals(maxAggrCount, groupCapacity.getMaxAggrCount().intValue()); + assertEquals(maxAggrSize, groupCapacity.getMaxAggrSize().intValue()); + assertEquals(tenant, groupCapacity.getTenant()); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/dump/DefaultHistoryConfigCleanerTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/dump/DefaultHistoryConfigCleanerTest.java new file mode 100644 index 00000000000..f6aac67fbc4 --- /dev/null +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/dump/DefaultHistoryConfigCleanerTest.java @@ -0,0 +1,102 @@ +/* + * Copyright 1999-2024 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.config.server.service.dump; + +import com.alibaba.nacos.config.server.service.repository.HistoryConfigInfoPersistService; +import com.alibaba.nacos.config.server.utils.ConfigExecutor; +import com.alibaba.nacos.sys.env.EnvUtil; +import com.alibaba.nacos.sys.utils.ApplicationUtils; +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.springframework.test.context.junit.jupiter.SpringExtension; + +import java.lang.reflect.Method; +import java.sql.Timestamp; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; + +@ExtendWith(SpringExtension.class) +public class DefaultHistoryConfigCleanerTest { + + private DefaultHistoryConfigCleaner defaultHistoryConfigCleaner = new DefaultHistoryConfigCleaner(); + + @Mock + private HistoryConfigInfoPersistService historyConfigInfoPersistService; + + MockedStatic applicationUtilsMockedStatic; + + MockedStatic configExecutorMocked; + + MockedStatic envUtilMockedStatic; + + /** + * Sets up. + */ + @BeforeEach + public void setUp() { + applicationUtilsMockedStatic = Mockito.mockStatic(ApplicationUtils.class); + applicationUtilsMockedStatic.when(() -> ApplicationUtils.getBean(HistoryConfigInfoPersistService.class)) + .thenReturn(historyConfigInfoPersistService); + + configExecutorMocked = Mockito.mockStatic(ConfigExecutor.class); + envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); + } + + /** + * End. + */ + @AfterEach + public void end() { + applicationUtilsMockedStatic.close(); + configExecutorMocked.close(); + envUtilMockedStatic.close(); + } + + @Test + public void test() { + HistoryConfigCleaner configCleaner = HistoryConfigCleanerManager.getHistoryConfigCleaner("nacos"); + assertEquals(configCleaner.getName(), "nacos"); + } + + @Test + public void testCleanHistoryConfig() throws Exception { + defaultHistoryConfigCleaner.cleanHistoryConfig(); + Mockito.verify(historyConfigInfoPersistService, Mockito.times(1)) + .removeConfigHistory(any(Timestamp.class), anyInt()); + } + + @Test + public void testGetRetentionDays() throws Exception { + Method method = DefaultHistoryConfigCleaner.class.getDeclaredMethod("getRetentionDays"); + method.setAccessible(true); + envUtilMockedStatic.when(() -> EnvUtil.getProperty("nacos.config.retention.days")).thenReturn("-1"); + assertEquals((int) method.invoke(defaultHistoryConfigCleaner), 30); + + envUtilMockedStatic.when(() -> EnvUtil.getProperty("nacos.config.retention.days")).thenReturn("30"); + assertEquals((int) method.invoke(defaultHistoryConfigCleaner), 30); + + envUtilMockedStatic.when(() -> EnvUtil.getProperty("nacos.config.retention.days")).thenReturn("1"); + assertEquals((int) method.invoke(defaultHistoryConfigCleaner), 1); + } +} \ No newline at end of file diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/dump/DumpChangeConfigWorkerTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/dump/DumpChangeConfigWorkerTest.java index 7ba2dabeb27..cde308bce33 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/dump/DumpChangeConfigWorkerTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/dump/DumpChangeConfigWorkerTest.java @@ -31,15 +31,14 @@ import com.alibaba.nacos.persistence.datasource.DynamicDataSource; import com.alibaba.nacos.plugin.datasource.constants.CommonConstant; import com.alibaba.nacos.sys.env.EnvUtil; -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; @@ -47,6 +46,8 @@ import java.util.ArrayList; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyLong; @@ -54,8 +55,8 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class DumpChangeConfigWorkerTest { +@ExtendWith(MockitoExtension.class) +class DumpChangeConfigWorkerTest { @Mock DynamicDataSource dynamicDataSource; @@ -75,13 +76,12 @@ public class DumpChangeConfigWorkerTest { MockedStatic envUtilMockedStatic; - @Before - public void init() throws Exception { + @BeforeEach + void init() throws Exception { dynamicDataSourceMockedStatic = Mockito.mockStatic(DynamicDataSource.class); envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); when(EnvUtil.getNacosHome()).thenReturn(System.getProperty("user.home") + File.separator + "tmp"); - when(EnvUtil.getProperty(eq(CommonConstant.NACOS_PLUGIN_DATASOURCE_LOG), eq(Boolean.class), - eq(false))).thenReturn(false); + when(EnvUtil.getProperty(eq(CommonConstant.NACOS_PLUGIN_DATASOURCE_LOG), eq(Boolean.class), eq(false))).thenReturn(false); dynamicDataSourceMockedStatic.when(DynamicDataSource::getInstance).thenReturn(dynamicDataSource); Field[] declaredFields = ConfigDiskServiceFactory.class.getDeclaredFields(); @@ -100,8 +100,8 @@ protected ConfigDiskService createDiskService() { return new ConfigRocksDbDiskService(); } - @After - public void after() throws IllegalAccessException { + @AfterEach + void after() throws IllegalAccessException { dynamicDataSourceMockedStatic.close(); envUtilMockedStatic.close(); ConfigDiskServiceFactory.getInstance().clearAll(); @@ -118,14 +118,14 @@ public void after() throws IllegalAccessException { } @Test - public void testDumpChangeIfOff() { + void testDumpChangeIfOff() { PropertyUtil.setDumpChangeOn(false); dumpChangeConfigWorker.run(); Mockito.verify(historyConfigInfoPersistService, times(0)).findDeletedConfig(any(), anyLong(), anyInt()); } @Test - public void testDumpChangeOfDeleteConfigs() { + void testDumpChangeOfDeleteConfigs() { PropertyUtil.setDumpChangeOn(true); dumpChangeConfigWorker.setPageSize(3); //mock delete first page @@ -138,29 +138,25 @@ public void testDumpChangeOfDeleteConfigs() { firstPageDeleted.add(createConfigInfoStateWrapper(dataIdPrefix, 3, startTime.getTime() + 3)); //pre set cache for id1 preSetCache(dataIdPrefix, 1, System.currentTimeMillis()); - Assert.assertEquals("encrykey" + 1, - ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)) - .getConfigCache().getEncryptedDataKey()); - Mockito.when(historyConfigInfoPersistService.findDeletedConfig(eq(startTime), eq(0L), eq(3))) - .thenReturn(firstPageDeleted); + assertEquals("encrykey" + 1, + ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)).getConfigCache() + .getEncryptedDataKey()); + Mockito.when(historyConfigInfoPersistService.findDeletedConfig(eq(startTime), eq(0L), eq(3))).thenReturn(firstPageDeleted); //mock delete config query is null - Mockito.when( - configInfoPersistService.findConfigInfoState(eq(dataIdPrefix + 1), eq("group" + 1), eq("tenant" + 1))) + Mockito.when(configInfoPersistService.findConfigInfoState(eq(dataIdPrefix + 1), eq("group" + 1), eq("tenant" + 1))) .thenReturn(null); - Mockito.when( - configInfoPersistService.findConfigInfoState(eq(dataIdPrefix + 2), eq("group" + 2), eq("tenant" + 2))) + Mockito.when(configInfoPersistService.findConfigInfoState(eq(dataIdPrefix + 2), eq("group" + 2), eq("tenant" + 2))) .thenReturn(null); dumpChangeConfigWorker.run(); //expect delete page return pagesize and will select second page Mockito.verify(historyConfigInfoPersistService, times(1)).findDeletedConfig(eq(startTime), eq(3L), eq(3)); //expect cache to be cleared. - Assert.assertNull( - ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1))); + assertNull(ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1))); } @Test - public void testDumpChangeOfChangedConfigsNewTimestampOverride() { + void testDumpChangeOfChangedConfigsNewTimestampOverride() { PropertyUtil.setDumpChangeOn(true); dumpChangeConfigWorker.setPageSize(3); //mock delete first page @@ -170,9 +166,9 @@ public void testDumpChangeOfChangedConfigsNewTimestampOverride() { //pre set cache for id1 with old timestamp preSetCache(dataIdPrefix, 1, startTime.getTime() - 1); - Assert.assertEquals(startTime.getTime() - 1, - ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)) - .getConfigCache().getLastModifiedTs()); + assertEquals(startTime.getTime() - 1, + ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)).getConfigCache() + .getLastModifiedTs()); List firstChanged = new ArrayList<>(); firstChanged.add(createConfigInfoStateWrapper(dataIdPrefix, 1, startTime.getTime() + 1)); @@ -180,8 +176,7 @@ public void testDumpChangeOfChangedConfigsNewTimestampOverride() { //mock change config query obj //1 timestamp-new&content-new - ConfigInfoWrapper configInfoWrapperNewForId1 = createConfigInfoWrapper(dataIdPrefix, 1, - startTime.getTime() + 2); + ConfigInfoWrapper configInfoWrapperNewForId1 = createConfigInfoWrapper(dataIdPrefix, 1, startTime.getTime() + 2); configInfoWrapperNewForId1.setContent("content" + System.currentTimeMillis()); Mockito.when(configInfoPersistService.findConfigInfo(eq(dataIdPrefix + 1), eq("group" + 1), eq("tenant" + 1))) .thenReturn(configInfoWrapperNewForId1); @@ -189,16 +184,16 @@ public void testDumpChangeOfChangedConfigsNewTimestampOverride() { dumpChangeConfigWorker.run(); //expect cache to be cleared. - Assert.assertEquals(startTime.getTime() + 2, - ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)) - .getConfigCache().getLastModifiedTs()); - Assert.assertEquals(MD5Utils.md5Hex(configInfoWrapperNewForId1.getContent(), "UTF-8"), - ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)) - .getConfigCache().getMd5Utf8()); + assertEquals(startTime.getTime() + 2, + ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)).getConfigCache() + .getLastModifiedTs()); + assertEquals(MD5Utils.md5Hex(configInfoWrapperNewForId1.getContent(), "UTF-8"), + ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)).getConfigCache() + .getMd5Utf8()); } @Test - public void testDumpChangeOfChangedConfigsNewTimestampEqualMd5() { + void testDumpChangeOfChangedConfigsNewTimestampEqualMd5() { PropertyUtil.setDumpChangeOn(true); dumpChangeConfigWorker.setPageSize(3); //mock delete first page @@ -208,9 +203,9 @@ public void testDumpChangeOfChangedConfigsNewTimestampEqualMd5() { //pre set cache for id1 with old timestamp preSetCache(dataIdPrefix, 1, startTime.getTime() - 1); - Assert.assertEquals(startTime.getTime() - 1, - ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)) - .getConfigCache().getLastModifiedTs()); + assertEquals(startTime.getTime() - 1, + ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)).getConfigCache() + .getLastModifiedTs()); List firstChanged = new ArrayList<>(); firstChanged.add(createConfigInfoStateWrapper(dataIdPrefix, 1, startTime.getTime() + 1)); @@ -218,25 +213,24 @@ public void testDumpChangeOfChangedConfigsNewTimestampEqualMd5() { //mock change config query obj //1 timestamp-new&content-old - ConfigInfoWrapper configInfoWrapperNewForId1 = createConfigInfoWrapper(dataIdPrefix, 1, - startTime.getTime() + 2); + ConfigInfoWrapper configInfoWrapperNewForId1 = createConfigInfoWrapper(dataIdPrefix, 1, startTime.getTime() + 2); Mockito.when(configInfoPersistService.findConfigInfo(eq(dataIdPrefix + 1), eq("group" + 1), eq("tenant" + 1))) .thenReturn(configInfoWrapperNewForId1); dumpChangeConfigWorker.run(); //expect cache - Assert.assertEquals(startTime.getTime() + 2, - ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)) - .getConfigCache().getLastModifiedTs()); - Assert.assertEquals(MD5Utils.md5Hex(configInfoWrapperNewForId1.getContent(), "UTF-8"), - ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)) - .getConfigCache().getMd5Utf8()); + assertEquals(startTime.getTime() + 2, + ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)).getConfigCache() + .getLastModifiedTs()); + assertEquals(MD5Utils.md5Hex(configInfoWrapperNewForId1.getContent(), "UTF-8"), + ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)).getConfigCache() + .getMd5Utf8()); } @Test - public void testDumpChangeOfChangedConfigsOldTimestamp() { + void testDumpChangeOfChangedConfigsOldTimestamp() { PropertyUtil.setDumpChangeOn(true); dumpChangeConfigWorker.setPageSize(3); //mock delete first page @@ -247,9 +241,9 @@ public void testDumpChangeOfChangedConfigsOldTimestamp() { //pre set cache for id1 with old timestamp preSetCache(dataIdPrefix, 1, startTime.getTime() - 1); - Assert.assertEquals(startTime.getTime() - 1, - ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)) - .getConfigCache().getLastModifiedTs()); + assertEquals(startTime.getTime() - 1, + ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)).getConfigCache() + .getLastModifiedTs()); List firstChanged = new ArrayList<>(); firstChanged.add(createConfigInfoStateWrapper(dataIdPrefix, 1, startTime.getTime() - 2)); @@ -257,8 +251,7 @@ public void testDumpChangeOfChangedConfigsOldTimestamp() { //mock change config query obj //1 timestamp-new&content-new - ConfigInfoWrapper configInfoWrapperNewForId1 = createConfigInfoWrapper(dataIdPrefix, 1, - startTime.getTime() - 2); + ConfigInfoWrapper configInfoWrapperNewForId1 = createConfigInfoWrapper(dataIdPrefix, 1, startTime.getTime() - 2); configInfoWrapperNewForId1.setContent("content" + System.currentTimeMillis()); Mockito.when(configInfoPersistService.findConfigInfo(eq(dataIdPrefix + 1), eq("group" + 1), eq("tenant" + 1))) .thenReturn(configInfoWrapperNewForId1); @@ -266,17 +259,17 @@ public void testDumpChangeOfChangedConfigsOldTimestamp() { dumpChangeConfigWorker.run(); //expect cache to be cleared. - Assert.assertEquals(startTime.getTime() - 1, - ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)) - .getConfigCache().getLastModifiedTs()); - Assert.assertEquals(MD5Utils.md5Hex("content" + 1, "UTF-8"), - ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)) - .getConfigCache().getMd5Utf8()); + assertEquals(startTime.getTime() - 1, + ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)).getConfigCache() + .getLastModifiedTs()); + assertEquals(MD5Utils.md5Hex("content" + 1, "UTF-8"), + ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)).getConfigCache() + .getMd5Utf8()); } @Test - public void testDumpChangeOfChangedConfigsEqualsTimestampMd5Update() { + void testDumpChangeOfChangedConfigsEqualsTimestampMd5Update() { PropertyUtil.setDumpChangeOn(true); dumpChangeConfigWorker.setPageSize(3); //mock delete first page @@ -287,9 +280,9 @@ public void testDumpChangeOfChangedConfigsEqualsTimestampMd5Update() { //pre set cache for id1 with old timestamp preSetCache(dataIdPrefix, 1, startTime.getTime() - 1); - Assert.assertEquals(startTime.getTime() - 1, - ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)) - .getConfigCache().getLastModifiedTs()); + assertEquals(startTime.getTime() - 1, + ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)).getConfigCache() + .getLastModifiedTs()); List firstChanged = new ArrayList<>(); firstChanged.add(createConfigInfoStateWrapper(dataIdPrefix, 1, startTime.getTime() - 1)); @@ -297,8 +290,7 @@ public void testDumpChangeOfChangedConfigsEqualsTimestampMd5Update() { //mock change config query obj //1 timestamp-new&content-new - ConfigInfoWrapper configInfoWrapperNewForId1 = createConfigInfoWrapper(dataIdPrefix, 1, - startTime.getTime() - 1); + ConfigInfoWrapper configInfoWrapperNewForId1 = createConfigInfoWrapper(dataIdPrefix, 1, startTime.getTime() - 1); configInfoWrapperNewForId1.setContent("content" + System.currentTimeMillis()); Mockito.when(configInfoPersistService.findConfigInfo(eq(dataIdPrefix + 1), eq("group" + 1), eq("tenant" + 1))) .thenReturn(configInfoWrapperNewForId1); @@ -306,12 +298,12 @@ public void testDumpChangeOfChangedConfigsEqualsTimestampMd5Update() { dumpChangeConfigWorker.run(); //expect cache to be cleared. - Assert.assertEquals(startTime.getTime() - 1, - ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)) - .getConfigCache().getLastModifiedTs()); - Assert.assertEquals(MD5Utils.md5Hex(configInfoWrapperNewForId1.getContent(), "UTF-8"), - ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)) - .getConfigCache().getMd5Utf8()); + assertEquals(startTime.getTime() - 1, + ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)).getConfigCache() + .getLastModifiedTs()); + assertEquals(MD5Utils.md5Hex(configInfoWrapperNewForId1.getContent(), "UTF-8"), + ConfigCacheService.getContentCache(GroupKey.getKeyTenant(dataIdPrefix + 1, "group" + 1, "tenant" + 1)).getConfigCache() + .getMd5Utf8()); } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/dump/DumpProcessorTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/dump/DumpProcessorTest.java index 56bb3dd2717..d01fc330d12 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/dump/DumpProcessorTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/dump/DumpProcessorTest.java @@ -35,25 +35,27 @@ import com.alibaba.nacos.persistence.datasource.DynamicDataSource; import com.alibaba.nacos.plugin.datasource.constants.CommonConstant; import com.alibaba.nacos.sys.env.EnvUtil; -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.IOException; import java.lang.reflect.Field; import java.util.Arrays; +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.eq; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class DumpProcessorTest { +@ExtendWith(MockitoExtension.class) +class DumpProcessorTest { @Mock DynamicDataSource dynamicDataSource; @@ -78,21 +80,19 @@ public class DumpProcessorTest { MockedStatic envUtilMockedStatic; - @Before - public void init() throws Exception { + @BeforeEach + void init() throws Exception { dynamicDataSourceMockedStatic = Mockito.mockStatic(DynamicDataSource.class); envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); when(EnvUtil.getNacosHome()).thenReturn(System.getProperty("user.home")); - when(EnvUtil.getProperty(eq(CommonConstant.NACOS_PLUGIN_DATASOURCE_LOG), eq(Boolean.class), - eq(false))).thenReturn(false); + when(EnvUtil.getProperty(eq(CommonConstant.NACOS_PLUGIN_DATASOURCE_LOG), eq(Boolean.class), eq(false))).thenReturn(false); dynamicDataSourceMockedStatic.when(DynamicDataSource::getInstance).thenReturn(dynamicDataSource); when(dynamicDataSource.getDataSource()).thenReturn(dataSourceService); dumpService = new ExternalDumpService(configInfoPersistService, null, null, null, configInfoBetaPersistService, configInfoTagPersistService, null, null); - dumpProcessor = new DumpProcessor(configInfoPersistService, configInfoBetaPersistService, - configInfoTagPersistService); + dumpProcessor = new DumpProcessor(configInfoPersistService, configInfoBetaPersistService, configInfoTagPersistService); Field[] declaredFields = ConfigDiskServiceFactory.class.getDeclaredFields(); for (Field filed : declaredFields) { if (filed.getName().equals("configDiskService")) { @@ -107,8 +107,8 @@ protected ConfigDiskService createDiskService() { return new ConfigRocksDbDiskService(); } - @After - public void after() { + @AfterEach + void after() { dynamicDataSourceMockedStatic.close(); envUtilMockedStatic.close(); ConfigDiskServiceFactory.getInstance().clearAll(); @@ -118,7 +118,7 @@ public void after() { } @Test - public void testDumpNormalAndRemove() throws IOException { + void testDumpNormalAndRemove() throws IOException { String dataId = "testDataId"; String group = "testGroup"; String tenant = "testTenant"; @@ -131,41 +131,39 @@ public void testDumpNormalAndRemove() throws IOException { configInfoWrapper.setContent(content); configInfoWrapper.setLastModified(time); - Mockito.when(configInfoPersistService.findConfigInfo(eq(dataId), eq(group), eq(tenant))) - .thenReturn(configInfoWrapper); + Mockito.when(configInfoPersistService.findConfigInfo(eq(dataId), eq(group), eq(tenant))).thenReturn(configInfoWrapper); String handlerIp = "127.0.0.1"; long lastModified = System.currentTimeMillis(); - DumpTask dumpTask = new DumpTask(GroupKey2.getKey(dataId, group, tenant), false, false, false, null, - lastModified, handlerIp); + DumpTask dumpTask = new DumpTask(GroupKey2.getKey(dataId, group, tenant), false, false, false, null, lastModified, handlerIp); boolean process = dumpProcessor.process(dumpTask); - Assert.assertTrue(process); + assertTrue(process); //Check cache CacheItem contentCache = ConfigCacheService.getContentCache(GroupKey2.getKey(dataId, group, tenant)); - Assert.assertEquals(MD5Utils.md5Hex(content, "UTF-8"), contentCache.getConfigCache().getMd5Utf8()); - Assert.assertEquals(time, contentCache.getConfigCache().getLastModifiedTs()); + assertEquals(MD5Utils.md5Hex(content, "UTF-8"), contentCache.getConfigCache().getMd5Utf8()); + assertEquals(time, contentCache.getConfigCache().getLastModifiedTs()); //check disk String contentFromDisk = ConfigDiskServiceFactory.getInstance().getContent(dataId, group, tenant); - Assert.assertEquals(content, contentFromDisk); + assertEquals(content, contentFromDisk); // remove Mockito.when(configInfoPersistService.findConfigInfo(eq(dataId), eq(group), eq(tenant))).thenReturn(null); boolean processRemove = dumpProcessor.process(dumpTask); - Assert.assertTrue(processRemove); + assertTrue(processRemove); //Check cache CacheItem contentCacheAfterRemove = ConfigCacheService.getContentCache(GroupKey2.getKey(dataId, group, tenant)); - Assert.assertTrue(contentCacheAfterRemove == null); + assertTrue(contentCacheAfterRemove == null); //check disk String contentFromDiskAfterRemove = ConfigDiskServiceFactory.getInstance().getContent(dataId, group, tenant); - Assert.assertNull(contentFromDiskAfterRemove); + assertNull(contentFromDiskAfterRemove); } @Test - public void testDumpBetaAndRemove() throws IOException { + void testDumpBetaAndRemove() throws IOException { String dataId = "testDataIdBeta"; String group = "testGroup"; String tenant = "testTenant"; @@ -180,43 +178,39 @@ public void testDumpBetaAndRemove() throws IOException { String betaIps = "127.0.0.1123,127.0.0.11"; configInfoWrapper.setBetaIps(betaIps); - Mockito.when(configInfoBetaPersistService.findConfigInfo4Beta(eq(dataId), eq(group), eq(tenant))) - .thenReturn(configInfoWrapper); + Mockito.when(configInfoBetaPersistService.findConfigInfo4Beta(eq(dataId), eq(group), eq(tenant))).thenReturn(configInfoWrapper); String handlerIp = "127.0.0.1"; long lastModified = System.currentTimeMillis(); - DumpTask dumpTask = new DumpTask(GroupKey2.getKey(dataId, group, tenant), true, false, false, null, - lastModified, handlerIp); + DumpTask dumpTask = new DumpTask(GroupKey2.getKey(dataId, group, tenant), true, false, false, null, lastModified, handlerIp); boolean process = dumpProcessor.process(dumpTask); - Assert.assertTrue(process); + assertTrue(process); //Check cache CacheItem contentCache = ConfigCacheService.getContentCache(GroupKey2.getKey(dataId, group, tenant)); - Assert.assertEquals(MD5Utils.md5Hex(content, "UTF-8"), contentCache.getConfigCacheBeta().getMd5Utf8()); - Assert.assertEquals(time, contentCache.getConfigCacheBeta().getLastModifiedTs()); - Assert.assertTrue(contentCache.ips4Beta.containsAll(Arrays.asList(betaIps.split(",")))); + assertEquals(MD5Utils.md5Hex(content, "UTF-8"), contentCache.getConfigCacheBeta().getMd5Utf8()); + assertEquals(time, contentCache.getConfigCacheBeta().getLastModifiedTs()); + assertTrue(contentCache.ips4Beta.containsAll(Arrays.asList(betaIps.split(",")))); //check disk String contentFromDisk = ConfigDiskServiceFactory.getInstance().getBetaContent(dataId, group, tenant); - Assert.assertEquals(content, contentFromDisk); + assertEquals(content, contentFromDisk); // remove - Mockito.when(configInfoBetaPersistService.findConfigInfo4Beta(eq(dataId), eq(group), eq(tenant))) - .thenReturn(null); + Mockito.when(configInfoBetaPersistService.findConfigInfo4Beta(eq(dataId), eq(group), eq(tenant))).thenReturn(null); boolean processRemove = dumpProcessor.process(dumpTask); - Assert.assertTrue(processRemove); + assertTrue(processRemove); //Check cache CacheItem contentCacheAfterRemove = ConfigCacheService.getContentCache(GroupKey2.getKey(dataId, group, tenant)); - Assert.assertTrue(contentCacheAfterRemove == null || contentCacheAfterRemove.getConfigCacheBeta() == null); + assertTrue(contentCacheAfterRemove == null || contentCacheAfterRemove.getConfigCacheBeta() == null); //check disk - String contentFromDiskAfterRemove = ConfigDiskServiceFactory.getInstance() - .getBetaContent(dataId, group, tenant); - Assert.assertNull(contentFromDiskAfterRemove); + String contentFromDiskAfterRemove = ConfigDiskServiceFactory.getInstance().getBetaContent(dataId, group, tenant); + assertNull(contentFromDiskAfterRemove); } @Test - public void testDumpTagAndRemove() throws IOException { + void testDumpTagAndRemove() throws IOException { String dataId = "testDataIdBeta"; String group = "testGroup"; String tenant = "testTenant"; @@ -235,33 +229,30 @@ public void testDumpTagAndRemove() throws IOException { String handlerIp = "127.0.0.1"; long lastModified = System.currentTimeMillis(); - DumpTask dumpTask = new DumpTask(GroupKey2.getKey(dataId, group, tenant), false, false, true, tag, lastModified, - handlerIp); + DumpTask dumpTask = new DumpTask(GroupKey2.getKey(dataId, group, tenant), false, false, true, tag, lastModified, handlerIp); boolean process = dumpProcessor.process(dumpTask); - Assert.assertTrue(process); + assertTrue(process); //Check cache CacheItem contentCache = ConfigCacheService.getContentCache(GroupKey2.getKey(dataId, group, tenant)); - Assert.assertEquals(MD5Utils.md5Hex(content, "UTF-8"), contentCache.getConfigCacheTags().get(tag).getMd5Utf8()); - Assert.assertEquals(time, contentCache.getConfigCacheTags().get(tag).getLastModifiedTs()); + assertEquals(MD5Utils.md5Hex(content, "UTF-8"), contentCache.getConfigCacheTags().get(tag).getMd5Utf8()); + assertEquals(time, contentCache.getConfigCacheTags().get(tag).getLastModifiedTs()); //check disk String contentFromDisk = ConfigDiskServiceFactory.getInstance().getTagContent(dataId, group, tenant, tag); - Assert.assertEquals(content, contentFromDisk); + assertEquals(content, contentFromDisk); // remove - Mockito.when(configInfoTagPersistService.findConfigInfo4Tag(eq(dataId), eq(group), eq(tenant), eq(tag))) - .thenReturn(null); + Mockito.when(configInfoTagPersistService.findConfigInfo4Tag(eq(dataId), eq(group), eq(tenant), eq(tag))).thenReturn(null); boolean processRemove = dumpProcessor.process(dumpTask); - Assert.assertTrue(processRemove); + assertTrue(processRemove); //Check cache CacheItem contentCacheAfterRemove = ConfigCacheService.getContentCache(GroupKey2.getKey(dataId, group, tenant)); - Assert.assertTrue(contentCacheAfterRemove == null || contentCache.getConfigCacheTags() == null + assertTrue(contentCacheAfterRemove == null || contentCache.getConfigCacheTags() == null || contentCache.getConfigCacheTags().get(tag) == null); //check disk - String contentFromDiskAfterRemove = ConfigDiskServiceFactory.getInstance() - .getTagContent(dataId, group, tenant, tag); - Assert.assertNull(contentFromDiskAfterRemove); + String contentFromDiskAfterRemove = ConfigDiskServiceFactory.getInstance().getTagContent(dataId, group, tenant, tag); + assertNull(contentFromDiskAfterRemove); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/dump/DumpProcessorUserRwaDiskTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/dump/DumpProcessorUserRwaDiskTest.java index 0ae123012fc..27a3bf09fc9 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/dump/DumpProcessorUserRwaDiskTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/dump/DumpProcessorUserRwaDiskTest.java @@ -18,18 +18,18 @@ import com.alibaba.nacos.config.server.service.dump.disk.ConfigDiskService; import com.alibaba.nacos.config.server.service.dump.disk.ConfigRawDiskService; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +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.junit.jupiter.MockitoExtension; import java.io.IOException; -@RunWith(MockitoJUnitRunner.class) -public class DumpProcessorUserRwaDiskTest extends DumpProcessorTest { +@ExtendWith(MockitoExtension.class) +class DumpProcessorUserRwaDiskTest extends DumpProcessorTest { - @Before + @BeforeEach public void init() throws Exception { super.init(); } @@ -39,7 +39,7 @@ protected ConfigDiskService createDiskService() { return new ConfigRawDiskService(); } - @After + @AfterEach public void after() { super.after(); } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/dump/DumpServiceTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/dump/DumpServiceTest.java index 717cee46102..884561422d1 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/dump/DumpServiceTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/dump/DumpServiceTest.java @@ -34,17 +34,16 @@ import com.alibaba.nacos.persistence.datasource.DataSourceService; import com.alibaba.nacos.persistence.datasource.DynamicDataSource; import com.alibaba.nacos.sys.env.EnvUtil; -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.MockedStatic; import org.mockito.Mockito; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.util.ReflectionTestUtils; -import java.sql.Timestamp; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -54,11 +53,19 @@ import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; -@RunWith(SpringJUnit4ClassRunner.class) -public class DumpServiceTest { +@ExtendWith(SpringExtension.class) +class DumpServiceTest { + + private static final String BETA_TABLE_NAME = "config_info_beta"; + + private static final String TAG_TABLE_NAME = "config_info_tag"; + + @Mock + DefaultHistoryConfigCleaner defaultHistoryConfigCleaner = new DefaultHistoryConfigCleaner(); @Mock ConfigInfoPersistService configInfoPersistService; @@ -85,26 +92,24 @@ public class DumpServiceTest { @Mock ServerMemberManager memberManager; - @Mock - private DataSourceService dataSourceService; - MockedStatic envUtilMockedStatic; MockedStatic configExecutorMocked; MockedStatic propertyUtilMockedStatic; - private DumpService dumpService; + MockedStatic historyConfigCleanerManagerMockedStatic; @Mock - private TaskManager dumpTaskMgr; + private DataSourceService dataSourceService; - private static final String BETA_TABLE_NAME = "config_info_beta"; + private DumpService dumpService; - private static final String TAG_TABLE_NAME = "config_info_tag"; + @Mock + private TaskManager dumpTaskMgr; - @Before - public void setUp() { + @BeforeEach + void setUp() { envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); propertyUtilMockedStatic = Mockito.mockStatic(PropertyUtil.class); propertyUtilMockedStatic.when(() -> PropertyUtil.getAllDumpPageSize()).thenReturn(100); @@ -112,26 +117,28 @@ public void setUp() { ReflectionTestUtils.setField(DynamicDataSource.getInstance(), "localDataSourceService", dataSourceService); ReflectionTestUtils.setField(DynamicDataSource.getInstance(), "basicDataSourceService", dataSourceService); - dumpService = new ExternalDumpService(configInfoPersistService, namespacePersistService, - historyConfigInfoPersistService, configInfoAggrPersistService, configInfoBetaPersistService, - configInfoTagPersistService, mergeDatumService, memberManager); + dumpService = new ExternalDumpService(configInfoPersistService, namespacePersistService, historyConfigInfoPersistService, + configInfoAggrPersistService, configInfoBetaPersistService, configInfoTagPersistService, mergeDatumService, memberManager); configExecutorMocked = Mockito.mockStatic(ConfigExecutor.class); + historyConfigCleanerManagerMockedStatic = Mockito.mockStatic(HistoryConfigCleanerManager.class); + historyConfigCleanerManagerMockedStatic.when(() -> HistoryConfigCleanerManager.getHistoryConfigCleaner(anyString())) + .thenReturn(defaultHistoryConfigCleaner); } - @After - public void after() { + @AfterEach + void after() { envUtilMockedStatic.close(); configExecutorMocked.close(); propertyUtilMockedStatic.close(); + historyConfigCleanerManagerMockedStatic.close(); } @Test - public void dumpRequest() throws Throwable { + void dumpRequest() throws Throwable { String dataId = "12345667dataId"; String group = "234445group"; - DumpRequest dumpRequest = DumpRequest.create(dataId, group, "testtenant", System.currentTimeMillis(), - "127.0.0.1"); + DumpRequest dumpRequest = DumpRequest.create(dataId, group, "testtenant", System.currentTimeMillis(), "127.0.0.1"); // TaskManager dumpTaskMgr; ReflectionTestUtils.setField(dumpService, "dumpTaskMgr", dumpTaskMgr); Mockito.doNothing().when(dumpTaskMgr).addTask(any(), any()); @@ -141,30 +148,26 @@ public void dumpRequest() throws Throwable { dumpRequest.setBeta(true); dumpService.dump(dumpRequest); Mockito.verify(dumpTaskMgr, times(1)) - .addTask(eq(GroupKey.getKeyTenant(dataId, group, dumpRequest.getTenant()) + "+beta"), - any(DumpTask.class)); + .addTask(eq(GroupKey.getKeyTenant(dataId, group, dumpRequest.getTenant()) + "+beta"), any(DumpTask.class)); dumpRequest.setBeta(false); dumpRequest.setBatch(true); dumpService.dump(dumpRequest); Mockito.verify(dumpTaskMgr, times(1)) - .addTask(eq(GroupKey.getKeyTenant(dataId, group, dumpRequest.getTenant()) + "+batch"), - any(DumpTask.class)); + .addTask(eq(GroupKey.getKeyTenant(dataId, group, dumpRequest.getTenant()) + "+batch"), any(DumpTask.class)); dumpRequest.setBatch(false); dumpRequest.setTag("testTag111"); dumpService.dump(dumpRequest); - Mockito.verify(dumpTaskMgr, times(1)).addTask( - eq(GroupKey.getKeyTenant(dataId, group, dumpRequest.getTenant()) + "+tag+" + dumpRequest.getTag()), - any(DumpTask.class)); + Mockito.verify(dumpTaskMgr, times(1)) + .addTask(eq(GroupKey.getKeyTenant(dataId, group, dumpRequest.getTenant()) + "+tag+" + dumpRequest.getTag()), + any(DumpTask.class)); } @Test - public void dumpOperate() throws Throwable { - configExecutorMocked.when( - () -> ConfigExecutor.scheduleConfigTask(any(Runnable.class), anyInt(), anyInt(), any(TimeUnit.class))) + void dumpOperate() throws Throwable { + configExecutorMocked.when(() -> ConfigExecutor.scheduleConfigTask(any(Runnable.class), anyInt(), anyInt(), any(TimeUnit.class))) .thenAnswer(invocation -> null); - configExecutorMocked.when( - () -> ConfigExecutor.scheduleConfigChangeTask(any(Runnable.class), anyInt(), any(TimeUnit.class))) + configExecutorMocked.when(() -> ConfigExecutor.scheduleConfigChangeTask(any(Runnable.class), anyInt(), any(TimeUnit.class))) .thenAnswer(invocation -> null); Mockito.when(namespacePersistService.isExistTable(BETA_TABLE_NAME)).thenReturn(true); Mockito.when(namespacePersistService.isExistTable(TAG_TABLE_NAME)).thenReturn(true); @@ -199,41 +202,42 @@ public void dumpOperate() throws Throwable { // expect dump formal,beta,tag,history clear,config change task to be scheduled. // expect config clear history task be scheduled. configExecutorMocked.verify( - () -> ConfigExecutor.scheduleConfigTask(any(DumpService.DumpAllProcessorRunner.class), anyLong(), - anyLong(), eq(TimeUnit.MINUTES)), times(1)); + () -> ConfigExecutor.scheduleConfigTask(any(DumpService.DumpAllProcessorRunner.class), anyLong(), anyLong(), + eq(TimeUnit.MINUTES)), times(1)); configExecutorMocked.verify( - () -> ConfigExecutor.scheduleConfigTask(any(DumpService.DumpAllBetaProcessorRunner.class), anyLong(), - anyLong(), eq(TimeUnit.MINUTES)), times(1)); + () -> ConfigExecutor.scheduleConfigTask(any(DumpService.DumpAllBetaProcessorRunner.class), anyLong(), anyLong(), + eq(TimeUnit.MINUTES)), times(1)); configExecutorMocked.verify( - () -> ConfigExecutor.scheduleConfigTask(any(DumpService.DumpAllTagProcessorRunner.class), anyLong(), - anyLong(), eq(TimeUnit.MINUTES)), times(1)); + () -> ConfigExecutor.scheduleConfigTask(any(DumpService.DumpAllTagProcessorRunner.class), anyLong(), anyLong(), + eq(TimeUnit.MINUTES)), times(1)); configExecutorMocked.verify( - () -> ConfigExecutor.scheduleConfigChangeTask(any(DumpChangeConfigWorker.class), anyLong(), - eq(TimeUnit.MILLISECONDS)), times(1)); + () -> ConfigExecutor.scheduleConfigChangeTask(any(DumpChangeConfigWorker.class), anyLong(), eq(TimeUnit.MILLISECONDS)), + times(1)); configExecutorMocked.verify( () -> ConfigExecutor.scheduleConfigTask(any(DumpService.ConfigHistoryClear.class), anyLong(), anyLong(), - eq(TimeUnit.MINUTES)), times(1)); + eq(TimeUnit.MINUTES)), times(1) + ); } @Test - public void clearHistory() { + void clearHistory() { envUtilMockedStatic.when(() -> EnvUtil.getProperty(eq("nacos.config.retention.days"))).thenReturn("10"); Mockito.when(memberManager.isFirstIp()).thenReturn(true); - dumpService.clearConfigHistory(); - Mockito.verify(historyConfigInfoPersistService, times(1)).removeConfigHistory(any(Timestamp.class), anyInt()); + DumpService.ConfigHistoryClear configHistoryClear = dumpService.new ConfigHistoryClear(defaultHistoryConfigCleaner); + configHistoryClear.run(); + Mockito.verify(defaultHistoryConfigCleaner, times(1)).cleanHistoryConfig(); } @Test - public void testHandleConfigDataChange() { - ConfigDataChangeEvent configDataChangeEvent = new ConfigDataChangeEvent("dataId", "group", - System.currentTimeMillis()); + void testHandleConfigDataChange() { + ConfigDataChangeEvent configDataChangeEvent = new ConfigDataChangeEvent("dataId", "group", System.currentTimeMillis()); ReflectionTestUtils.setField(dumpService, "dumpTaskMgr", dumpTaskMgr); Mockito.doNothing().when(dumpTaskMgr).addTask(any(), any()); dumpService.handleConfigDataChange(configDataChangeEvent); - Mockito.verify(dumpTaskMgr, times(1)).addTask( - eq(GroupKey.getKeyTenant(configDataChangeEvent.dataId, configDataChangeEvent.group, - configDataChangeEvent.tenant)), any(DumpTask.class)); + Mockito.verify(dumpTaskMgr, times(1)) + .addTask(eq(GroupKey.getKeyTenant(configDataChangeEvent.dataId, configDataChangeEvent.group, configDataChangeEvent.tenant)), + any(DumpTask.class)); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/dump/HistoryConfigCleanerConfigTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/dump/HistoryConfigCleanerConfigTest.java new file mode 100644 index 00000000000..f3fb8319a96 --- /dev/null +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/dump/HistoryConfigCleanerConfigTest.java @@ -0,0 +1,58 @@ +/* + * Copyright 1999-2024 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.config.server.service.dump; + +import com.alibaba.nacos.sys.env.EnvUtil; +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.MockedStatic; +import org.mockito.Mockito; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; + +@ExtendWith(SpringExtension.class) +class HistoryConfigCleanerConfigTest { + + MockedStatic envUtilMockedStatic; + + @BeforeEach + public void before() { + envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); + } + + @Test + public void test() { + envUtilMockedStatic.when(() -> EnvUtil.getProperty(anyString(), any(), anyString())).thenReturn("test"); + HistoryConfigCleanerConfig historyConfigCleanerConfig = HistoryConfigCleanerConfig.getInstance(); + historyConfigCleanerConfig.getConfigFromEnv(); + assertEquals("test", historyConfigCleanerConfig.getActiveHistoryConfigCleaner()); + envUtilMockedStatic.when(() -> EnvUtil.getProperty(anyString(), any(), anyString())).thenReturn(null); + historyConfigCleanerConfig.getConfigFromEnv(); + assertEquals("nacos", historyConfigCleanerConfig.getActiveHistoryConfigCleaner()); + } + + @AfterEach + public void after() { + envUtilMockedStatic.close(); + } + +} \ No newline at end of file diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/dump/HistoryConfigCleanerManagerTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/dump/HistoryConfigCleanerManagerTest.java new file mode 100644 index 00000000000..5fb8135bdef --- /dev/null +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/dump/HistoryConfigCleanerManagerTest.java @@ -0,0 +1,32 @@ +/* + * Copyright 1999-2024 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.config.server.service.dump; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class HistoryConfigCleanerManagerTest { + + @Test + public void testHistoryConfigCleanerManangerTest() { + HistoryConfigCleaner cleaner = HistoryConfigCleanerManager.getHistoryConfigCleaner( + HistoryConfigCleanerConfig.getInstance().getActiveHistoryConfigCleaner()); + assertEquals(cleaner.getName(), "nacos"); + } + +} \ No newline at end of file diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/dump/disk/ConfigDiskServiceFactoryTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/dump/disk/ConfigDiskServiceFactoryTest.java index f54d928f8f6..5289fa01f17 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/dump/disk/ConfigDiskServiceFactoryTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/dump/disk/ConfigDiskServiceFactoryTest.java @@ -16,47 +16,48 @@ package com.alibaba.nacos.config.server.service.dump.disk; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +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.junit.jupiter.MockitoExtension; import java.lang.reflect.Field; -@RunWith(MockitoJUnitRunner.class) -public class ConfigDiskServiceFactoryTest { +import static org.junit.jupiter.api.Assertions.assertTrue; + +@ExtendWith(MockitoExtension.class) +class ConfigDiskServiceFactoryTest { - @Before - public void before() throws Exception { + @BeforeEach + void before() throws Exception { clearDiskInstance(); } - @After - public void after() { + @AfterEach + void after() { } @Test - public void getRawDiskInstance() { + void getRawDiskInstance() { System.setProperty("config_disk_type", "rawdisk"); ConfigDiskService instance = ConfigDiskServiceFactory.getInstance(); - Assert.assertTrue(instance instanceof ConfigRawDiskService); + assertTrue(instance instanceof ConfigRawDiskService); } @Test - public void getRockDbDiskInstance() { + void getRockDbDiskInstance() { System.setProperty("config_disk_type", "rocksdb"); ConfigDiskService instance = ConfigDiskServiceFactory.getInstance(); - Assert.assertTrue(instance instanceof ConfigRocksDbDiskService); + assertTrue(instance instanceof ConfigRocksDbDiskService); } @Test - public void getDefaultRawDiskInstance() { + void getDefaultRawDiskInstance() { System.setProperty("config_disk_type", "123"); ConfigDiskService instance = ConfigDiskServiceFactory.getInstance(); - Assert.assertTrue(instance instanceof ConfigRawDiskService); + assertTrue(instance instanceof ConfigRawDiskService); } private void clearDiskInstance() throws Exception { diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/dump/disk/ConfigRawDiskServiceTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/dump/disk/ConfigRawDiskServiceTest.java new file mode 100644 index 00000000000..a0cce0f95f6 --- /dev/null +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/dump/disk/ConfigRawDiskServiceTest.java @@ -0,0 +1,114 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.config.server.service.dump.disk; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.nio.file.Path; +import java.nio.file.Paths; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ConfigRawDiskServiceTest { + + private String cachedOsName; + + @BeforeEach + void setUp() throws Exception { + cachedOsName = System.getProperty("os.name"); + } + + private boolean isWindows() { + return cachedOsName.toLowerCase().startsWith("win"); + } + + /** + * 测试获取文件路径. + */ + @Test + void testTargetFile() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { + Method method = ConfigRawDiskService.class.getDeclaredMethod("targetFile", String.class, String.class, String.class); + method.setAccessible(true); + File result = (File) method.invoke(null, "aaaa?dsaknkf", "aaaa*dsaknkf", "aaaa:dsaknkf"); + // 分解路径 + Path path = Paths.get(result.getPath()); + Path parent = path.getParent(); + Path grandParent = parent.getParent(); + // 获取最后三段路径 + String lastSegment = path.getFileName().toString(); + String secondLastSegment = parent.getFileName().toString(); + String thirdLastSegment = grandParent.getFileName().toString(); + assertEquals(isWindows() ? "aaaa%A3%dsaknkf" : thirdLastSegment, thirdLastSegment); + assertEquals(isWindows() ? "aaaa%A4%dsaknkf" : secondLastSegment, secondLastSegment); + assertEquals(isWindows() ? "aaaa%A5%dsaknkf" : lastSegment, lastSegment); + } + + /** + * 测试获取beta文件路径. + */ + @Test + void testTargetBetaFile() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { + Method method = ConfigRawDiskService.class.getDeclaredMethod("targetBetaFile", String.class, String.class, String.class); + method.setAccessible(true); + File result = (File) method.invoke(null, "aaaa?dsaknkf", "aaaa*dsaknkf", "aaaa:dsaknkf"); + // 分解路径 + Path path = Paths.get(result.getPath()); + Path parent = path.getParent(); + Path grandParent = parent.getParent(); + // 获取最后三段路径 + String lastSegment = path.getFileName().toString(); + String secondLastSegment = parent.getFileName().toString(); + String thirdLastSegment = grandParent.getFileName().toString(); + assertEquals(isWindows() ? "aaaa%A3%dsaknkf" : thirdLastSegment, thirdLastSegment); + assertEquals(isWindows() ? "aaaa%A4%dsaknkf" : secondLastSegment, secondLastSegment); + assertEquals(isWindows() ? "aaaa%A5%dsaknkf" : lastSegment, lastSegment); + + } + + /** + * 测试获取tag文件路径. + * + * @throws NoSuchMethodException 方法不存在异常 + * @throws IllegalAccessException 非法访问异常 + * @throws InvocationTargetException 目标异常 + */ + @Test + void testTargetTagFile() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { + Method method = ConfigRawDiskService.class.getDeclaredMethod("targetTagFile", String.class, String.class, String.class, + String.class); + method.setAccessible(true); + File result = (File) method.invoke(null, "aaaa?dsaknkf", "aaaa*dsaknkf", "aaaa:dsaknkf", "aaaadsaknkf"); + // 分解路径 + Path path = Paths.get(result.getPath()); + Path parent = path.getParent(); + Path grandParent = parent.getParent(); + Path greatGrandParent = grandParent.getParent(); + // 获取最后四段路径 + String secondLastSegment = parent.getFileName().toString(); + String thirdLastSegment = grandParent.getFileName().toString(); + String fourthLastSegment = greatGrandParent.getFileName().toString(); + assertEquals(isWindows() ? "aaaa%A3%dsaknkf" : fourthLastSegment, fourthLastSegment); + assertEquals(isWindows() ? "aaaa%A4%dsaknkf" : thirdLastSegment, thirdLastSegment); + assertEquals(isWindows() ? "aaaa%A5%dsaknkf" : secondLastSegment, secondLastSegment); + String lastSegment = path.getFileName().toString(); + assertEquals("aaaadsaknkf", lastSegment); + } +} diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/dump/processor/DumpAllProcessorTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/dump/processor/DumpAllProcessorTest.java index 392e4015bc4..206d950adcf 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/dump/processor/DumpAllProcessorTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/dump/processor/DumpAllProcessorTest.java @@ -33,26 +33,28 @@ import com.alibaba.nacos.persistence.model.Page; import com.alibaba.nacos.plugin.datasource.constants.CommonConstant; import com.alibaba.nacos.sys.env.EnvUtil; -import junit.framework.TestCase; -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 org.springframework.beans.BeanUtils; import java.util.Arrays; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class DumpAllProcessorTest extends TestCase { +@ExtendWith(MockitoExtension.class) +class DumpAllProcessorTest { + + private static int newConfigCount = 1; @Mock DynamicDataSource dynamicDataSource; @@ -79,14 +81,13 @@ public class DumpAllProcessorTest extends TestCase { private String mockMem = "tmpmocklimitfile.txt"; - @Before - public void init() throws Exception { + @BeforeEach + void init() throws Exception { dynamicDataSourceMockedStatic = Mockito.mockStatic(DynamicDataSource.class); envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); dumpAllProcessor = new DumpAllProcessor(configInfoPersistService); when(EnvUtil.getNacosHome()).thenReturn(System.getProperty("user.home")); - when(EnvUtil.getProperty(eq(CommonConstant.NACOS_PLUGIN_DATASOURCE_LOG), eq(Boolean.class), - eq(false))).thenReturn(false); + when(EnvUtil.getProperty(eq(CommonConstant.NACOS_PLUGIN_DATASOURCE_LOG), eq(Boolean.class), eq(false))).thenReturn(false); dynamicDataSourceMockedStatic.when(DynamicDataSource::getInstance).thenReturn(dynamicDataSource); when(dynamicDataSource.getDataSource()).thenReturn(dataSourceService); @@ -95,18 +96,16 @@ public void init() throws Exception { configInfoTagPersistService, null, null); dumpAllProcessor = new DumpAllProcessor(configInfoPersistService); - envUtilMockedStatic.when(() -> EnvUtil.getProperty(eq("memory_limit_file_path"), - eq("/sys/fs/cgroup/memory/memory.limit_in_bytes"))).thenReturn(mockMem); + envUtilMockedStatic.when(() -> EnvUtil.getProperty(eq("memory_limit_file_path"), eq("/sys/fs/cgroup/memory/memory.limit_in_bytes"))) + .thenReturn(mockMem); } - @After - public void after() throws Exception { + @AfterEach + void after() throws Exception { dynamicDataSourceMockedStatic.close(); envUtilMockedStatic.close(); } - private static int newConfigCount = 1; - private ConfigInfoWrapper createNewConfig(int id) { ConfigInfoWrapper configInfoWrapper = new ConfigInfoWrapper(); String dataId = "dataIdTime" + newConfigCount; @@ -123,7 +122,7 @@ private ConfigInfoWrapper createNewConfig(int id) { } @Test - public void testDumpAllOnStartUp() throws Exception { + void testDumpAllOnStartUp() throws Exception { ConfigInfoWrapper configInfoWrapper1 = createNewConfig(1); ConfigInfoWrapper configInfoWrapper2 = createNewConfig(2); long timestamp = System.currentTimeMillis(); @@ -137,8 +136,7 @@ public void testDumpAllOnStartUp() throws Exception { page.setPageItems(list); Mockito.when(configInfoPersistService.findConfigMaxId()).thenReturn(2L); - Mockito.when(configInfoPersistService.findAllConfigInfoFragment(0, PropertyUtil.getAllDumpPageSize(), true)) - .thenReturn(page); + Mockito.when(configInfoPersistService.findAllConfigInfoFragment(0, PropertyUtil.getAllDumpPageSize(), true)).thenReturn(page); // For config 1, assign a latter time, to make sure that it would be updated. // For config 2, assign an earlier time, to make sure that it is not be updated. @@ -147,52 +145,44 @@ public void testDumpAllOnStartUp() throws Exception { long latterTimestamp = timestamp + 999; long earlierTimestamp = timestamp - 999; String encryptedDataKey = "testEncryptedDataKey"; - ConfigCacheService.dumpWithMd5(configInfoWrapper1.getDataId(), configInfoWrapper1.getGroup(), - configInfoWrapper1.getTenant(), configInfoWrapper1.getContent(), md51, latterTimestamp, "json", - encryptedDataKey); - ConfigCacheService.dumpWithMd5(configInfoWrapper2.getDataId(), configInfoWrapper2.getGroup(), - configInfoWrapper2.getTenant(), configInfoWrapper2.getContent(), md52, earlierTimestamp, "json", - encryptedDataKey); + ConfigCacheService.dumpWithMd5(configInfoWrapper1.getDataId(), configInfoWrapper1.getGroup(), configInfoWrapper1.getTenant(), + configInfoWrapper1.getContent(), md51, latterTimestamp, "json", encryptedDataKey); + ConfigCacheService.dumpWithMd5(configInfoWrapper2.getDataId(), configInfoWrapper2.getGroup(), configInfoWrapper2.getTenant(), + configInfoWrapper2.getContent(), md52, earlierTimestamp, "json", encryptedDataKey); DumpAllTask dumpAllTask = new DumpAllTask(true); boolean process = dumpAllProcessor.process(dumpAllTask); - Assert.assertTrue(process); + assertTrue(process); //Check cache CacheItem contentCache1 = ConfigCacheService.getContentCache( - GroupKey2.getKey(configInfoWrapper1.getDataId(), configInfoWrapper1.getGroup(), - configInfoWrapper1.getTenant())); - Assert.assertEquals(md51, contentCache1.getConfigCache().getMd5Utf8()); + GroupKey2.getKey(configInfoWrapper1.getDataId(), configInfoWrapper1.getGroup(), configInfoWrapper1.getTenant())); + assertEquals(md51, contentCache1.getConfigCache().getMd5Utf8()); // check if config1 is updated - Assert.assertTrue(timestamp < contentCache1.getConfigCache().getLastModifiedTs()); + assertTrue(timestamp < contentCache1.getConfigCache().getLastModifiedTs()); //check disk String contentFromDisk1 = ConfigDiskServiceFactory.getInstance() - .getContent(configInfoWrapper1.getDataId(), configInfoWrapper1.getGroup(), - configInfoWrapper1.getTenant()); - Assert.assertEquals(configInfoWrapper1.getContent(), contentFromDisk1); + .getContent(configInfoWrapper1.getDataId(), configInfoWrapper1.getGroup(), configInfoWrapper1.getTenant()); + assertEquals(configInfoWrapper1.getContent(), contentFromDisk1); //Check cache CacheItem contentCache2 = ConfigCacheService.getContentCache( - GroupKey2.getKey(configInfoWrapper2.getDataId(), configInfoWrapper2.getGroup(), - configInfoWrapper2.getTenant())); - Assert.assertEquals(MD5Utils.md5Hex(configInfoWrapper2.getContent(), "UTF-8"), - contentCache2.getConfigCache().getMd5Utf8()); + GroupKey2.getKey(configInfoWrapper2.getDataId(), configInfoWrapper2.getGroup(), configInfoWrapper2.getTenant())); + assertEquals(MD5Utils.md5Hex(configInfoWrapper2.getContent(), "UTF-8"), contentCache2.getConfigCache().getMd5Utf8()); // check if config2 is updated - Assert.assertEquals(timestamp, contentCache2.getConfigCache().getLastModifiedTs()); + assertEquals(timestamp, contentCache2.getConfigCache().getLastModifiedTs()); //check disk String contentFromDisk2 = ConfigDiskServiceFactory.getInstance() - .getContent(configInfoWrapper2.getDataId(), configInfoWrapper2.getGroup(), - configInfoWrapper2.getTenant()); - Assert.assertEquals(configInfoWrapper2.getContent(), contentFromDisk2); + .getContent(configInfoWrapper2.getDataId(), configInfoWrapper2.getGroup(), configInfoWrapper2.getTenant()); + assertEquals(configInfoWrapper2.getContent(), contentFromDisk2); } /** * test dump all for all check task. - * */ @Test - public void testDumpAllOnCheckAll() throws Exception { + void testDumpAllOnCheckAll() throws Exception { ConfigInfoWrapper configInfoWrapper1 = createNewConfig(1); ConfigInfoWrapper configInfoWrapper2 = createNewConfig(2); long timestamp = System.currentTimeMillis(); @@ -206,22 +196,19 @@ public void testDumpAllOnCheckAll() throws Exception { page.setPageItems(list); Mockito.when(configInfoPersistService.findConfigMaxId()).thenReturn(2L); - Mockito.when(configInfoPersistService.findAllConfigInfoFragment(0, PropertyUtil.getAllDumpPageSize(), false)) - .thenReturn(page); + Mockito.when(configInfoPersistService.findAllConfigInfoFragment(0, PropertyUtil.getAllDumpPageSize(), false)).thenReturn(page); ConfigInfoWrapper configInfoWrapperSingle1 = new ConfigInfoWrapper(); BeanUtils.copyProperties(configInfoWrapper1, configInfoWrapperSingle1); configInfoWrapperSingle1.setContent("content123456"); - Mockito.when( - configInfoPersistService.findConfigInfo(configInfoWrapper1.getDataId(), configInfoWrapper1.getGroup(), - configInfoWrapper1.getTenant())).thenReturn(configInfoWrapperSingle1); + Mockito.when(configInfoPersistService.findConfigInfo(configInfoWrapper1.getDataId(), configInfoWrapper1.getGroup(), + configInfoWrapper1.getTenant())).thenReturn(configInfoWrapperSingle1); ConfigInfoWrapper configInfoWrapperSingle2 = new ConfigInfoWrapper(); BeanUtils.copyProperties(configInfoWrapper2, configInfoWrapperSingle2); configInfoWrapperSingle2.setContent("content123456222"); - Mockito.when( - configInfoPersistService.findConfigInfo(configInfoWrapper2.getDataId(), configInfoWrapper2.getGroup(), - configInfoWrapper2.getTenant())).thenReturn(configInfoWrapperSingle2); + Mockito.when(configInfoPersistService.findConfigInfo(configInfoWrapper2.getDataId(), configInfoWrapper2.getGroup(), + configInfoWrapper2.getTenant())).thenReturn(configInfoWrapperSingle2); // For config 1, assign a latter time, to make sure that it would not be updated. // For config 2, assign an earlier time, to make sure that it would be updated. @@ -230,44 +217,37 @@ public void testDumpAllOnCheckAll() throws Exception { long latterTimestamp = timestamp + 999; long earlierTimestamp = timestamp - 999; String encryptedDataKey = "testEncryptedDataKey"; - ConfigCacheService.dumpWithMd5(configInfoWrapper1.getDataId(), configInfoWrapper1.getGroup(), - configInfoWrapper1.getTenant(), configInfoWrapper1.getContent(), md51, latterTimestamp, "json", - encryptedDataKey); - ConfigCacheService.dumpWithMd5(configInfoWrapper2.getDataId(), configInfoWrapper2.getGroup(), - configInfoWrapper2.getTenant(), configInfoWrapper2.getContent(), md52, earlierTimestamp, "json", - encryptedDataKey); + ConfigCacheService.dumpWithMd5(configInfoWrapper1.getDataId(), configInfoWrapper1.getGroup(), configInfoWrapper1.getTenant(), + configInfoWrapper1.getContent(), md51, latterTimestamp, "json", encryptedDataKey); + ConfigCacheService.dumpWithMd5(configInfoWrapper2.getDataId(), configInfoWrapper2.getGroup(), configInfoWrapper2.getTenant(), + configInfoWrapper2.getContent(), md52, earlierTimestamp, "json", encryptedDataKey); DumpAllTask dumpAllTask = new DumpAllTask(false); boolean process = dumpAllProcessor.process(dumpAllTask); - Assert.assertTrue(process); + assertTrue(process); //Check cache CacheItem contentCache1 = ConfigCacheService.getContentCache( - GroupKey2.getKey(configInfoWrapper1.getDataId(), configInfoWrapper1.getGroup(), - configInfoWrapper1.getTenant())); + GroupKey2.getKey(configInfoWrapper1.getDataId(), configInfoWrapper1.getGroup(), configInfoWrapper1.getTenant())); // check if config1 is not updated - Assert.assertEquals(md51, contentCache1.getConfigCache().getMd5Utf8()); - Assert.assertEquals(latterTimestamp, contentCache1.getConfigCache().getLastModifiedTs()); + assertEquals(md51, contentCache1.getConfigCache().getMd5Utf8()); + assertEquals(latterTimestamp, contentCache1.getConfigCache().getLastModifiedTs()); //check disk String contentFromDisk1 = ConfigDiskServiceFactory.getInstance() - .getContent(configInfoWrapper1.getDataId(), configInfoWrapper1.getGroup(), - configInfoWrapper1.getTenant()); - Assert.assertEquals(configInfoWrapper1.getContent(), contentFromDisk1); + .getContent(configInfoWrapper1.getDataId(), configInfoWrapper1.getGroup(), configInfoWrapper1.getTenant()); + assertEquals(configInfoWrapper1.getContent(), contentFromDisk1); //Check cache CacheItem contentCache2 = ConfigCacheService.getContentCache( - GroupKey2.getKey(configInfoWrapper2.getDataId(), configInfoWrapper2.getGroup(), - configInfoWrapper2.getTenant())); + GroupKey2.getKey(configInfoWrapper2.getDataId(), configInfoWrapper2.getGroup(), configInfoWrapper2.getTenant())); // check if config2 is updated - Assert.assertEquals(MD5Utils.md5Hex(configInfoWrapperSingle2.getContent(), "UTF-8"), - contentCache2.getConfigCache().getMd5Utf8()); - Assert.assertEquals(configInfoWrapper2.getLastModified(), contentCache2.getConfigCache().getLastModifiedTs()); + assertEquals(MD5Utils.md5Hex(configInfoWrapperSingle2.getContent(), "UTF-8"), contentCache2.getConfigCache().getMd5Utf8()); + assertEquals(configInfoWrapper2.getLastModified(), contentCache2.getConfigCache().getLastModifiedTs()); //check disk String contentFromDisk2 = ConfigDiskServiceFactory.getInstance() - .getContent(configInfoWrapper2.getDataId(), configInfoWrapper2.getGroup(), - configInfoWrapper2.getTenant()); - Assert.assertEquals(configInfoWrapperSingle2.getContent(), contentFromDisk2); + .getContent(configInfoWrapper2.getDataId(), configInfoWrapper2.getGroup(), configInfoWrapper2.getTenant()); + assertEquals(configInfoWrapperSingle2.getContent(), contentFromDisk2); } - + } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/merge/MergeDatumServiceTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/merge/MergeDatumServiceTest.java index 4cc30a0431f..f2eeeb570d4 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/merge/MergeDatumServiceTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/merge/MergeDatumServiceTest.java @@ -30,21 +30,21 @@ import com.alibaba.nacos.persistence.model.Page; import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.utils.ApplicationUtils; -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.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.util.ReflectionTestUtils; import java.util.ArrayList; import java.util.List; import static com.alibaba.nacos.persistence.constants.PersistenceConstant.CONFIG_MODEL_RAFT_GROUP; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; @@ -52,8 +52,8 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; -@RunWith(SpringJUnit4ClassRunner.class) -public class MergeDatumServiceTest { +@ExtendWith(SpringExtension.class) +class MergeDatumServiceTest { @Mock ConfigInfoPersistService configInfoPersistService; @@ -67,37 +67,35 @@ public class MergeDatumServiceTest { @Mock ProtocolManager protocolManager; - @Mock - private DataSourceService dataSourceService; - MockedStatic envUtilMockedStatic; MockedStatic applicationUtilsMockedStaticc; + @Mock + private DataSourceService dataSourceService; + private MergeDatumService mergeDatumService; - @Before - public void setUp() { + @BeforeEach + void setUp() { envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); applicationUtilsMockedStaticc = Mockito.mockStatic(ApplicationUtils.class); - applicationUtilsMockedStaticc.when(() -> ApplicationUtils.getBean(eq(ProtocolManager.class))) - .thenReturn(protocolManager); + applicationUtilsMockedStaticc.when(() -> ApplicationUtils.getBean(eq(ProtocolManager.class))).thenReturn(protocolManager); ReflectionTestUtils.setField(DynamicDataSource.getInstance(), "localDataSourceService", dataSourceService); ReflectionTestUtils.setField(DynamicDataSource.getInstance(), "basicDataSourceService", dataSourceService); - mergeDatumService = new MergeDatumService(configInfoPersistService, configInfoAggrPersistService, - configInfoTagPersistService); + mergeDatumService = new MergeDatumService(configInfoPersistService, configInfoAggrPersistService, configInfoTagPersistService); } - @After - public void after() { + @AfterEach + void after() { envUtilMockedStatic.close(); applicationUtilsMockedStaticc.close(); } @Test - public void testSplitList() { + void testSplitList() { String dataId = "dataID"; int count = 5; List configList = new ArrayList<>(); @@ -119,11 +117,11 @@ public void testSplitList() { for (int j = 0; j < indexList.size(); j++) { ConfigInfoChanged configInfoChanged = indexList.get(j); actualCount++; - Assert.assertEquals(configInfoChanged, configList.get((j * count) + i)); + assertEquals(configInfoChanged, configList.get((j * count) + i)); } } - Assert.assertEquals(originalCount, actualCount); + assertEquals(originalCount, actualCount); } @@ -136,7 +134,7 @@ private ConfigInfoChanged create(String dataID, int i) { } @Test - public void executeMergeConfigTask() { + void executeMergeConfigTask() { envUtilMockedStatic.when(() -> EnvUtil.getProperty(eq("nacos.config.retention.days"))).thenReturn("10"); ConfigInfoChanged hasDatum = new ConfigInfoChanged(); hasDatum.setDataId("hasDatumdataId1"); @@ -170,7 +168,7 @@ public void executeMergeConfigTask() { } @Test - public void testAddMergeTaskExternalModel() { + void testAddMergeTaskExternalModel() { String dataId = "dataId12345"; String group = "group123"; String tenant = "tenant1234"; @@ -183,7 +181,7 @@ public void testAddMergeTaskExternalModel() { } @Test - public void testAddMergeTaskEmbeddedAndStandAloneModel() { + void testAddMergeTaskEmbeddedAndStandAloneModel() { DatasourceConfiguration.setEmbeddedStorage(true); envUtilMockedStatic.when(() -> EnvUtil.getStandaloneMode()).thenReturn(true); @@ -198,7 +196,7 @@ public void testAddMergeTaskEmbeddedAndStandAloneModel() { } @Test - public void testAddMergeTaskEmbeddedAndClusterModelLeader() { + void testAddMergeTaskEmbeddedAndClusterModelLeader() { DatasourceConfiguration.setEmbeddedStorage(true); envUtilMockedStatic.when(() -> EnvUtil.getStandaloneMode()).thenReturn(false); @@ -217,7 +215,7 @@ public void testAddMergeTaskEmbeddedAndClusterModelLeader() { } @Test - public void testAddMergeTaskEmbeddedAndClusterModelNotLeader() { + void testAddMergeTaskEmbeddedAndClusterModelNotLeader() { DatasourceConfiguration.setEmbeddedStorage(true); envUtilMockedStatic.when(() -> EnvUtil.getStandaloneMode()).thenReturn(false); diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/merge/MergeTaskProcessorTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/merge/MergeTaskProcessorTest.java index b5163cc6436..12855d8ff61 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/merge/MergeTaskProcessorTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/merge/MergeTaskProcessorTest.java @@ -31,25 +31,25 @@ import com.alibaba.nacos.persistence.model.Page; import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.utils.InetUtils; -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.MockedStatic; import org.mockito.Mockito; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.util.ReflectionTestUtils; import java.util.concurrent.atomic.AtomicReference; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; -@RunWith(SpringJUnit4ClassRunner.class) +@ExtendWith(SpringExtension.class) public class MergeTaskProcessorTest { @@ -62,31 +62,30 @@ public class MergeTaskProcessorTest { @Mock ConfigInfoTagPersistService configInfoTagPersistService; - @Mock - private DataSourceService dataSourceService; - - @Mock - private MergeDatumService mergeDatumService; - MockedStatic envUtilMockedStatic; MergeTaskProcessor mergeTaskProcessor; MockedStatic inetUtilsMockedStatic; - @Before - public void setUp() { + @Mock + private DataSourceService dataSourceService; + + @Mock + private MergeDatumService mergeDatumService; + + @BeforeEach + void setUp() { envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); inetUtilsMockedStatic = Mockito.mockStatic(InetUtils.class); ReflectionTestUtils.setField(DynamicDataSource.getInstance(), "localDataSourceService", dataSourceService); ReflectionTestUtils.setField(DynamicDataSource.getInstance(), "basicDataSourceService", dataSourceService); - mergeTaskProcessor = new MergeTaskProcessor(configInfoPersistService, configInfoAggrPersistService, - configInfoTagPersistService, mergeDatumService); + mergeTaskProcessor = new MergeTaskProcessor(configInfoPersistService, configInfoAggrPersistService, configInfoTagPersistService, + mergeDatumService); inetUtilsMockedStatic.when(InetUtils::getSelfIP).thenReturn("127.0.0.1"); - + after(); } - @Before public void after() { envUtilMockedStatic.close(); inetUtilsMockedStatic.close(); @@ -96,7 +95,7 @@ public void after() { * test aggr has datum and merge it expect: 1.config to be inserted 2.config data change event to be published */ @Test - public void testMergerExistAggrConfig() throws InterruptedException { + void testMergerExistAggrConfig() throws InterruptedException { String dataId = "dataId12345"; String group = "group123"; String tenant = "tenant1234"; @@ -109,8 +108,8 @@ public void testMergerExistAggrConfig() throws InterruptedException { datumPage.getPageItems().add(configInfoAggr1); datumPage.getPageItems().add(configInfoAggr2); - when(configInfoAggrPersistService.findConfigInfoAggrByPage(eq(dataId), eq(group), eq(tenant), anyInt(), - anyInt())).thenReturn(datumPage); + when(configInfoAggrPersistService.findConfigInfoAggrByPage(eq(dataId), eq(group), eq(tenant), anyInt(), anyInt())).thenReturn( + datumPage); when(configInfoPersistService.insertOrUpdate(eq(null), eq(null), any(ConfigInfo.class), eq(null))).thenReturn( new ConfigOperateResult()); @@ -135,10 +134,9 @@ public Class subscribeType() { MergeDataTask mergeDataTask = new MergeDataTask(dataId, group, tenant, "127.0.0.1"); mergeTaskProcessor.process(mergeDataTask); - Mockito.verify(configInfoPersistService, times(1)) - .insertOrUpdate(eq(null), eq(null), any(ConfigInfo.class), eq(null)); + Mockito.verify(configInfoPersistService, times(1)).insertOrUpdate(eq(null), eq(null), any(ConfigInfo.class), eq(null)); Thread.sleep(1000L); - Assert.assertTrue(reference.get() != null); + assertTrue(reference.get() != null); } @@ -146,7 +144,7 @@ public Class subscribeType() { * test aggr has datum and remove it. */ @Test - public void testMergerNotExistAggrConfig() throws InterruptedException { + void testMergerNotExistAggrConfig() throws InterruptedException { String dataId = "dataId12345"; String group = "group123"; String tenant = "tenant1234"; @@ -170,21 +168,19 @@ public Class subscribeType() { }); MergeDataTask mergeDataTask = new MergeDataTask(dataId, group, tenant, "127.0.0.1"); - Mockito.doNothing().when(configInfoPersistService) - .removeConfigInfo(eq(dataId), eq(group), eq(tenant), eq("127.0.0.1"), eq(null)); + Mockito.doNothing().when(configInfoPersistService).removeConfigInfo(eq(dataId), eq(group), eq(tenant), eq("127.0.0.1"), eq(null)); //Mockito.doNothing().when(configInfoTagPersistService).removeConfigInfoTag(eq(dataId), eq(group), eq(tenant),eq(),eq("127.0.0.1"),eq(null)); mergeTaskProcessor.process(mergeDataTask); - Mockito.verify(configInfoPersistService, times(1)) - .removeConfigInfo(eq(dataId), eq(group), eq(tenant), eq("127.0.0.1"), eq(null)); + Mockito.verify(configInfoPersistService, times(1)).removeConfigInfo(eq(dataId), eq(group), eq(tenant), eq("127.0.0.1"), eq(null)); Thread.sleep(1000L); - Assert.assertTrue(reference.get() != null); + assertTrue(reference.get() != null); } /** * test aggr has no datum and remove it tag. */ @Test - public void testTagMergerNotExistAggrConfig() throws InterruptedException { + void testTagMergerNotExistAggrConfig() throws InterruptedException { String dataId = "dataId12345"; String group = "group123"; String tenant = "tenant1234"; @@ -197,8 +193,7 @@ public void testTagMergerNotExistAggrConfig() throws InterruptedException { @Override public void onEvent(Event event) { ConfigDataChangeEvent event1 = (ConfigDataChangeEvent) event; - if (event1.dataId.equals(dataId) && event1.group.equals(group) && tenant.equals(event1.tenant) - && tag.equals(event1.tag)) { + if (event1.dataId.equals(dataId) && event1.group.equals(group) && tenant.equals(event1.tenant) && tag.equals(event1.tag)) { reference.set((ConfigDataChangeEvent) event); } } @@ -217,19 +212,18 @@ public Class subscribeType() { Mockito.verify(configInfoTagPersistService, times(1)) .removeConfigInfoTag(eq(dataId), eq(group), eq(tenant), eq(tag), eq("127.0.0.1"), eq(null)); Thread.sleep(1000L); - Assert.assertTrue(reference.get() != null); + assertTrue(reference.get() != null); } /** * test aggr has no datum and remove it tag. */ @Test - public void testTagMergerError() throws InterruptedException { + void testTagMergerError() throws InterruptedException { String dataId = "dataId12345"; String group = "group123"; String tenant = "tenant1234"; - when(configInfoAggrPersistService.aggrConfigInfoCount(eq(dataId), eq(group), eq(tenant))).thenThrow( - new NullPointerException()); + when(configInfoAggrPersistService.aggrConfigInfoCount(eq(dataId), eq(group), eq(tenant))).thenThrow(new NullPointerException()); MergeDataTask mergeDataTask = new MergeDataTask(dataId, group, tenant, "127.0.0.1"); diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/notify/AsyncNotifyServiceTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/notify/AsyncNotifyServiceTest.java index d0191492937..a6072adab3e 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/notify/AsyncNotifyServiceTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/notify/AsyncNotifyServiceTest.java @@ -29,14 +29,14 @@ import com.alibaba.nacos.core.cluster.ServerMemberManager; import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.utils.InetUtils; -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.MockedStatic; import org.mockito.Mockito; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.util.ReflectionTestUtils; import java.util.ArrayList; @@ -56,38 +56,38 @@ * * @author shiyiyue */ -@RunWith(SpringJUnit4ClassRunner.class) -public class AsyncNotifyServiceTest { +@ExtendWith(SpringExtension.class) +class AsyncNotifyServiceTest { @Mock ServerMemberManager serverMemberManager; - @Mock - private ConfigClusterRpcClientProxy configClusterRpcClientProxy; - MockedStatic envUtilMocked; MockedStatic configExecutorMocked; MockedStatic inetUtilsMocked; - @Before - public void setUp() { + @Mock + private ConfigClusterRpcClientProxy configClusterRpcClientProxy; + + @BeforeEach + void setUp() { envUtilMocked = Mockito.mockStatic(EnvUtil.class); configExecutorMocked = Mockito.mockStatic(ConfigExecutor.class); inetUtilsMocked = Mockito.mockStatic(InetUtils.class); inetUtilsMocked.when(InetUtils::getSelfIP).thenReturn("127.0.0.1"); } - @After - public void after() { + @AfterEach + void after() { envUtilMocked.close(); inetUtilsMocked.close(); configExecutorMocked.close(); } @Test - public void testSyncConfigChangeCallback() { + void testSyncConfigChangeCallback() { long timeStamp = System.currentTimeMillis(); Member member1 = new Member(); member1.setIp("testip1" + timeStamp); @@ -96,17 +96,15 @@ public void testSyncConfigChangeCallback() { ReflectionTestUtils.setField(asyncNotifyService, "configClusterRpcClientProxy", configClusterRpcClientProxy); String dataId = "testDataId" + timeStamp; String group = "testGroup"; - AsyncNotifyService.NotifySingleRpcTask notifySingleRpcTask = new AsyncNotifyService.NotifySingleRpcTask(dataId, - group, null, null, 0, false, false, member1); - configExecutorMocked.when( - () -> ConfigExecutor.scheduleAsyncNotify(any(Runnable.class), anyLong(), any(TimeUnit.class))) + AsyncNotifyService.NotifySingleRpcTask notifySingleRpcTask = new AsyncNotifyService.NotifySingleRpcTask(dataId, group, null, null, + 0, false, false, member1); + configExecutorMocked.when(() -> ConfigExecutor.scheduleAsyncNotify(any(Runnable.class), anyLong(), any(TimeUnit.class))) .thenAnswer(invocation -> null); notifySingleRpcTask.setBatch(true); notifySingleRpcTask.setTag("test"); notifySingleRpcTask.setBeta(false); - AsyncRpcNotifyCallBack asyncRpcNotifyCallBack = new AsyncRpcNotifyCallBack(asyncNotifyService, - notifySingleRpcTask); + AsyncRpcNotifyCallBack asyncRpcNotifyCallBack = new AsyncRpcNotifyCallBack(asyncNotifyService, notifySingleRpcTask); ConfigChangeClusterSyncResponse successResponse = new ConfigChangeClusterSyncResponse(); //1. success response asyncRpcNotifyCallBack.onResponse(successResponse); @@ -118,15 +116,15 @@ public void testSyncConfigChangeCallback() { // expect schedule twice fail or exception response. configExecutorMocked.verify( - () -> ConfigExecutor.scheduleAsyncNotify(any(AsyncNotifyService.AsyncRpcTask.class), anyLong(), - any(TimeUnit.class)), times(2)); + () -> ConfigExecutor.scheduleAsyncNotify(any(AsyncNotifyService.AsyncRpcTask.class), anyLong(), any(TimeUnit.class)), + times(2)); } /** * test HandleConfigDataChangeEvent. expect create a AsyncRpcTask and execute in ConfigExecutor. */ @Test - public void testHandleConfigDataChangeEvent() { + void testHandleConfigDataChangeEvent() { long timeStamp = System.currentTimeMillis(); List memberList = new ArrayList<>(); @@ -148,23 +146,20 @@ public void testHandleConfigDataChangeEvent() { Mockito.when(serverMemberManager.allMembersWithoutSelf()).thenReturn(memberList); - configExecutorMocked.when( - () -> ConfigExecutor.scheduleAsyncNotify(any(Runnable.class), anyLong(), any(TimeUnit.class))) + configExecutorMocked.when(() -> ConfigExecutor.scheduleAsyncNotify(any(Runnable.class), anyLong(), any(TimeUnit.class))) .thenAnswer(invocation -> null); String dataId = "testDataId" + timeStamp; String group = "testGroup"; AsyncNotifyService asyncNotifyService = new AsyncNotifyService(serverMemberManager); - asyncNotifyService.handleConfigDataChangeEvent( - new ConfigDataChangeEvent(dataId, group, System.currentTimeMillis())); + asyncNotifyService.handleConfigDataChangeEvent(new ConfigDataChangeEvent(dataId, group, System.currentTimeMillis())); // expect schedule twice fail or exception response. - configExecutorMocked.verify( - () -> ConfigExecutor.executeAsyncNotify(any(AsyncNotifyService.AsyncRpcTask.class)), times(1)); + configExecutorMocked.verify(() -> ConfigExecutor.executeAsyncNotify(any(AsyncNotifyService.AsyncRpcTask.class)), times(1)); } @Test - public void testExecuteAsyncRpcTask() throws Exception { + void testExecuteAsyncRpcTask() throws Exception { long timeStamp = System.currentTimeMillis(); String dataId = "testDataId" + timeStamp; String group = "testGroup"; @@ -189,9 +184,8 @@ public void testExecuteAsyncRpcTask() throws Exception { for (Member member : memberList) { // grpc report data change only - rpcQueue.add( - new AsyncNotifyService.NotifySingleRpcTask(dataId, group, null, null, System.currentTimeMillis(), - false, false, member)); + rpcQueue.add(new AsyncNotifyService.NotifySingleRpcTask(dataId, group, null, null, System.currentTimeMillis(), false, false, + member)); } AsyncNotifyService asyncNotifyService = new AsyncNotifyService(serverMemberManager); @@ -201,18 +195,14 @@ public void testExecuteAsyncRpcTask() throws Exception { Mockito.when(serverMemberManager.hasMember(eq(member1.getAddress()))).thenReturn(true); Mockito.when(serverMemberManager.hasMember(eq(member2.getAddress()))).thenReturn(true); Mockito.when(serverMemberManager.hasMember(eq(member3.getAddress()))).thenReturn(true); - Mockito.when(serverMemberManager.stateCheck(eq(member1.getAddress()), eq(HEALTHY_CHECK_STATUS))) - .thenReturn(true); - Mockito.when(serverMemberManager.stateCheck(eq(member2.getAddress()), eq(HEALTHY_CHECK_STATUS))) - .thenReturn(true); + Mockito.when(serverMemberManager.stateCheck(eq(member1.getAddress()), eq(HEALTHY_CHECK_STATUS))).thenReturn(true); + Mockito.when(serverMemberManager.stateCheck(eq(member2.getAddress()), eq(HEALTHY_CHECK_STATUS))).thenReturn(true); // mock stateCheck fail before notify member3 - Mockito.when(serverMemberManager.stateCheck(eq(member3.getAddress()), eq(HEALTHY_CHECK_STATUS))) - .thenReturn(false); + Mockito.when(serverMemberManager.stateCheck(eq(member3.getAddress()), eq(HEALTHY_CHECK_STATUS))).thenReturn(false); //mock syncConfigChange exception when notify member2 Mockito.doThrow(new NacosException()).when(configClusterRpcClientProxy) .syncConfigChange(eq(member2), any(ConfigChangeClusterSyncRequest.class), any(RequestCallBack.class)); - configExecutorMocked.when( - () -> ConfigExecutor.scheduleAsyncNotify(any(Runnable.class), anyLong(), any(TimeUnit.class))) + configExecutorMocked.when(() -> ConfigExecutor.scheduleAsyncNotify(any(Runnable.class), anyLong(), any(TimeUnit.class))) .thenAnswer(invocation -> null); asyncNotifyService.executeAsyncRpcTask(rpcQueue); @@ -226,8 +216,8 @@ public void testExecuteAsyncRpcTask() throws Exception { //verify scheduleAsyncNotify member2 & member3 in task when syncConfigChange fail configExecutorMocked.verify( - () -> ConfigExecutor.scheduleAsyncNotify(any(AsyncNotifyService.AsyncRpcTask.class), anyLong(), - any(TimeUnit.class)), times(2)); + () -> ConfigExecutor.scheduleAsyncNotify(any(AsyncNotifyService.AsyncRpcTask.class), anyLong(), any(TimeUnit.class)), + times(2)); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/repository/ConfigRowMapperInjectorTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/repository/ConfigRowMapperInjectorTest.java index 35df8476961..3e93e4f69c4 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/repository/ConfigRowMapperInjectorTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/repository/ConfigRowMapperInjectorTest.java @@ -38,29 +38,29 @@ import com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.ConfigInfoTagWrapperRowMapper; import com.alibaba.nacos.persistence.repository.RowMapperManager; import com.mysql.cj.jdbc.result.ResultSetImpl; -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.Mockito; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import java.sql.SQLException; import java.sql.Timestamp; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.eq; -@RunWith(SpringJUnit4ClassRunner.class) -public class ConfigRowMapperInjectorTest { +@ExtendWith(SpringExtension.class) +class ConfigRowMapperInjectorTest { @Test - public void testInit() { + void testInit() { ConfigRowMapperInjector configRowMapperInjector = new ConfigRowMapperInjector(); - Assert.assertEquals(ConfigRowMapperInjector.CONFIG_INFO_WRAPPER_ROW_MAPPER, RowMapperManager.getRowMapper( - ConfigRowMapperInjector.CONFIG_INFO_WRAPPER_ROW_MAPPER.getClass().getCanonicalName())); + assertEquals(ConfigRowMapperInjector.CONFIG_INFO_WRAPPER_ROW_MAPPER, + RowMapperManager.getRowMapper(ConfigRowMapperInjector.CONFIG_INFO_WRAPPER_ROW_MAPPER.getClass().getCanonicalName())); } @Test - public void testConfigInfoTagWrapperRowMapper() throws SQLException { + void testConfigInfoTagWrapperRowMapper() throws SQLException { ConfigInfoTagWrapper preConfig = new ConfigInfoTagWrapper(); preConfig.setDataId("testDataId"); preConfig.setGroup("group_id11"); @@ -87,12 +87,12 @@ public void testConfigInfoTagWrapperRowMapper() throws SQLException { Mockito.when(resultSet.getString(eq("tag_id"))).thenReturn(preConfig.getTag()); ConfigInfoTagWrapperRowMapper configInfoWrapperRowMapper = new ConfigInfoTagWrapperRowMapper(); ConfigInfoTagWrapper configInfoWrapper = configInfoWrapperRowMapper.mapRow(resultSet, 10); - Assert.assertEquals(preConfig, configInfoWrapper); - Assert.assertEquals(preConfig.getTag(), configInfoWrapper.getTag()); + assertEquals(preConfig, configInfoWrapper); + assertEquals(preConfig.getTag(), configInfoWrapper.getTag()); } @Test - public void testConfigInfo4BetaRowMapper() throws SQLException { + void testConfigInfo4BetaRowMapper() throws SQLException { ConfigInfo4Beta preConfig = new ConfigInfo4Beta(); preConfig.setDataId("testDataId"); preConfig.setGroup("group_id11"); @@ -117,12 +117,12 @@ public void testConfigInfo4BetaRowMapper() throws SQLException { Mockito.when(resultSet.getString(eq("encrypted_data_key"))).thenReturn(preConfig.getEncryptedDataKey()); ConfigInfo4BetaRowMapper configInfoWrapperRowMapper = new ConfigInfo4BetaRowMapper(); ConfigInfo4Beta configInfoWrapper = configInfoWrapperRowMapper.mapRow(resultSet, 10); - Assert.assertEquals(preConfig, configInfoWrapper); - Assert.assertEquals(preConfig.getBetaIps(), configInfoWrapper.getBetaIps()); + assertEquals(preConfig, configInfoWrapper); + assertEquals(preConfig.getBetaIps(), configInfoWrapper.getBetaIps()); } @Test - public void testConfigInfoBetaWrapperRowMapper() throws SQLException { + void testConfigInfoBetaWrapperRowMapper() throws SQLException { ConfigInfoBetaWrapper preConfig = new ConfigInfoBetaWrapper(); preConfig.setDataId("testDataId"); preConfig.setGroup("group_id11"); @@ -147,11 +147,11 @@ public void testConfigInfoBetaWrapperRowMapper() throws SQLException { Mockito.when(resultSet.getString(eq("encrypted_data_key"))).thenReturn(preConfig.getEncryptedDataKey()); ConfigInfoBetaWrapperRowMapper configInfoWrapperRowMapper = new ConfigInfoBetaWrapperRowMapper(); ConfigInfoBetaWrapper configInfoWrapper = configInfoWrapperRowMapper.mapRow(resultSet, 10); - Assert.assertEquals(preConfig, configInfoWrapper); + assertEquals(preConfig, configInfoWrapper); } @Test - public void testConfigAdvanceInfoRowMapper() throws SQLException { + void testConfigAdvanceInfoRowMapper() throws SQLException { ConfigAdvanceInfo preConfig = new ConfigAdvanceInfo(); preConfig.setModifyTime(System.currentTimeMillis()); preConfig.setCreateTime(System.currentTimeMillis()); @@ -174,11 +174,11 @@ public void testConfigAdvanceInfoRowMapper() throws SQLException { Mockito.when(resultSet.getString(eq("c_schema"))).thenReturn(preConfig.getSchema()); ConfigRowMapperInjector.ConfigAdvanceInfoRowMapper configInfoWrapperRowMapper = new ConfigRowMapperInjector.ConfigAdvanceInfoRowMapper(); ConfigAdvanceInfo configInfoWrapper = configInfoWrapperRowMapper.mapRow(resultSet, 10); - Assert.assertEquals(preConfig, configInfoWrapper); + assertEquals(preConfig, configInfoWrapper); } @Test - public void testConfigAllInfoRowMapper() throws SQLException { + void testConfigAllInfoRowMapper() throws SQLException { ConfigAllInfo preConfig = new ConfigAllInfo(); preConfig.setDataId("testDataId"); preConfig.setGroup("group_id11"); @@ -206,11 +206,11 @@ public void testConfigAllInfoRowMapper() throws SQLException { ConfigRowMapperInjector.ConfigAllInfoRowMapper configInfoWrapperRowMapper = new ConfigRowMapperInjector.ConfigAllInfoRowMapper(); ConfigAllInfo configInfoWrapper = configInfoWrapperRowMapper.mapRow(resultSet, 10); - Assert.assertEquals(preConfig, configInfoWrapper); + assertEquals(preConfig, configInfoWrapper); } @Test - public void testConfigInfoRowMapper() throws SQLException { + void testConfigInfoRowMapper() throws SQLException { ConfigInfo preConfig = new ConfigInfo(); preConfig.setDataId("testDataId"); @@ -234,11 +234,11 @@ public void testConfigInfoRowMapper() throws SQLException { Mockito.when(resultSet.getString(eq("encrypted_data_key"))).thenReturn(preConfig.getEncryptedDataKey()); ConfigRowMapperInjector.ConfigInfoRowMapper configInfoWrapperRowMapper = new ConfigRowMapperInjector.ConfigInfoRowMapper(); ConfigInfo configInfoWrapper = configInfoWrapperRowMapper.mapRow(resultSet, 10); - Assert.assertEquals(preConfig, configInfoWrapper); + assertEquals(preConfig, configInfoWrapper); } @Test - public void testConfigInfoWrapperRowMapper() throws SQLException { + void testConfigInfoWrapperRowMapper() throws SQLException { ConfigInfoWrapper preConfig = new ConfigInfoWrapper(); preConfig.setDataId("testDataId"); @@ -264,12 +264,12 @@ public void testConfigInfoWrapperRowMapper() throws SQLException { Mockito.when(resultSet.getString(eq("encrypted_data_key"))).thenReturn(preConfig.getEncryptedDataKey()); ConfigRowMapperInjector.ConfigInfoWrapperRowMapper configInfoWrapperRowMapper = new ConfigRowMapperInjector.ConfigInfoWrapperRowMapper(); ConfigInfoWrapper configInfoWrapper = configInfoWrapperRowMapper.mapRow(resultSet, 10); - Assert.assertEquals(preConfig, configInfoWrapper); + assertEquals(preConfig, configInfoWrapper); } @Test - public void testConfigInfo4TagRowMapper() throws SQLException { + void testConfigInfo4TagRowMapper() throws SQLException { ConfigInfo4Tag preConfig = new ConfigInfo4Tag(); preConfig.setDataId("testDataId"); @@ -295,12 +295,12 @@ public void testConfigInfo4TagRowMapper() throws SQLException { Mockito.when(resultSet.getString(eq("encrypted_data_key"))).thenReturn(preConfig.getEncryptedDataKey()); ConfigRowMapperInjector.ConfigInfo4TagRowMapper configInfoWrapperRowMapper = new ConfigRowMapperInjector.ConfigInfo4TagRowMapper(); ConfigInfo4Tag configInfoWrapper = configInfoWrapperRowMapper.mapRow(resultSet, 10); - Assert.assertEquals(preConfig, configInfoWrapper); + assertEquals(preConfig, configInfoWrapper); } @Test - public void testConfigInfoBaseRowMapper() throws SQLException { + void testConfigInfoBaseRowMapper() throws SQLException { ConfigInfoBase preConfig = new ConfigInfoBase(); preConfig.setDataId("testDataId"); @@ -314,12 +314,12 @@ public void testConfigInfoBaseRowMapper() throws SQLException { Mockito.when(resultSet.getLong(eq("id"))).thenReturn(preConfig.getId()); ConfigRowMapperInjector.ConfigInfoBaseRowMapper configInfoWrapperRowMapper = new ConfigRowMapperInjector.ConfigInfoBaseRowMapper(); ConfigInfoBase configInfoWrapper = configInfoWrapperRowMapper.mapRow(resultSet, 10); - Assert.assertEquals(preConfig, configInfoWrapper); + assertEquals(preConfig, configInfoWrapper); } @Test - public void testConfigInfoAggrRowMapper() throws SQLException { + void testConfigInfoAggrRowMapper() throws SQLException { ConfigInfoAggr preConfig = new ConfigInfoAggr(); preConfig.setDataId("testDataId"); @@ -338,12 +338,12 @@ public void testConfigInfoAggrRowMapper() throws SQLException { ConfigRowMapperInjector.ConfigInfoAggrRowMapper configInfoWrapperRowMapper = new ConfigRowMapperInjector.ConfigInfoAggrRowMapper(); ConfigInfoAggr configInfoWrapper = configInfoWrapperRowMapper.mapRow(resultSet, 10); - Assert.assertEquals(preConfig, configInfoWrapper); + assertEquals(preConfig, configInfoWrapper); } @Test - public void testConfigInfoChangedRowMapper() throws SQLException { + void testConfigInfoChangedRowMapper() throws SQLException { ConfigInfoChanged preConfig = new ConfigInfoChanged(); preConfig.setDataId("testDataId"); @@ -355,12 +355,12 @@ public void testConfigInfoChangedRowMapper() throws SQLException { Mockito.when(resultSet.getString(eq("tenant_id"))).thenReturn(preConfig.getTenant()); ConfigInfoChangedRowMapper configInfoWrapperRowMapper = new ConfigInfoChangedRowMapper(); ConfigInfoChanged configInfoWrapper = configInfoWrapperRowMapper.mapRow(resultSet, 10); - Assert.assertEquals(preConfig, configInfoWrapper); + assertEquals(preConfig, configInfoWrapper); } @Test - public void testConfigHistoryRowMapper() throws SQLException { + void testConfigHistoryRowMapper() throws SQLException { ConfigHistoryInfo preConfig = new ConfigHistoryInfo(); preConfig.setDataId("testDataId"); @@ -387,12 +387,12 @@ public void testConfigHistoryRowMapper() throws SQLException { ConfigRowMapperInjector.ConfigHistoryRowMapper configInfoWrapperRowMapper = new ConfigRowMapperInjector.ConfigHistoryRowMapper(); ConfigHistoryInfo configInfoWrapper = configInfoWrapperRowMapper.mapRow(resultSet, 10); - Assert.assertEquals(preConfig, configInfoWrapper); + assertEquals(preConfig, configInfoWrapper); } @Test - public void testConfigHistoryDetailRowMapper() throws SQLException { + void testConfigHistoryDetailRowMapper() throws SQLException { ConfigHistoryInfo preConfig = new ConfigHistoryInfo(); preConfig.setDataId("testDataId"); @@ -427,12 +427,12 @@ public void testConfigHistoryDetailRowMapper() throws SQLException { ConfigHistoryDetailRowMapper configInfoWrapperRowMapper = new ConfigHistoryDetailRowMapper(); ConfigHistoryInfo configInfoWrapper = configInfoWrapperRowMapper.mapRow(resultSet, 10); - Assert.assertEquals(preConfig, configInfoWrapper); + assertEquals(preConfig, configInfoWrapper); } @Test - public void testConfigInfoStateWrapperRowMapper() throws SQLException { + void testConfigInfoStateWrapperRowMapper() throws SQLException { ConfigInfoStateWrapper preConfig = new ConfigInfoStateWrapper(); preConfig.setDataId("testDataId"); @@ -448,12 +448,12 @@ public void testConfigInfoStateWrapperRowMapper() throws SQLException { Mockito.when(resultSet.getLong(eq("id"))).thenReturn(preConfig.getId()); ConfigInfoStateWrapperRowMapper configInfoWrapperRowMapper = new ConfigInfoStateWrapperRowMapper(); ConfigInfoStateWrapper configInfoWrapper = configInfoWrapperRowMapper.mapRow(resultSet, 10); - Assert.assertEquals(preConfig, configInfoWrapper); + assertEquals(preConfig, configInfoWrapper); } @Test - public void testConfigKeyRowMapper() throws SQLException { + void testConfigKeyRowMapper() throws SQLException { ConfigKey preConfig = new ConfigKey(); preConfig.setDataId("testDataId"); preConfig.setGroup("group_id11"); @@ -465,7 +465,7 @@ public void testConfigKeyRowMapper() throws SQLException { ConfigRowMapperInjector.ConfigKeyRowMapper configInfoWrapperRowMapper = new ConfigRowMapperInjector.ConfigKeyRowMapper(); ConfigKey configInfoWrapper = configInfoWrapperRowMapper.mapRow(resultSet, 10); - Assert.assertEquals(preConfig, configInfoWrapper); + assertEquals(preConfig, configInfoWrapper); } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoAggrPersistServiceImplTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoAggrPersistServiceImplTest.java index c6607c3c98e..33b45b4ade9 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoAggrPersistServiceImplTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoAggrPersistServiceImplTest.java @@ -24,15 +24,14 @@ import com.alibaba.nacos.persistence.repository.embedded.EmbeddedStorageContextHolder; import com.alibaba.nacos.persistence.repository.embedded.operate.DatabaseOperate; import com.alibaba.nacos.sys.env.EnvUtil; -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.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.ArrayList; import java.util.HashMap; @@ -41,22 +40,20 @@ import static com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.CONFIG_INFO_AGGR_ROW_MAPPER; import static com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.CONFIG_INFO_CHANGED_ROW_MAPPER; +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.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; /** - * test for embedded config aggr. + * test for embedded config aggr. + * * @author shiyiyue */ -@RunWith(SpringJUnit4ClassRunner.class) -public class EmbeddedConfigInfoAggrPersistServiceImplTest { - - private EmbeddedConfigInfoAggrPersistServiceImpl embededConfigInfoAggrPersistService; - - @Mock - private DataSourceService dataSourceService; +@ExtendWith(SpringExtension.class) +class EmbeddedConfigInfoAggrPersistServiceImplTest { MockedStatic envUtilMockedStatic; @@ -70,28 +67,32 @@ public class EmbeddedConfigInfoAggrPersistServiceImplTest { @Mock DatabaseOperate databaseOperate; - @Before - public void before() { + private EmbeddedConfigInfoAggrPersistServiceImpl embededConfigInfoAggrPersistService; + + @Mock + private DataSourceService dataSourceService; + + @BeforeEach + void before() { embeddedStorageContextHolderMockedStatic = Mockito.mockStatic(EmbeddedStorageContextHolder.class); dynamicDataSourceMockedStatic = Mockito.mockStatic(DynamicDataSource.class); envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); when(DynamicDataSource.getInstance()).thenReturn(dynamicDataSource); when(dynamicDataSource.getDataSource()).thenReturn(dataSourceService); when(dataSourceService.getDataSourceType()).thenReturn("derby"); - envUtilMockedStatic.when(() -> EnvUtil.getProperty(anyString(), eq(Boolean.class), eq(false))) - .thenReturn(false); + envUtilMockedStatic.when(() -> EnvUtil.getProperty(anyString(), eq(Boolean.class), eq(false))).thenReturn(false); embededConfigInfoAggrPersistService = new EmbeddedConfigInfoAggrPersistServiceImpl(databaseOperate); } - @After - public void after() { + @AfterEach + void after() { dynamicDataSourceMockedStatic.close(); envUtilMockedStatic.close(); embeddedStorageContextHolderMockedStatic.close(); } @Test - public void testAddAggrConfigInfoOfEqualContent() { + void testAddAggrConfigInfoOfEqualContent() { String dataId = "dataId111"; String group = "group"; String tenant = "tenant"; @@ -101,18 +102,17 @@ public void testAddAggrConfigInfoOfEqualContent() { //mock query datumId and equal with current content param. String existContent = "content1234"; - Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant, datumId}), - eq(String.class))).thenReturn(existContent); + Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant, datumId}), eq(String.class))) + .thenReturn(existContent); //mock insert success Mockito.when(databaseOperate.update(any(List.class))).thenReturn(true); - boolean result = embededConfigInfoAggrPersistService.addAggrConfigInfo(dataId, group, tenant, datumId, appName, - content); - Assert.assertTrue(result); + boolean result = embededConfigInfoAggrPersistService.addAggrConfigInfo(dataId, group, tenant, datumId, appName, content); + assertTrue(result); } @Test - public void testAddAggrConfigInfoOfAddNewContent() { + void testAddAggrConfigInfoOfAddNewContent() { String dataId = "dataId111"; String group = "group"; String tenant = "tenant"; @@ -121,19 +121,18 @@ public void testAddAggrConfigInfoOfAddNewContent() { String content = "content1234"; //mock query datumId and return null. - Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant, datumId}), - eq(String.class))).thenReturn(null); + Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant, datumId}), eq(String.class))) + .thenReturn(null); //mock insert success Mockito.when(databaseOperate.update(any(List.class))).thenReturn(true); //execute - boolean result = embededConfigInfoAggrPersistService.addAggrConfigInfo(dataId, group, tenant, datumId, appName, - content); - Assert.assertTrue(result); + boolean result = embededConfigInfoAggrPersistService.addAggrConfigInfo(dataId, group, tenant, datumId, appName, content); + assertTrue(result); } @Test - public void testAddAggrConfigInfoOfUpdateNotEqualContent() { + void testAddAggrConfigInfoOfUpdateNotEqualContent() { String dataId = "dataId111"; String group = "group"; String tenant = "tenant"; @@ -143,33 +142,29 @@ public void testAddAggrConfigInfoOfUpdateNotEqualContent() { //mock query datumId String existContent = "existContent111"; - Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant, datumId}), - eq(String.class))).thenReturn(existContent); + Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant, datumId}), eq(String.class))) + .thenReturn(existContent); //mock update success,return 1 Mockito.when(databaseOperate.update(any(List.class))).thenReturn(true); //mock update content - boolean result = embededConfigInfoAggrPersistService.addAggrConfigInfo(dataId, group, tenant, datumId, appName, - content); - Assert.assertTrue(result); + boolean result = embededConfigInfoAggrPersistService.addAggrConfigInfo(dataId, group, tenant, datumId, appName, content); + assertTrue(result); } @Test - public void testBatchPublishAggrSuccess() { + void testBatchPublishAggrSuccess() { String dataId = "dataId111"; String group = "group"; String tenant = "tenant"; //mock query datumId and equal with current content param. - Mockito.when( - databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant, "d1"}), eq(String.class))) + Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant, "d1"}), eq(String.class))) .thenReturn("c1"); - Mockito.when( - databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant, "d2"}), eq(String.class))) + Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant, "d2"}), eq(String.class))) .thenReturn("c2"); - Mockito.when( - databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant, "d3"}), eq(String.class))) + Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant, "d3"}), eq(String.class))) .thenReturn("c3"); Mockito.when(databaseOperate.update(any(List.class))).thenReturn(true); @@ -179,11 +174,11 @@ public void testBatchPublishAggrSuccess() { datumMap.put("d3", "c3"); String appName = "appname1234"; boolean result = embededConfigInfoAggrPersistService.batchPublishAggr(dataId, group, tenant, datumMap, appName); - Assert.assertTrue(result); + assertTrue(result); } @Test - public void testAggrConfigInfoCount() { + void testAggrConfigInfoCount() { String dataId = "dataId11122"; String group = "group"; String tenant = "tenant"; @@ -192,38 +187,37 @@ public void testAggrConfigInfoCount() { Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), eq(Integer.class))) .thenReturn(new Integer(101)); int result = embededConfigInfoAggrPersistService.aggrConfigInfoCount(dataId, group, tenant); - Assert.assertEquals(101, result); + assertEquals(101, result); } @Test - public void testFindConfigInfoAggrByPage() { + void testFindConfigInfoAggrByPage() { String dataId = "dataId111"; String group = "group"; String tenant = "tenant"; //mock query count. - Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), eq(Integer.class))) - .thenReturn(101); + Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), eq(Integer.class))).thenReturn(101); //mock query page list List configInfoAggrs = new ArrayList<>(); configInfoAggrs.add(new ConfigInfoAggr()); configInfoAggrs.add(new ConfigInfoAggr()); configInfoAggrs.add(new ConfigInfoAggr()); - Mockito.when(databaseOperate.queryMany(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_AGGR_ROW_MAPPER))).thenReturn(configInfoAggrs); + Mockito.when(databaseOperate.queryMany(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_AGGR_ROW_MAPPER))) + .thenReturn(configInfoAggrs); int pageNo = 1; int pageSize = 120; - Page configInfoAggrByPage = embededConfigInfoAggrPersistService.findConfigInfoAggrByPage(dataId, - group, tenant, pageNo, pageSize); - Assert.assertEquals(101, configInfoAggrByPage.getTotalCount()); - Assert.assertEquals(configInfoAggrs, configInfoAggrByPage.getPageItems()); + Page configInfoAggrByPage = embededConfigInfoAggrPersistService.findConfigInfoAggrByPage(dataId, group, tenant, + pageNo, pageSize); + assertEquals(101, configInfoAggrByPage.getTotalCount()); + assertEquals(configInfoAggrs, configInfoAggrByPage.getPageItems()); } @Test - public void testFindAllAggrGroup() { + void testFindAllAggrGroup() { List configList = new ArrayList<>(); configList.add(create("dataId", 0)); configList.add(create("dataId", 1)); @@ -232,7 +226,7 @@ public void testFindAllAggrGroup() { .thenReturn(configList); List allAggrGroup = embededConfigInfoAggrPersistService.findAllAggrGroup(); - Assert.assertEquals(configList, allAggrGroup); + assertEquals(configList, allAggrGroup); } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoBetaPersistServiceImplTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoBetaPersistServiceImplTest.java index 9a8c859b5d6..6b053253d80 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoBetaPersistServiceImplTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoBetaPersistServiceImplTest.java @@ -28,22 +28,21 @@ import com.alibaba.nacos.persistence.repository.embedded.EmbeddedStorageContextHolder; import com.alibaba.nacos.persistence.repository.embedded.operate.DatabaseOperate; import com.alibaba.nacos.sys.env.EnvUtil; -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.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import static com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.CONFIG_INFO_BETA_WRAPPER_ROW_MAPPER; import static com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -55,13 +54,8 @@ * * @author shiyiyue */ -@RunWith(SpringJUnit4ClassRunner.class) -public class EmbeddedConfigInfoBetaPersistServiceImplTest { - - private EmbeddedConfigInfoBetaPersistServiceImpl embeddedConfigInfoBetaPersistService; - - @Mock - private DataSourceService dataSourceService; +@ExtendWith(SpringExtension.class) +class EmbeddedConfigInfoBetaPersistServiceImplTest { MockedStatic envUtilMockedStatic; @@ -75,28 +69,32 @@ public class EmbeddedConfigInfoBetaPersistServiceImplTest { @Mock DatabaseOperate databaseOperate; - @Before - public void before() { + private EmbeddedConfigInfoBetaPersistServiceImpl embeddedConfigInfoBetaPersistService; + + @Mock + private DataSourceService dataSourceService; + + @BeforeEach + void before() { embeddedStorageContextHolderMockedStatic = Mockito.mockStatic(EmbeddedStorageContextHolder.class); dynamicDataSourceMockedStatic = Mockito.mockStatic(DynamicDataSource.class); envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); when(DynamicDataSource.getInstance()).thenReturn(dynamicDataSource); when(dynamicDataSource.getDataSource()).thenReturn(dataSourceService); when(dataSourceService.getDataSourceType()).thenReturn("derby"); - envUtilMockedStatic.when(() -> EnvUtil.getProperty(anyString(), eq(Boolean.class), eq(false))) - .thenReturn(false); + envUtilMockedStatic.when(() -> EnvUtil.getProperty(anyString(), eq(Boolean.class), eq(false))).thenReturn(false); embeddedConfigInfoBetaPersistService = new EmbeddedConfigInfoBetaPersistServiceImpl(databaseOperate); } - @After - public void after() { + @AfterEach + void after() { dynamicDataSourceMockedStatic.close(); envUtilMockedStatic.close(); embeddedStorageContextHolderMockedStatic.close(); } @Test - public void testInsertOrUpdateBetaOfUpdate() { + void testInsertOrUpdateBetaOfUpdate() { String dataId = "betaDataId113"; String group = "group"; String tenant = "tenant"; @@ -107,8 +105,8 @@ public void testInsertOrUpdateBetaOfUpdate() { mockedConfigInfoStateWrapper.setTenant(tenant); mockedConfigInfoStateWrapper.setId(123456L); mockedConfigInfoStateWrapper.setLastModified(System.currentTimeMillis()); - Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) + Mockito.when( + databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) .thenReturn(mockedConfigInfoStateWrapper, mockedConfigInfoStateWrapper); //execute String betaIps = "betaips..."; @@ -118,22 +116,20 @@ public void testInsertOrUpdateBetaOfUpdate() { String content = "content111"; ConfigInfo configInfo = new ConfigInfo(dataId, group, tenant, appName, content); configInfo.setEncryptedDataKey("key34567"); - ConfigOperateResult configOperateResult = embeddedConfigInfoBetaPersistService.insertOrUpdateBeta(configInfo, - betaIps, srcIp, srcUser); + ConfigOperateResult configOperateResult = embeddedConfigInfoBetaPersistService.insertOrUpdateBeta(configInfo, betaIps, srcIp, + srcUser); //expect return obj - Assert.assertEquals(mockedConfigInfoStateWrapper.getId(), configOperateResult.getId()); - Assert.assertEquals(mockedConfigInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); + assertEquals(mockedConfigInfoStateWrapper.getId(), configOperateResult.getId()); + assertEquals(mockedConfigInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); //verify update to be invoked embeddedStorageContextHolderMockedStatic.verify( () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(configInfo.getContent()), - eq(configInfo.getMd5()), eq(betaIps), eq(srcIp), eq(srcUser), any(Timestamp.class), - eq(configInfo.getAppName()), eq(configInfo.getEncryptedDataKey()), eq(dataId), eq(group), - eq(tenant)), times(1)); - + eq(configInfo.getMd5()), eq(betaIps), eq(srcIp), eq(srcUser), eq(configInfo.getAppName()), + eq(configInfo.getEncryptedDataKey()), eq(dataId), eq(group), eq(tenant)), times(1)); } @Test - public void testInsertOrUpdateBetaOfAdd() { + void testInsertOrUpdateBetaOfAdd() { String dataId = "betaDataId113"; String group = "group113"; String tenant = "tenant113"; @@ -144,8 +140,9 @@ public void testInsertOrUpdateBetaOfAdd() { mockedConfigInfoStateWrapper.setTenant(tenant); mockedConfigInfoStateWrapper.setId(123456L); mockedConfigInfoStateWrapper.setLastModified(System.currentTimeMillis()); - Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(null).thenReturn(mockedConfigInfoStateWrapper); + Mockito.when( + databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) + .thenReturn(null).thenReturn(mockedConfigInfoStateWrapper); String betaIps = "betaips..."; String srcIp = "srcUp..."; @@ -155,21 +152,20 @@ public void testInsertOrUpdateBetaOfAdd() { ConfigInfo configInfo = new ConfigInfo(dataId, group, tenant, appName, content); configInfo.setEncryptedDataKey("key34567"); //execute - ConfigOperateResult configOperateResult = embeddedConfigInfoBetaPersistService.insertOrUpdateBeta(configInfo, - betaIps, srcIp, srcUser); + ConfigOperateResult configOperateResult = embeddedConfigInfoBetaPersistService.insertOrUpdateBeta(configInfo, betaIps, srcIp, + srcUser); //expect return obj - Assert.assertEquals(mockedConfigInfoStateWrapper.getId(), configOperateResult.getId()); - Assert.assertEquals(mockedConfigInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); + assertEquals(mockedConfigInfoStateWrapper.getId(), configOperateResult.getId()); + assertEquals(mockedConfigInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); //verify add to be invoked embeddedStorageContextHolderMockedStatic.verify( () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(dataId), eq(group), eq(tenant), - eq(configInfo.getAppName()), eq(configInfo.getContent()), eq(configInfo.getMd5()), eq(betaIps), - eq(srcIp), eq(srcUser), any(Timestamp.class), any(Timestamp.class), - eq(configInfo.getEncryptedDataKey())), times(1)); + eq(configInfo.getAppName()), eq(configInfo.getContent()), eq(configInfo.getMd5()), + eq(betaIps), eq(srcIp), eq(srcUser), eq(configInfo.getEncryptedDataKey())), times(1)); } @Test - public void testInsertOrUpdateBetaCasOfUpdate() { + void testInsertOrUpdateBetaCasOfUpdate() { String dataId = "betaDataId113"; String group = "group"; String tenant = "tenant"; @@ -180,8 +176,8 @@ public void testInsertOrUpdateBetaCasOfUpdate() { mockedConfigInfoStateWrapper.setTenant(tenant); mockedConfigInfoStateWrapper.setId(123456L); mockedConfigInfoStateWrapper.setLastModified(System.currentTimeMillis()); - Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) + Mockito.when( + databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) .thenReturn(mockedConfigInfoStateWrapper, mockedConfigInfoStateWrapper); //execute @@ -196,22 +192,21 @@ public void testInsertOrUpdateBetaCasOfUpdate() { String betaIps = "betaips..."; String srcIp = "srcUp..."; String srcUser = "srcUser..."; - ConfigOperateResult configOperateResult = embeddedConfigInfoBetaPersistService.insertOrUpdateBetaCas(configInfo, - betaIps, srcIp, srcUser); + ConfigOperateResult configOperateResult = embeddedConfigInfoBetaPersistService.insertOrUpdateBetaCas(configInfo, betaIps, srcIp, + srcUser); //expect return obj - Assert.assertEquals(mockedConfigInfoStateWrapper.getId(), configOperateResult.getId()); - Assert.assertEquals(mockedConfigInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); + assertEquals(mockedConfigInfoStateWrapper.getId(), configOperateResult.getId()); + assertEquals(mockedConfigInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); //verify cas update to be invoked embeddedStorageContextHolderMockedStatic.verify( () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(configInfo.getContent()), eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), eq(betaIps), eq(srcIp), eq(srcUser), - any(Timestamp.class), eq(appName), eq(dataId), eq(group), eq(tenant), eq(configInfo.getMd5())), - times(1)); + eq(appName), eq(dataId), eq(group), eq(tenant), eq(configInfo.getMd5())), times(1)); } @Test - public void testInsertOrUpdateBetaCasOfAdd() { + void testInsertOrUpdateBetaCasOfAdd() { String dataId = "betaDataId113"; String group = "group113"; String tenant = "tenant113"; @@ -222,8 +217,9 @@ public void testInsertOrUpdateBetaCasOfAdd() { mockedConfigInfoStateWrapper.setTenant(tenant); mockedConfigInfoStateWrapper.setId(123456L); mockedConfigInfoStateWrapper.setLastModified(System.currentTimeMillis()); - Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(null).thenReturn(mockedConfigInfoStateWrapper); + Mockito.when( + databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) + .thenReturn(null).thenReturn(mockedConfigInfoStateWrapper); String betaIps = "betaips..."; String srcIp = "srcUp..."; @@ -233,22 +229,21 @@ public void testInsertOrUpdateBetaCasOfAdd() { ConfigInfo configInfo = new ConfigInfo(dataId, group, tenant, appName, content); configInfo.setEncryptedDataKey("key34567"); //execute - ConfigOperateResult configOperateResult = embeddedConfigInfoBetaPersistService.insertOrUpdateBetaCas(configInfo, - betaIps, srcIp, srcUser); + ConfigOperateResult configOperateResult = embeddedConfigInfoBetaPersistService.insertOrUpdateBetaCas(configInfo, betaIps, srcIp, + srcUser); //expect return obj - Assert.assertEquals(mockedConfigInfoStateWrapper.getId(), configOperateResult.getId()); - Assert.assertEquals(mockedConfigInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); + assertEquals(mockedConfigInfoStateWrapper.getId(), configOperateResult.getId()); + assertEquals(mockedConfigInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); //verify add to be invoked embeddedStorageContextHolderMockedStatic.verify( () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(dataId), eq(group), eq(tenant), - eq(configInfo.getAppName()), eq(configInfo.getContent()), eq(configInfo.getMd5()), eq(betaIps), - eq(srcIp), eq(srcUser), any(Timestamp.class), any(Timestamp.class), - eq(configInfo.getEncryptedDataKey())), times(1)); + eq(configInfo.getAppName()), eq(configInfo.getContent()), eq(configInfo.getMd5()), + eq(betaIps), eq(srcIp), eq(srcUser), eq(configInfo.getEncryptedDataKey())), times(1)); } @Test - public void testRemoveConfigInfo4Beta() { + void testRemoveConfigInfo4Beta() { String dataId = "dataId456789"; String group = "group4567"; String tenant = "tenant56789o0"; @@ -259,21 +254,21 @@ public void testRemoveConfigInfo4Beta() { mockedConfigInfoStateWrapper.setTenant(tenant); mockedConfigInfoStateWrapper.setId(123456L); mockedConfigInfoStateWrapper.setLastModified(System.currentTimeMillis()); - Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(mockedConfigInfoStateWrapper); + Mockito.when( + databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) + .thenReturn(mockedConfigInfoStateWrapper); //mock remove ok Mockito.when(databaseOperate.update(any(List.class))).thenReturn(true); embeddedConfigInfoBetaPersistService.removeConfigInfo4Beta(dataId, group, tenant); //verity embeddedStorageContextHolderMockedStatic.verify( - () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(dataId), eq(group), eq(tenant)), - times(1)); + () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(dataId), eq(group), eq(tenant)), times(1)); } @Test - public void testFindConfigInfo4Beta() { + void testFindConfigInfo4Beta() { String dataId = "dataId456789"; String group = "group4567"; String tenant = "tenant56789o0"; @@ -284,23 +279,23 @@ public void testFindConfigInfo4Beta() { mockedConfigInfoStateWrapper.setTenant(tenant); mockedConfigInfoStateWrapper.setId(123456L); mockedConfigInfoStateWrapper.setLastModified(System.currentTimeMillis()); - Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_BETA_WRAPPER_ROW_MAPPER))).thenReturn(mockedConfigInfoStateWrapper); - ConfigInfoBetaWrapper configInfo4BetaReturn = embeddedConfigInfoBetaPersistService.findConfigInfo4Beta(dataId, - group, tenant); - Assert.assertEquals(mockedConfigInfoStateWrapper, configInfo4BetaReturn); + Mockito.when( + databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_BETA_WRAPPER_ROW_MAPPER))) + .thenReturn(mockedConfigInfoStateWrapper); + ConfigInfoBetaWrapper configInfo4BetaReturn = embeddedConfigInfoBetaPersistService.findConfigInfo4Beta(dataId, group, tenant); + assertEquals(mockedConfigInfoStateWrapper, configInfo4BetaReturn); } @Test - public void testConfigInfoBetaCount() { + void testConfigInfoBetaCount() { Mockito.when(databaseOperate.queryOne(anyString(), eq(Integer.class))).thenReturn(101); int returnCount = embeddedConfigInfoBetaPersistService.configInfoBetaCount(); - Assert.assertEquals(101, returnCount); + assertEquals(101, returnCount); } @Test - public void testFindAllConfigInfoBetaForDumpAll() { + void testFindAllConfigInfoBetaForDumpAll() { //mock count Mockito.when(databaseOperate.queryOne(anyString(), eq(Integer.class))).thenReturn(12345); @@ -313,18 +308,16 @@ public void testFindAllConfigInfoBetaForDumpAll() { mockList.get(1).setLastModified(System.currentTimeMillis()); mockList.get(2).setLastModified(System.currentTimeMillis()); - Mockito.when( - databaseOperate.queryMany(anyString(), eq(new Object[] {}), eq(CONFIG_INFO_BETA_WRAPPER_ROW_MAPPER))) + Mockito.when(databaseOperate.queryMany(anyString(), eq(new Object[] {}), eq(CONFIG_INFO_BETA_WRAPPER_ROW_MAPPER))) .thenReturn(mockList); int pageNo = 1; int pageSize = 101; Mockito.when(databaseOperate.queryOne(anyString(), eq(Integer.class))).thenReturn(101); //execute & expect - Page pageReturn = embeddedConfigInfoBetaPersistService.findAllConfigInfoBetaForDumpAll( - pageNo, pageSize); - Assert.assertEquals(mockList, pageReturn.getPageItems()); - Assert.assertEquals(101, pageReturn.getTotalCount()); + Page pageReturn = embeddedConfigInfoBetaPersistService.findAllConfigInfoBetaForDumpAll(pageNo, pageSize); + assertEquals(mockList, pageReturn.getPageItems()); + assertEquals(101, pageReturn.getTotalCount()); } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoPersistServiceImplTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoPersistServiceImplTest.java index 5d263382f6b..b62a44521bb 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoPersistServiceImplTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoPersistServiceImplTest.java @@ -35,15 +35,14 @@ import com.alibaba.nacos.persistence.repository.embedded.EmbeddedStorageContextHolder; import com.alibaba.nacos.persistence.repository.embedded.operate.DatabaseOperate; import com.alibaba.nacos.sys.env.EnvUtil; -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.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import java.sql.Timestamp; import java.util.ArrayList; @@ -58,6 +57,8 @@ import static com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER; import static com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.CONFIG_INFO_WRAPPER_ROW_MAPPER; import static com.alibaba.nacos.persistence.repository.RowMapperManager.MAP_ROW_MAPPER; +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.anyLong; import static org.mockito.ArgumentMatchers.anyString; @@ -70,16 +71,8 @@ * * @author shiyiyue */ -@RunWith(SpringJUnit4ClassRunner.class) -public class EmbeddedConfigInfoPersistServiceImplTest { - - private EmbeddedConfigInfoPersistServiceImpl embeddedConfigInfoPersistService; - - @Mock - private DataSourceService dataSourceService; - - @Mock - private HistoryConfigInfoPersistService historyConfigInfoPersistService; +@ExtendWith(SpringExtension.class) +class EmbeddedConfigInfoPersistServiceImplTest { @Mock IdGeneratorManager idGeneratorManager; @@ -96,29 +89,36 @@ public class EmbeddedConfigInfoPersistServiceImplTest { @Mock DatabaseOperate databaseOperate; - @Before - public void before() { + private EmbeddedConfigInfoPersistServiceImpl embeddedConfigInfoPersistService; + + @Mock + private DataSourceService dataSourceService; + + @Mock + private HistoryConfigInfoPersistService historyConfigInfoPersistService; + + @BeforeEach + void before() { embeddedStorageContextHolderMockedStatic = Mockito.mockStatic(EmbeddedStorageContextHolder.class); dynamicDataSourceMockedStatic = Mockito.mockStatic(DynamicDataSource.class); envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); when(DynamicDataSource.getInstance()).thenReturn(dynamicDataSource); when(dynamicDataSource.getDataSource()).thenReturn(dataSourceService); when(dataSourceService.getDataSourceType()).thenReturn("derby"); - envUtilMockedStatic.when(() -> EnvUtil.getProperty(anyString(), eq(Boolean.class), eq(false))) - .thenReturn(false); + envUtilMockedStatic.when(() -> EnvUtil.getProperty(anyString(), eq(Boolean.class), eq(false))).thenReturn(false); embeddedConfigInfoPersistService = new EmbeddedConfigInfoPersistServiceImpl(databaseOperate, idGeneratorManager, historyConfigInfoPersistService); } - @After - public void after() { + @AfterEach + void after() { dynamicDataSourceMockedStatic.close(); envUtilMockedStatic.close(); embeddedStorageContextHolderMockedStatic.close(); } @Test - public void testInsertOrUpdateOfInsertConfigSuccess() { + void testInsertOrUpdateOfInsertConfigSuccess() { String dataId = "dataId"; String group = "group"; @@ -146,44 +146,42 @@ public void testInsertOrUpdateOfInsertConfigSuccess() { configInfoStateWrapperFinalSelect.setId(insertConfigIndoId); configInfoStateWrapperFinalSelect.setLastModified(System.currentTimeMillis()); //mock get config state - Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(null, configInfoStateWrapperFinalSelect); + Mockito.when( + databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) + .thenReturn(null, configInfoStateWrapperFinalSelect); String srcIp = "srcIp"; String srcUser = "srcUser"; //mock insert config info Mockito.doNothing().when(historyConfigInfoPersistService) - .insertConfigHistoryAtomic(eq(0), eq(configInfo), eq(srcIp), eq(srcUser), any(Timestamp.class), - eq("I")); + .insertConfigHistoryAtomic(eq(0), eq(configInfo), eq(srcIp), eq(srcUser), any(Timestamp.class), eq("I")); - ConfigOperateResult configOperateResult = embeddedConfigInfoPersistService.insertOrUpdate(srcIp, srcUser, - configInfo, configAdvanceInfo); - Assert.assertEquals(configInfoStateWrapperFinalSelect.getId(), configOperateResult.getId()); - Assert.assertEquals(configInfoStateWrapperFinalSelect.getLastModified(), configOperateResult.getLastModified()); + ConfigOperateResult configOperateResult = embeddedConfigInfoPersistService.insertOrUpdate(srcIp, srcUser, configInfo, + configAdvanceInfo); + assertEquals(configInfoStateWrapperFinalSelect.getId(), configOperateResult.getId()); + assertEquals(configInfoStateWrapperFinalSelect.getLastModified(), configOperateResult.getLastModified()); //expect insert config info invoked. embeddedStorageContextHolderMockedStatic.verify( - () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), anyLong(), eq(dataId), eq(group), - eq(tenant), eq(appName), eq(content), eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), - eq(srcIp), eq(srcUser), any(Timestamp.class), any(Timestamp.class), eq(desc), eq(use), - eq(effect), eq(type), eq(schema), eq(encryptedDataKey)), times(1)); + () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), anyLong(), eq(dataId), eq(group), eq(tenant), eq(appName), + eq(content), eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), eq(srcIp), eq(srcUser), eq(desc), + eq(use), eq(effect), eq(type), eq(schema), eq(encryptedDataKey)), times(1)); //expect insert config tags embeddedStorageContextHolderMockedStatic.verify( - () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), anyLong(), eq("tag1"), - eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant)), times(1)); + () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), anyLong(), eq("tag1"), eq(StringUtils.EMPTY), eq(dataId), + eq(group), eq(tenant)), times(1)); embeddedStorageContextHolderMockedStatic.verify( - () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), anyLong(), eq("tag2"), - eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant)), times(1)); + () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), anyLong(), eq("tag2"), eq(StringUtils.EMPTY), eq(dataId), + eq(group), eq(tenant)), times(1)); //expect insert history info Mockito.verify(historyConfigInfoPersistService, times(1)) - .insertConfigHistoryAtomic(eq(0L), eq(configInfo), eq(srcIp), eq(srcUser), any(Timestamp.class), - eq("I")); + .insertConfigHistoryAtomic(eq(0L), eq(configInfo), eq(srcIp), eq(srcUser), any(Timestamp.class), eq("I")); } @Test - public void testInsertOrUpdateCasOfInsertConfigSuccess() { + void testInsertOrUpdateCasOfInsertConfigSuccess() { Map configAdvanceInfo = new HashMap<>(); String desc = "testdesc"; @@ -211,36 +209,35 @@ public void testInsertOrUpdateCasOfInsertConfigSuccess() { configInfoStateWrapperFinalSelect.setId(insertConfigIndoId); configInfoStateWrapperFinalSelect.setLastModified(System.currentTimeMillis()); //mock get config state - Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(null, configInfoStateWrapperFinalSelect); + Mockito.when( + databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) + .thenReturn(null, configInfoStateWrapperFinalSelect); String srcIp = "iptest"; String srcUser = "users"; - ConfigOperateResult configOperateResult = embeddedConfigInfoPersistService.insertOrUpdateCas(srcIp, srcUser, - configInfo, configAdvanceInfo); - Assert.assertEquals(configInfoStateWrapperFinalSelect.getId(), configOperateResult.getId()); - Assert.assertEquals(configInfoStateWrapperFinalSelect.getLastModified(), configOperateResult.getLastModified()); + ConfigOperateResult configOperateResult = embeddedConfigInfoPersistService.insertOrUpdateCas(srcIp, srcUser, configInfo, + configAdvanceInfo); + assertEquals(configInfoStateWrapperFinalSelect.getId(), configOperateResult.getId()); + assertEquals(configInfoStateWrapperFinalSelect.getLastModified(), configOperateResult.getLastModified()); //expect insert config info invoked. embeddedStorageContextHolderMockedStatic.verify( - () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), anyLong(), eq(dataId), eq(group), - eq(tenant), eq(appName), eq(content), eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), - eq(srcIp), eq(srcUser), any(Timestamp.class), any(Timestamp.class), eq(desc), eq(use), - eq(effect), eq(type), eq(schema), eq(encryptedDatakey)), times(1)); + () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), anyLong(), eq(dataId), eq(group), eq(tenant), eq(appName), + eq(content), eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), eq(srcIp), eq(srcUser), + eq(desc), eq(use), eq(effect), eq(type), eq(schema), eq(encryptedDatakey)), times(1)); //expect insert config tags embeddedStorageContextHolderMockedStatic.verify( - () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), anyLong(), eq("tag1"), - eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant)), times(1)); + () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), anyLong(), eq("tag1"), eq(StringUtils.EMPTY), eq(dataId), + eq(group), eq(tenant)), times(1)); embeddedStorageContextHolderMockedStatic.verify( - () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), anyLong(), eq("tag2"), - eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant)), times(1)); + () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), anyLong(), eq("tag2"), eq(StringUtils.EMPTY), eq(dataId), + eq(group), eq(tenant)), times(1)); //expect insert history info Mockito.verify(historyConfigInfoPersistService, times(1)) - .insertConfigHistoryAtomic(eq(0L), eq(configInfo), eq(srcIp), eq(srcUser), any(Timestamp.class), - eq("I")); + .insertConfigHistoryAtomic(eq(0L), eq(configInfo), eq(srcIp), eq(srcUser), any(Timestamp.class), eq("I")); } @Test - public void testInsertOrUpdateOfUpdateConfigSuccess() { + void testInsertOrUpdateOfUpdateConfigSuccess() { Map configAdvanceInfo = new HashMap<>(); String desc = "testdesc"; @@ -264,8 +261,8 @@ public void testInsertOrUpdateOfUpdateConfigSuccess() { String encryptedDataKey = "key34567"; configInfo.setEncryptedDataKey(encryptedDataKey); //mock get config state,first and second is not null - Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) + Mockito.when( + databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) .thenReturn(new ConfigInfoStateWrapper(), new ConfigInfoStateWrapper()); //mock select config info before update @@ -276,36 +273,34 @@ public void testInsertOrUpdateOfUpdateConfigSuccess() { configInfoWrapperOld.setAppName("old_app"); configInfoWrapperOld.setMd5("old_md5"); configInfoWrapperOld.setId(12345678765L); - Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))).thenReturn(configInfoWrapperOld); + Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))) + .thenReturn(configInfoWrapperOld); String srcIp = "srcIp"; String srcUser = "srcUser"; embeddedConfigInfoPersistService.insertOrUpdate(srcIp, srcUser, configInfo, configAdvanceInfo); //expect update config info invoked. - embeddedStorageContextHolderMockedStatic.verify( - () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(content), - eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), eq(srcIp), eq(srcUser), - any(Timestamp.class), eq(appName), eq(desc), eq(use), eq(effect), eq(type), eq(schema), - eq(encryptedDataKey), eq(dataId), eq(group), eq(tenant)), times(1)); + embeddedStorageContextHolderMockedStatic.verify(() -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(content), + eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), eq(srcIp), eq(srcUser), eq(appName), eq(desc), + eq(use), eq(effect), eq(type), eq(schema), eq(encryptedDataKey), eq(dataId), eq(group), eq(tenant)), times(1)); //expect insert config tags embeddedStorageContextHolderMockedStatic.verify( - () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), anyLong(), eq("tag1"), - eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant)), times(1)); + () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), anyLong(), eq("tag1"), eq(StringUtils.EMPTY), eq(dataId), + eq(group), eq(tenant)), times(1)); embeddedStorageContextHolderMockedStatic.verify( - () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), anyLong(), eq("tag2"), - eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant)), times(1)); + () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), anyLong(), eq("tag2"), eq(StringUtils.EMPTY), eq(dataId), + eq(group), eq(tenant)), times(1)); //expect insert history info of U Mockito.verify(historyConfigInfoPersistService, times(1)) - .insertConfigHistoryAtomic(eq(configInfoWrapperOld.getId()), any(ConfigInfo.class), eq(srcIp), - eq(srcUser), any(Timestamp.class), eq("U")); + .insertConfigHistoryAtomic(eq(configInfoWrapperOld.getId()), any(ConfigInfo.class), eq(srcIp), eq(srcUser), + any(Timestamp.class), eq("U")); } @Test - public void testInsertOrUpdateCasOfUpdateConfigSuccess() { + void testInsertOrUpdateCasOfUpdateConfigSuccess() { Map configAdvanceInfo = new HashMap<>(); String desc = "testdesc11"; @@ -331,8 +326,8 @@ public void testInsertOrUpdateCasOfUpdateConfigSuccess() { configInfo.setEncryptedDataKey(encryptedDataKey); //mock get config state,first and second is not null - Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) + Mockito.when( + databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) .thenReturn(new ConfigInfoStateWrapper(), new ConfigInfoStateWrapper()); //mock select config info before update @@ -343,8 +338,8 @@ public void testInsertOrUpdateCasOfUpdateConfigSuccess() { configInfoWrapperOld.setAppName("old_app11"); configInfoWrapperOld.setMd5("old_md5"); configInfoWrapperOld.setId(123456799L); - Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))).thenReturn(configInfoWrapperOld); + Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))) + .thenReturn(configInfoWrapperOld); String srcIp = "srcIp"; String srcUser = "srcUser"; @@ -352,27 +347,27 @@ public void testInsertOrUpdateCasOfUpdateConfigSuccess() { //expect update config info invoked. embeddedStorageContextHolderMockedStatic.verify( () -> EmbeddedStorageContextHolder.addSqlContext(eq(Boolean.TRUE), anyString(), eq(content), - eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), eq(srcIp), eq(srcUser), - any(Timestamp.class), eq(appName), eq(desc), eq(use), eq(effect), eq(type), eq(schema), - eq(encryptedDataKey), eq(dataId), eq(group), eq(tenant), eq(casMd5)), times(1)); + eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), eq(srcIp), eq(srcUser), eq(appName), + eq(desc), eq(use), eq(effect), eq(type), eq(schema), eq(encryptedDataKey), eq(dataId), eq(group), eq(tenant), + eq(casMd5)), times(1)); //expect insert config tags embeddedStorageContextHolderMockedStatic.verify( - () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), anyLong(), eq("tag1"), - eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant)), times(1)); + () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), anyLong(), eq("tag1"), eq(StringUtils.EMPTY), eq(dataId), + eq(group), eq(tenant)), times(1)); embeddedStorageContextHolderMockedStatic.verify( - () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), anyLong(), eq("tag2"), - eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant)), times(1)); + () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), anyLong(), eq("tag2"), eq(StringUtils.EMPTY), eq(dataId), + eq(group), eq(tenant)), times(1)); //expect insert history info of U Mockito.verify(historyConfigInfoPersistService, times(1)) - .insertConfigHistoryAtomic(eq(configInfoWrapperOld.getId()), any(ConfigInfo.class), eq(srcIp), - eq(srcUser), any(Timestamp.class), eq("U")); + .insertConfigHistoryAtomic(eq(configInfoWrapperOld.getId()), any(ConfigInfo.class), eq(srcIp), eq(srcUser), + any(Timestamp.class), eq("U")); } @Test - public void testRemoveConfigInfo() { + void testRemoveConfigInfo() { String dataId = "dataId4567"; String group = "group3456789"; String tenant = "tenant4567890"; @@ -387,8 +382,8 @@ public void testRemoveConfigInfo() { configInfoWrapperOld.setMd5("old_md5"); configInfoWrapperOld.setId(12345678765L); configInfoWrapperOld.setEncryptedDataKey("key3456"); - Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))).thenReturn(configInfoWrapperOld); + Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))) + .thenReturn(configInfoWrapperOld); String srcIp = "srcIp1234"; String srcUser = "srcUser"; Mockito.when(databaseOperate.update(any())).thenReturn(true); @@ -396,21 +391,19 @@ public void testRemoveConfigInfo() { //expect delete config to be invoked embeddedStorageContextHolderMockedStatic.verify( - () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(dataId), eq(group), eq(tenant)), - times(1)); + () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(dataId), eq(group), eq(tenant)), times(1)); //expect delete config tag to be invoked embeddedStorageContextHolderMockedStatic.verify( - () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(configInfoWrapperOld.getId())), - times(1)); + () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(configInfoWrapperOld.getId())), times(1)); //expect insert delete history Mockito.verify(historyConfigInfoPersistService, times(1)) - .insertConfigHistoryAtomic(eq(configInfoWrapperOld.getId()), eq(configInfoWrapperOld), eq(srcIp), - eq(srcUser), any(), eq("D")); + .insertConfigHistoryAtomic(eq(configInfoWrapperOld.getId()), eq(configInfoWrapperOld), eq(srcIp), eq(srcUser), any(), + eq("D")); } @Test - public void testRemoveConfigInfoByIds() { + void testRemoveConfigInfoByIds() { //mock exist config info List configInfos = new ArrayList<>(); @@ -419,8 +412,7 @@ public void testRemoveConfigInfoByIds() { List deleteIds = Arrays.asList(12344L, 3456789L); configInfos.get(0).setId(12344L); configInfos.get(1).setId(3456789L); - Mockito.when(databaseOperate.queryMany(anyString(), eq(deleteIds.toArray()), eq(CONFIG_INFO_ROW_MAPPER))) - .thenReturn(configInfos); + Mockito.when(databaseOperate.queryMany(anyString(), eq(deleteIds.toArray()), eq(CONFIG_INFO_ROW_MAPPER))).thenReturn(configInfos); String srcIp = "srcIp1234"; String srcUser = "srcUser"; Mockito.when(databaseOperate.update(any())).thenReturn(true); @@ -433,22 +425,20 @@ public void testRemoveConfigInfoByIds() { embeddedStorageContextHolderMockedStatic.verify( () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(deleteId0), eq(deleteId1)), times(1)); //expect delete config tag to be invoked - embeddedStorageContextHolderMockedStatic.verify( - () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(deleteId0)), times(1)); - embeddedStorageContextHolderMockedStatic.verify( - () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(deleteId1)), times(1)); + embeddedStorageContextHolderMockedStatic.verify(() -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(deleteId0)), + times(1)); + embeddedStorageContextHolderMockedStatic.verify(() -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(deleteId1)), + times(1)); //expect insert delete history Mockito.verify(historyConfigInfoPersistService, times(1)) - .insertConfigHistoryAtomic(eq(configInfos.get(0).getId()), eq(configInfos.get(0)), eq(srcIp), - eq(srcUser), any(), eq("D")); + .insertConfigHistoryAtomic(eq(configInfos.get(0).getId()), eq(configInfos.get(0)), eq(srcIp), eq(srcUser), any(), eq("D")); Mockito.verify(historyConfigInfoPersistService, times(1)) - .insertConfigHistoryAtomic(eq(configInfos.get(1).getId()), eq(configInfos.get(1)), eq(srcIp), - eq(srcUser), any(), eq("D")); + .insertConfigHistoryAtomic(eq(configInfos.get(1).getId()), eq(configInfos.get(1)), eq(srcIp), eq(srcUser), any(), eq("D")); } @Test - public void testBatchInsertOrUpdateOverwrite() throws NacosException { + void testBatchInsertOrUpdateOverwrite() throws NacosException { List configInfoList = new ArrayList<>(); //insert direct configInfoList.add(createMockConfigAllInfo(0)); @@ -462,32 +452,28 @@ public void testBatchInsertOrUpdateOverwrite() throws NacosException { //mock add config 1 success,config 2 fail and skip,config 3 success Mockito.when(databaseOperate.queryOne(anyString(), - eq(new Object[] {configInfoList.get(0).getDataId(), configInfoList.get(0).getGroup(), - configInfoList.get(0).getTenant()}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) - .thenReturn(null); + eq(new Object[] {configInfoList.get(0).getDataId(), configInfoList.get(0).getGroup(), configInfoList.get(0).getTenant()}), + eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(null); Mockito.when(databaseOperate.queryOne(anyString(), - eq(new Object[] {configInfoList.get(1).getDataId(), configInfoList.get(1).getGroup(), - configInfoList.get(1).getTenant()}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) - .thenReturn(new ConfigInfoStateWrapper()); + eq(new Object[] {configInfoList.get(1).getDataId(), configInfoList.get(1).getGroup(), configInfoList.get(1).getTenant()}), + eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(new ConfigInfoStateWrapper()); Mockito.when(databaseOperate.queryOne(anyString(), - eq(new Object[] {configInfoList.get(2).getDataId(), configInfoList.get(2).getGroup(), - configInfoList.get(1).getTenant()}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) - .thenReturn(null); + eq(new Object[] {configInfoList.get(2).getDataId(), configInfoList.get(2).getGroup(), configInfoList.get(1).getTenant()}), + eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(null); //mock query config info during update ConfigInfoWrapper configInfoWrapper = new ConfigInfoWrapper(); Mockito.when(databaseOperate.queryOne(anyString(), - eq(new Object[] {configInfoList.get(1).getDataId(), configInfoList.get(1).getGroup(), - configInfoList.get(1).getTenant()}), eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))) - .thenReturn(configInfoWrapper); + eq(new Object[] {configInfoList.get(1).getDataId(), configInfoList.get(1).getGroup(), configInfoList.get(1).getTenant()}), + eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))).thenReturn(configInfoWrapper); - Map stringObjectMap = embeddedConfigInfoPersistService.batchInsertOrUpdate(configInfoList, - srcUser, srcIp, configAdvanceInfo, SameConfigPolicy.OVERWRITE); - Assert.assertEquals(3, stringObjectMap.get("succCount")); - Assert.assertEquals(0, stringObjectMap.get("skipCount")); + Map stringObjectMap = embeddedConfigInfoPersistService.batchInsertOrUpdate(configInfoList, srcUser, srcIp, + configAdvanceInfo, SameConfigPolicy.OVERWRITE); + assertEquals(3, stringObjectMap.get("succCount")); + assertEquals(0, stringObjectMap.get("skipCount")); } @Test - public void testBatchInsertOrUpdateSkip() throws NacosException { + void testBatchInsertOrUpdateSkip() throws NacosException { List configInfoList = new ArrayList<>(); //insert direct configInfoList.add(createMockConfigAllInfo(0)); @@ -501,28 +487,24 @@ public void testBatchInsertOrUpdateSkip() throws NacosException { //mock add config 1 success,config 2 fail and skip,config 3 success Mockito.when(databaseOperate.queryOne(anyString(), - eq(new Object[] {configInfoList.get(0).getDataId(), configInfoList.get(0).getGroup(), - configInfoList.get(0).getTenant()}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) - .thenReturn(null); + eq(new Object[] {configInfoList.get(0).getDataId(), configInfoList.get(0).getGroup(), configInfoList.get(0).getTenant()}), + eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(null); Mockito.when(databaseOperate.queryOne(anyString(), - eq(new Object[] {configInfoList.get(1).getDataId(), configInfoList.get(1).getGroup(), - configInfoList.get(1).getTenant()}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) - .thenReturn(new ConfigInfoStateWrapper()); + eq(new Object[] {configInfoList.get(1).getDataId(), configInfoList.get(1).getGroup(), configInfoList.get(1).getTenant()}), + eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(new ConfigInfoStateWrapper()); Mockito.when(databaseOperate.queryOne(anyString(), - eq(new Object[] {configInfoList.get(2).getDataId(), configInfoList.get(2).getGroup(), - configInfoList.get(1).getTenant()}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) - .thenReturn(null); - - Map stringObjectMap = embeddedConfigInfoPersistService.batchInsertOrUpdate(configInfoList, - srcUser, srcIp, configAdvanceInfo, SameConfigPolicy.SKIP); - Assert.assertEquals(2, stringObjectMap.get("succCount")); - Assert.assertEquals(1, stringObjectMap.get("skipCount")); - Assert.assertEquals(configInfoList.get(1).getDataId(), - ((List>) stringObjectMap.get("skipData")).get(0).get("dataId")); + eq(new Object[] {configInfoList.get(2).getDataId(), configInfoList.get(2).getGroup(), configInfoList.get(1).getTenant()}), + eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(null); + + Map stringObjectMap = embeddedConfigInfoPersistService.batchInsertOrUpdate(configInfoList, srcUser, srcIp, + configAdvanceInfo, SameConfigPolicy.SKIP); + assertEquals(2, stringObjectMap.get("succCount")); + assertEquals(1, stringObjectMap.get("skipCount")); + assertEquals(configInfoList.get(1).getDataId(), ((List>) stringObjectMap.get("skipData")).get(0).get("dataId")); } @Test - public void testBatchInsertOrUpdateAbort() throws NacosException { + void testBatchInsertOrUpdateAbort() throws NacosException { List configInfoList = new ArrayList<>(); //insert direct configInfoList.add(createMockConfigAllInfo(0)); @@ -536,28 +518,23 @@ public void testBatchInsertOrUpdateAbort() throws NacosException { //mock add config 1 success,config 2 fail and abort,config 3 not operated Mockito.when(databaseOperate.queryOne(anyString(), - eq(new Object[] {configInfoList.get(0).getDataId(), configInfoList.get(0).getGroup(), - configInfoList.get(0).getTenant()}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) - .thenReturn(null); + eq(new Object[] {configInfoList.get(0).getDataId(), configInfoList.get(0).getGroup(), configInfoList.get(0).getTenant()}), + eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(null); Mockito.when(databaseOperate.queryOne(anyString(), - eq(new Object[] {configInfoList.get(1).getDataId(), configInfoList.get(1).getGroup(), - configInfoList.get(1).getTenant()}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) - .thenReturn(new ConfigInfoStateWrapper()); + eq(new Object[] {configInfoList.get(1).getDataId(), configInfoList.get(1).getGroup(), configInfoList.get(1).getTenant()}), + eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(new ConfigInfoStateWrapper()); Mockito.when(databaseOperate.queryOne(anyString(), - eq(new Object[] {configInfoList.get(2).getDataId(), configInfoList.get(2).getGroup(), - configInfoList.get(1).getTenant()}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) - .thenReturn(null); - - Map stringObjectMap = embeddedConfigInfoPersistService.batchInsertOrUpdate(configInfoList, - srcUser, srcIp, configAdvanceInfo, SameConfigPolicy.ABORT); - Assert.assertEquals(1, stringObjectMap.get("succCount")); - Assert.assertEquals(1, stringObjectMap.get("skipCount")); + eq(new Object[] {configInfoList.get(2).getDataId(), configInfoList.get(2).getGroup(), configInfoList.get(1).getTenant()}), + eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(null); + + Map stringObjectMap = embeddedConfigInfoPersistService.batchInsertOrUpdate(configInfoList, srcUser, srcIp, + configAdvanceInfo, SameConfigPolicy.ABORT); + assertEquals(1, stringObjectMap.get("succCount")); + assertEquals(1, stringObjectMap.get("skipCount")); // config 2 failed - Assert.assertEquals(configInfoList.get(1).getDataId(), - ((List>) stringObjectMap.get("failData")).get(0).get("dataId")); + assertEquals(configInfoList.get(1).getDataId(), ((List>) stringObjectMap.get("failData")).get(0).get("dataId")); //skip config 3 - Assert.assertEquals(configInfoList.get(2).getDataId(), - ((List>) stringObjectMap.get("skipData")).get(0).get("dataId")); + assertEquals(configInfoList.get(2).getDataId(), ((List>) stringObjectMap.get("skipData")).get(0).get("dataId")); } private ConfigAllInfo createMockConfigAllInfo(long mockId) { @@ -597,34 +574,33 @@ private ConfigInfo createMockConfigInfo(long mockId) { } @Test - public void testFindConfigMaxId() { + void testFindConfigMaxId() { Mockito.when(databaseOperate.queryOne(anyString(), eq(Long.class))).thenReturn(123456L); long configMaxId = embeddedConfigInfoPersistService.findConfigMaxId(); - Assert.assertEquals(123456L, configMaxId); + assertEquals(123456L, configMaxId); } @Test - public void testFindConfigMaxId0() { + void testFindConfigMaxId0() { Mockito.when(databaseOperate.queryOne(anyString(), eq(Long.class))).thenReturn(0L); long configMaxId = embeddedConfigInfoPersistService.findConfigMaxId(); - Assert.assertEquals(0, configMaxId); + assertEquals(0, configMaxId); } @Test - public void testFindConfigInfoById() { + void testFindConfigInfoById() { long id = 1234567890876L; ConfigInfo configInfo = new ConfigInfo(); configInfo.setId(id); - Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {id}), eq(CONFIG_INFO_ROW_MAPPER))) - .thenReturn(configInfo); + Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {id}), eq(CONFIG_INFO_ROW_MAPPER))).thenReturn(configInfo); ConfigInfo configReturn = embeddedConfigInfoPersistService.findConfigInfo(id); - Assert.assertEquals(id, configReturn.getId()); + assertEquals(id, configReturn.getId()); } @Test - public void testFindConfigInfoByDataId() { + void testFindConfigInfoByDataId() { String dataId = "dataId4567"; String group = "group3456789"; String tenant = "tenant4567890"; @@ -633,38 +609,37 @@ public void testFindConfigInfoByDataId() { configInfoWrapper.setGroup(group); configInfoWrapper.setTenant(tenant); - Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))).thenReturn(configInfoWrapper); + Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))) + .thenReturn(configInfoWrapper); ConfigInfo configReturn = embeddedConfigInfoPersistService.findConfigInfo(dataId, group, tenant); - Assert.assertEquals(dataId, configReturn.getDataId()); + assertEquals(dataId, configReturn.getDataId()); } @Test - public void testFindConfigInfo4Page() { + void testFindConfigInfo4Page() { String dataId = "dataId4567222"; String group = "group3456789"; String tenant = "tenant4567890"; //mock total count - when(databaseOperate.queryOne(anyString(), eq(new Object[] {tenant, dataId, group}), - eq(Integer.class))).thenReturn(new Integer(9)); + when(databaseOperate.queryOne(anyString(), eq(new Object[] {tenant, dataId, group}), eq(Integer.class))).thenReturn(new Integer(9)); //mock page list List result = new ArrayList<>(); result.add(createMockConfigInfo(0)); result.add(createMockConfigInfo(1)); result.add(createMockConfigInfo(2)); - when(databaseOperate.queryMany(anyString(), eq(new Object[] {tenant, dataId, group}), - eq(CONFIG_INFO_ROW_MAPPER))).thenReturn(result); + when(databaseOperate.queryMany(anyString(), eq(new Object[] {tenant, dataId, group}), eq(CONFIG_INFO_ROW_MAPPER))).thenReturn( + result); Map configAdvanceInfo = new HashMap<>(); - Page configInfo4Page = embeddedConfigInfoPersistService.findConfigInfo4Page(1, 3, dataId, group, - tenant, configAdvanceInfo); - Assert.assertEquals(result.size(), configInfo4Page.getPageItems().size()); - Assert.assertEquals(9, configInfo4Page.getTotalCount()); + Page configInfo4Page = embeddedConfigInfoPersistService.findConfigInfo4Page(1, 3, dataId, group, tenant, + configAdvanceInfo); + assertEquals(result.size(), configInfo4Page.getPageItems().size()); + assertEquals(9, configInfo4Page.getTotalCount()); } @Test - public void testFindConfigInfo4PageWithTags() { + void testFindConfigInfo4PageWithTags() { String dataId = "dataId4567222"; String group = "group3456789"; String tenant = "tenant4567890"; @@ -682,52 +657,51 @@ public void testFindConfigInfo4PageWithTags() { when(databaseOperate.queryMany(anyString(), eq(new Object[] {tenant, dataId, group, "tags1", "tags3"}), eq(CONFIG_INFO_ROW_MAPPER))).thenReturn(result); - Page configInfo4Page = embeddedConfigInfoPersistService.findConfigInfo4Page(1, 3, dataId, group, - tenant, configAdvanceInfo); - Assert.assertEquals(result.size(), configInfo4Page.getPageItems().size()); - Assert.assertEquals(9, configInfo4Page.getTotalCount()); + Page configInfo4Page = embeddedConfigInfoPersistService.findConfigInfo4Page(1, 3, dataId, group, tenant, + configAdvanceInfo); + assertEquals(result.size(), configInfo4Page.getPageItems().size()); + assertEquals(9, configInfo4Page.getTotalCount()); } @Test - public void testConfigInfoCount() { + void testConfigInfoCount() { //mock total count when(databaseOperate.queryOne(anyString(), eq(Integer.class))).thenReturn(new Integer(9)); int count = embeddedConfigInfoPersistService.configInfoCount(); - Assert.assertEquals(9, count); + assertEquals(9, count); when(databaseOperate.queryOne(anyString(), eq(Integer.class))).thenReturn(null); try { embeddedConfigInfoPersistService.configInfoCount(); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertTrue(e instanceof IllegalArgumentException); + assertTrue(e instanceof IllegalArgumentException); } } @Test - public void testConfigInfoCountByTenant() { + void testConfigInfoCountByTenant() { String tenant = "tenant124"; //mock total count - when(databaseOperate.queryOne(anyString(), eq(new Object[] {tenant}), eq(Integer.class))).thenReturn( - new Integer(90)); + when(databaseOperate.queryOne(anyString(), eq(new Object[] {tenant}), eq(Integer.class))).thenReturn(new Integer(90)); int count = embeddedConfigInfoPersistService.configInfoCount(tenant); - Assert.assertEquals(90, count); + assertEquals(90, count); when(databaseOperate.queryOne(anyString(), eq(new Object[] {tenant}), eq(Integer.class))).thenReturn(null); try { embeddedConfigInfoPersistService.configInfoCount(tenant); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertTrue(e instanceof IllegalArgumentException); + assertTrue(e instanceof IllegalArgumentException); } } @Test - public void testFindConfigInfoLike4Page() { + void testFindConfigInfoLike4Page() { String dataId = "dataId4567222*"; String group = "group3456789*"; String tenant = "tenant4567890"; @@ -738,26 +712,26 @@ public void testFindConfigInfoLike4Page() { configAdvanceInfo.put("content", content); //mock total count when(databaseOperate.queryOne(anyString(), - eq(new Object[] {tenant, dataId.replaceAll("\\*", "%"), group.replaceAll("\\*", "%"), appName, - content}), eq(Integer.class))).thenReturn(new Integer(9)); + eq(new Object[] {tenant, dataId.replaceAll("\\*", "%"), group.replaceAll("\\*", "%"), appName, content}), + eq(Integer.class))).thenReturn(new Integer(9)); //mock page list List result = new ArrayList<>(); result.add(createMockConfigInfo(0)); result.add(createMockConfigInfo(1)); result.add(createMockConfigInfo(2)); when(databaseOperate.queryMany(anyString(), - eq(new Object[] {tenant, dataId.replaceAll("\\*", "%"), group.replaceAll("\\*", "%"), appName, - content}), eq(CONFIG_INFO_ROW_MAPPER))).thenReturn(result); + eq(new Object[] {tenant, dataId.replaceAll("\\*", "%"), group.replaceAll("\\*", "%"), appName, content}), + eq(CONFIG_INFO_ROW_MAPPER))).thenReturn(result); - Page configInfo4Page = embeddedConfigInfoPersistService.findConfigInfoLike4Page(1, 3, dataId, group, - tenant, configAdvanceInfo); - Assert.assertEquals(result.size(), configInfo4Page.getPageItems().size()); - Assert.assertEquals(9, configInfo4Page.getTotalCount()); + Page configInfo4Page = embeddedConfigInfoPersistService.findConfigInfoLike4Page(1, 3, dataId, group, tenant, + configAdvanceInfo); + assertEquals(result.size(), configInfo4Page.getPageItems().size()); + assertEquals(9, configInfo4Page.getTotalCount()); } @Test - public void testFindConfigInfoLike4PageWithTags() { + void testFindConfigInfoLike4PageWithTags() { String appName = "appName1234"; String content = "content123"; @@ -770,26 +744,26 @@ public void testFindConfigInfoLike4PageWithTags() { String tenant = "tenant4567890"; //mock total count when(databaseOperate.queryOne(anyString(), - eq(new Object[] {tenant, dataId.replaceAll("\\*", "%"), group.replaceAll("\\*", "%"), appName, content, - "tags", "tag2"}), eq(Integer.class))).thenReturn(new Integer(9)); + eq(new Object[] {tenant, dataId.replaceAll("\\*", "%"), group.replaceAll("\\*", "%"), appName, content, "tags", "tag2"}), + eq(Integer.class))).thenReturn(new Integer(9)); //mock page list List result = new ArrayList<>(); result.add(createMockConfigInfo(0)); result.add(createMockConfigInfo(1)); result.add(createMockConfigInfo(2)); when(databaseOperate.queryMany(anyString(), - eq(new Object[] {tenant, dataId.replaceAll("\\*", "%"), group.replaceAll("\\*", "%"), appName, content, - "tags", "tag2"}), eq(CONFIG_INFO_ROW_MAPPER))).thenReturn(result); + eq(new Object[] {tenant, dataId.replaceAll("\\*", "%"), group.replaceAll("\\*", "%"), appName, content, "tags", "tag2"}), + eq(CONFIG_INFO_ROW_MAPPER))).thenReturn(result); - Page configInfo4Page = embeddedConfigInfoPersistService.findConfigInfoLike4Page(1, 3, dataId, group, - tenant, configAdvanceInfo); - Assert.assertEquals(result.size(), configInfo4Page.getPageItems().size()); - Assert.assertEquals(9, configInfo4Page.getTotalCount()); + Page configInfo4Page = embeddedConfigInfoPersistService.findConfigInfoLike4Page(1, 3, dataId, group, tenant, + configAdvanceInfo); + assertEquals(result.size(), configInfo4Page.getPageItems().size()); + assertEquals(9, configInfo4Page.getTotalCount()); } @Test - public void testFindChangeConfig() { + void testFindChangeConfig() { //mock page list List result = new ArrayList<>(); @@ -802,56 +776,52 @@ public void testFindChangeConfig() { when(databaseOperate.queryMany(anyString(), eq(new Object[] {startTime, lastMaxId, pageSize}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(result); - List configInfo4List = embeddedConfigInfoPersistService.findChangeConfig(startTime, - lastMaxId, pageSize); - Assert.assertEquals(result.size(), configInfo4List.size()); + List configInfo4List = embeddedConfigInfoPersistService.findChangeConfig(startTime, lastMaxId, pageSize); + assertEquals(result.size(), configInfo4List.size()); } @Test - public void testSelectTagByConfig() { + void testSelectTagByConfig() { String dataId = "dataId4567222"; String group = "group3456789"; String tenant = "tenant4567890"; //mock page list List tagStrings = Arrays.asList("", "", ""); - when(databaseOperate.queryMany(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(String.class))).thenReturn(tagStrings); + when(databaseOperate.queryMany(anyString(), eq(new Object[] {dataId, group, tenant}), eq(String.class))).thenReturn(tagStrings); List configTags = embeddedConfigInfoPersistService.selectTagByConfig(dataId, group, tenant); - Assert.assertEquals(tagStrings, configTags); + assertEquals(tagStrings, configTags); } @Test - public void testFindConfigInfosByIds() { + void testFindConfigInfosByIds() { //mock page list List result = new ArrayList<>(); result.add(createMockConfigInfo(0)); result.add(createMockConfigInfo(1)); result.add(createMockConfigInfo(2)); - when(databaseOperate.queryMany(anyString(), eq(new Object[] {123L, 1232345L}), - eq(CONFIG_INFO_ROW_MAPPER))).thenReturn(result); + when(databaseOperate.queryMany(anyString(), eq(new Object[] {123L, 1232345L}), eq(CONFIG_INFO_ROW_MAPPER))).thenReturn(result); String ids = "123,1232345"; List configInfosByIds = embeddedConfigInfoPersistService.findConfigInfosByIds(ids); - Assert.assertEquals(result.size(), configInfosByIds.size()); - Assert.assertEquals(result.get(2).getDataId(), configInfosByIds.get(2).getDataId()); + assertEquals(result.size(), configInfosByIds.size()); + assertEquals(result.get(2).getDataId(), configInfosByIds.get(2).getDataId()); //blank ids. List nullResultBlankIds = embeddedConfigInfoPersistService.findConfigInfosByIds(""); - Assert.assertTrue(nullResultBlankIds == null); + assertTrue(nullResultBlankIds == null); } @Test - public void testFindConfigAdvanceInfo() { + void testFindConfigAdvanceInfo() { String dataId = "dataId1324"; String group = "group23546"; String tenant = "tenant13245"; //mock select tags List mockTags = Arrays.asList("tag1", "tag2", "tag3"); - when(databaseOperate.queryMany(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(String.class))).thenReturn(mockTags); + when(databaseOperate.queryMany(anyString(), eq(new Object[] {dataId, group, tenant}), eq(String.class))).thenReturn(mockTags); String schema = "schema12345654"; //mock select config advance @@ -861,41 +831,39 @@ public void testFindConfigAdvanceInfo() { eq(CONFIG_ADVANCE_INFO_ROW_MAPPER))).thenReturn(mockedAdvance); //execute return mock obj - ConfigAdvanceInfo configAdvanceInfo = embeddedConfigInfoPersistService.findConfigAdvanceInfo(dataId, group, - tenant); + ConfigAdvanceInfo configAdvanceInfo = embeddedConfigInfoPersistService.findConfigAdvanceInfo(dataId, group, tenant); //expect check schema & tags. - Assert.assertEquals(mockedAdvance.getSchema(), configAdvanceInfo.getSchema()); - Assert.assertEquals(String.join(",", mockTags), configAdvanceInfo.getConfigTags()); + assertEquals(mockedAdvance.getSchema(), configAdvanceInfo.getSchema()); + assertEquals(String.join(",", mockTags), configAdvanceInfo.getConfigTags()); } @Test - public void testFindConfigAllInfo() { + void testFindConfigAllInfo() { String dataId = "dataId1324"; String group = "group23546"; String tenant = "tenant13245"; //mock select tags List mockTags = Arrays.asList("tag1", "tag2", "tag3"); - when(databaseOperate.queryMany(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(String.class))).thenReturn(mockTags); + when(databaseOperate.queryMany(anyString(), eq(new Object[] {dataId, group, tenant}), eq(String.class))).thenReturn(mockTags); String schema = "schema12345654"; //mock select config advance ConfigAllInfo mockedConfig = new ConfigAllInfo(); mockedConfig.setSchema(schema); - when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_ALL_INFO_ROW_MAPPER))).thenReturn(mockedConfig); + when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_ALL_INFO_ROW_MAPPER))).thenReturn( + mockedConfig); //execute return mock obj ConfigAllInfo configAllInfo = embeddedConfigInfoPersistService.findConfigAllInfo(dataId, group, tenant); //expect check schema & tags. - Assert.assertEquals(mockedConfig.getSchema(), configAllInfo.getSchema()); - Assert.assertEquals(String.join(",", mockTags), configAllInfo.getConfigTags()); + assertEquals(mockedConfig.getSchema(), configAllInfo.getSchema()); + assertEquals(String.join(",", mockTags), configAllInfo.getConfigTags()); } @Test - public void testFindConfigInfoState() { + void testFindConfigInfoState() { String dataId = "dataId1324"; String group = "group23546"; @@ -909,15 +877,14 @@ public void testFindConfigInfoState() { eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(mockedConfig); //execute return mock obj - ConfigInfoStateWrapper configInfoStateWrapper = embeddedConfigInfoPersistService.findConfigInfoState(dataId, - group, tenant); + ConfigInfoStateWrapper configInfoStateWrapper = embeddedConfigInfoPersistService.findConfigInfoState(dataId, group, tenant); //expect check schema & tags. - Assert.assertEquals(mockedConfig.getId(), configInfoStateWrapper.getId()); - Assert.assertEquals(mockedConfig.getLastModified(), configInfoStateWrapper.getLastModified()); + assertEquals(mockedConfig.getId(), configInfoStateWrapper.getId()); + assertEquals(mockedConfig.getLastModified(), configInfoStateWrapper.getLastModified()); } @Test - public void testFindAllConfigInfo4Export() { + void testFindAllConfigInfo4Export() { //mock select config state List mockConfigs = new ArrayList<>(); @@ -931,26 +898,26 @@ public void testFindAllConfigInfo4Export() { String appName = "appName1243"; List ids = Arrays.asList(132L, 1343L, 245L); - when(databaseOperate.queryMany(anyString(), eq(new Object[] {132L, 1343L, 245L}), - eq(CONFIG_ALL_INFO_ROW_MAPPER))).thenReturn(mockConfigs); + when(databaseOperate.queryMany(anyString(), eq(new Object[] {132L, 1343L, 245L}), eq(CONFIG_ALL_INFO_ROW_MAPPER))).thenReturn( + mockConfigs); //execute return mock obj - List configAllInfosIds = embeddedConfigInfoPersistService.findAllConfigInfo4Export(dataId, group, - tenant, appName, ids); + List configAllInfosIds = embeddedConfigInfoPersistService.findAllConfigInfo4Export(dataId, group, tenant, appName, + ids); //expect check - Assert.assertEquals(mockConfigs, configAllInfosIds); + assertEquals(mockConfigs, configAllInfosIds); when(databaseOperate.queryMany(anyString(), eq(new Object[] {tenant, dataId, group, appName}), eq(CONFIG_ALL_INFO_ROW_MAPPER))).thenReturn(mockConfigs); //execute return mock obj - List configAllInfosWithDataId = embeddedConfigInfoPersistService.findAllConfigInfo4Export(dataId, - group, tenant, appName, null); + List configAllInfosWithDataId = embeddedConfigInfoPersistService.findAllConfigInfo4Export(dataId, group, tenant, + appName, null); //expect check - Assert.assertEquals(mockConfigs, configAllInfosWithDataId); + assertEquals(mockConfigs, configAllInfosWithDataId); } @Test - public void testQueryConfigInfoByNamespace() { + void testQueryConfigInfoByNamespace() { //mock select config state List mockConfigs = new ArrayList<>(); @@ -958,17 +925,15 @@ public void testQueryConfigInfoByNamespace() { mockConfigs.add(createMockConfigInfoWrapper(1)); mockConfigs.add(createMockConfigInfoWrapper(2)); String tenant = "tenant13245"; - when(databaseOperate.queryMany(anyString(), eq(new Object[] {tenant}), - eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))).thenReturn(mockConfigs); + when(databaseOperate.queryMany(anyString(), eq(new Object[] {tenant}), eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))).thenReturn(mockConfigs); //execute return mock obj - List configInfoWrappers = embeddedConfigInfoPersistService.queryConfigInfoByNamespace( - tenant); + List configInfoWrappers = embeddedConfigInfoPersistService.queryConfigInfoByNamespace(tenant); //expect check - Assert.assertEquals(mockConfigs, configInfoWrappers); + assertEquals(mockConfigs, configInfoWrappers); } @Test - public void testGetTenantIdList() { + void testGetTenantIdList() { //mock select config state List tenantStrings = Arrays.asList("tenant1", "tenant2", "tenant3"); @@ -987,11 +952,11 @@ public void testGetTenantIdList() { //execute return mock obj List returnTenants = embeddedConfigInfoPersistService.getTenantIdList(page, pageSize); //expect check - Assert.assertEquals(tenantStrings, returnTenants); + assertEquals(tenantStrings, returnTenants); } @Test - public void testGetGroupIdList() { + void testGetGroupIdList() { //mock select config state List groupStrings = Arrays.asList("group1", "group2", "group3"); @@ -1011,25 +976,23 @@ public void testGetGroupIdList() { List returnGroups = embeddedConfigInfoPersistService.getGroupIdList(page, pageSize); //expect check - Assert.assertEquals(groupStrings, returnGroups); + assertEquals(groupStrings, returnGroups); } @Test - public void testFindAllConfigInfoFragment() { + void testFindAllConfigInfoFragment() { //mock page list List mockConfigs = new ArrayList<>(); mockConfigs.add(createMockConfigInfoWrapper(0)); mockConfigs.add(createMockConfigInfoWrapper(1)); mockConfigs.add(createMockConfigInfoWrapper(2)); long lastId = 10111L; - when(databaseOperate.queryMany(anyString(), eq(new Object[] {lastId}), - eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))).thenReturn(mockConfigs); + when(databaseOperate.queryMany(anyString(), eq(new Object[] {lastId}), eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))).thenReturn(mockConfigs); int pageSize = 100; //execute return mock obj - Page returnConfigPage = embeddedConfigInfoPersistService.findAllConfigInfoFragment(lastId, - pageSize, true); + Page returnConfigPage = embeddedConfigInfoPersistService.findAllConfigInfoFragment(lastId, pageSize, true); //expect check - Assert.assertEquals(mockConfigs, returnConfigPage.getPageItems()); + assertEquals(mockConfigs, returnConfigPage.getPageItems()); } } \ No newline at end of file diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoTagPersistServiceImplTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoTagPersistServiceImplTest.java index 90466e04f4e..5c09eeef356 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoTagPersistServiceImplTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoTagPersistServiceImplTest.java @@ -28,15 +28,14 @@ import com.alibaba.nacos.persistence.repository.embedded.EmbeddedStorageContextHolder; import com.alibaba.nacos.persistence.repository.embedded.operate.DatabaseOperate; import com.alibaba.nacos.sys.env.EnvUtil; -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.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import java.sql.Timestamp; import java.util.ArrayList; @@ -45,6 +44,7 @@ import static com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER; import static com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.CONFIG_INFO_TAG_WRAPPER_ROW_MAPPER; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -52,16 +52,12 @@ import static org.mockito.Mockito.when; /** - * test for embedded config tag. + * test for embedded config tag. + * * @author shiyiyue */ -@RunWith(SpringJUnit4ClassRunner.class) -public class EmbeddedConfigInfoTagPersistServiceImplTest { - - private EmbeddedConfigInfoTagPersistServiceImpl embeddedConfigInfoTagPersistService; - - @Mock - private DataSourceService dataSourceService; +@ExtendWith(SpringExtension.class) +class EmbeddedConfigInfoTagPersistServiceImplTest { MockedStatic envUtilMockedStatic; @@ -75,28 +71,32 @@ public class EmbeddedConfigInfoTagPersistServiceImplTest { @Mock DatabaseOperate databaseOperate; - @Before - public void before() { + private EmbeddedConfigInfoTagPersistServiceImpl embeddedConfigInfoTagPersistService; + + @Mock + private DataSourceService dataSourceService; + + @BeforeEach + void before() { embeddedStorageContextHolderMockedStatic = Mockito.mockStatic(EmbeddedStorageContextHolder.class); dynamicDataSourceMockedStatic = Mockito.mockStatic(DynamicDataSource.class); envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); when(DynamicDataSource.getInstance()).thenReturn(dynamicDataSource); when(dynamicDataSource.getDataSource()).thenReturn(dataSourceService); when(dataSourceService.getDataSourceType()).thenReturn("derby"); - envUtilMockedStatic.when(() -> EnvUtil.getProperty(anyString(), eq(Boolean.class), eq(false))) - .thenReturn(false); + envUtilMockedStatic.when(() -> EnvUtil.getProperty(anyString(), eq(Boolean.class), eq(false))).thenReturn(false); embeddedConfigInfoTagPersistService = new EmbeddedConfigInfoTagPersistServiceImpl(databaseOperate); } - @After - public void after() { + @AfterEach + void after() { dynamicDataSourceMockedStatic.close(); envUtilMockedStatic.close(); embeddedStorageContextHolderMockedStatic.close(); } @Test - public void testInsertOrUpdateTagOfAdd() { + void testInsertOrUpdateTagOfAdd() { String dataId = "dataId111222"; String group = "group"; String tenant = "tenant"; @@ -116,21 +116,20 @@ public void testInsertOrUpdateTagOfAdd() { String srcIp = "ip345678"; String srcUser = "user1234567"; - ConfigOperateResult configOperateResult = embeddedConfigInfoTagPersistService.insertOrUpdateTag(configInfo, tag, - srcIp, srcUser); + ConfigOperateResult configOperateResult = embeddedConfigInfoTagPersistService.insertOrUpdateTag(configInfo, tag, srcIp, srcUser); //mock insert invoked. embeddedStorageContextHolderMockedStatic.verify( - () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(dataId), eq(group), eq(tenant), - eq(tag), eq(appName), eq(content), eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), - eq(srcIp), eq(srcUser), any(Timestamp.class), any(Timestamp.class)), times(1)); - Assert.assertEquals(configInfoStateWrapper.getId(), configOperateResult.getId()); - Assert.assertEquals(configInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); + () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(dataId), eq(group), eq(tenant), eq(tag), eq(appName), + eq(content), eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), eq(srcIp), eq(srcUser), any(Timestamp.class), + any(Timestamp.class)), times(1)); + assertEquals(configInfoStateWrapper.getId(), configOperateResult.getId()); + assertEquals(configInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); } @Test - public void testInsertOrUpdateTagOfUpdate() { + void testInsertOrUpdateTagOfUpdate() { String dataId = "dataId111222"; String group = "group"; String tenant = "tenant"; @@ -146,24 +145,21 @@ public void testInsertOrUpdateTagOfUpdate() { String tag = "tag123"; Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant, tag}), - eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(new ConfigInfoStateWrapper()) - .thenReturn(configInfoStateWrapper); + eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(new ConfigInfoStateWrapper()).thenReturn(configInfoStateWrapper); String srcIp = "ip345678"; String srcUser = "user1234567"; - ConfigOperateResult configOperateResult = embeddedConfigInfoTagPersistService.insertOrUpdateTag(configInfo, tag, - srcIp, srcUser); + ConfigOperateResult configOperateResult = embeddedConfigInfoTagPersistService.insertOrUpdateTag(configInfo, tag, srcIp, srcUser); //verify update to be invoked - embeddedStorageContextHolderMockedStatic.verify( - () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(content), - eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), eq(srcIp), eq(srcUser), - any(Timestamp.class), eq(appName), eq(dataId), eq(group), eq(tenant), eq(tag)), times(1)); - Assert.assertEquals(configInfoStateWrapper.getId(), configOperateResult.getId()); - Assert.assertEquals(configInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); + embeddedStorageContextHolderMockedStatic.verify(() -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(content), + eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), eq(srcIp), eq(srcUser), any(Timestamp.class), eq(appName), + eq(dataId), eq(group), eq(tenant), eq(tag)), times(1)); + assertEquals(configInfoStateWrapper.getId(), configOperateResult.getId()); + assertEquals(configInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); } @Test - public void testInsertOrUpdateTagCasOfAdd() { + void testInsertOrUpdateTagCasOfAdd() { String dataId = "dataId111222"; String group = "group"; String tenant = "tenant"; @@ -184,21 +180,20 @@ public void testInsertOrUpdateTagCasOfAdd() { String srcIp = "ip345678"; String srcUser = "user1234567"; - ConfigOperateResult configOperateResult = embeddedConfigInfoTagPersistService.insertOrUpdateTagCas(configInfo, - tag, srcIp, srcUser); + ConfigOperateResult configOperateResult = embeddedConfigInfoTagPersistService.insertOrUpdateTagCas(configInfo, tag, srcIp, srcUser); //verify insert to be invoked //mock insert invoked. embeddedStorageContextHolderMockedStatic.verify( - () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(dataId), eq(group), eq(tenant), - eq(tag), eq(appName), eq(content), eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), - eq(srcIp), eq(srcUser), any(Timestamp.class), any(Timestamp.class)), times(1)); - Assert.assertEquals(configInfoStateWrapper.getId(), configOperateResult.getId()); - Assert.assertEquals(configInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); + () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(dataId), eq(group), eq(tenant), eq(tag), eq(appName), + eq(content), eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), eq(srcIp), eq(srcUser), any(Timestamp.class), + any(Timestamp.class)), times(1)); + assertEquals(configInfoStateWrapper.getId(), configOperateResult.getId()); + assertEquals(configInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); } @Test - public void testInsertOrUpdateTagCasOfUpdate() { + void testInsertOrUpdateTagCasOfUpdate() { String dataId = "dataId111222"; String group = "group"; String tenant = "tenant"; @@ -214,27 +209,23 @@ public void testInsertOrUpdateTagCasOfUpdate() { configInfoStateWrapper.setId(234567890L); String tag = "tag123"; Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant, tag}), - eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(new ConfigInfoStateWrapper()) - .thenReturn(configInfoStateWrapper); + eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(new ConfigInfoStateWrapper()).thenReturn(configInfoStateWrapper); String srcIp = "ip345678"; String srcUser = "user1234567"; //mock cas update return 1 Mockito.when(databaseOperate.blockUpdate()).thenReturn(true); - ConfigOperateResult configOperateResult = embeddedConfigInfoTagPersistService.insertOrUpdateTagCas(configInfo, - tag, srcIp, srcUser); + ConfigOperateResult configOperateResult = embeddedConfigInfoTagPersistService.insertOrUpdateTagCas(configInfo, tag, srcIp, srcUser); //verify update to be invoked - embeddedStorageContextHolderMockedStatic.verify( - () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(content), - eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), eq(srcIp), eq(srcUser), - any(Timestamp.class), eq(appName), eq(dataId), eq(group), eq(tenant), eq(tag), - eq(configInfo.getMd5())), times(1)); - Assert.assertEquals(configInfoStateWrapper.getId(), configOperateResult.getId()); - Assert.assertEquals(configInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); + embeddedStorageContextHolderMockedStatic.verify(() -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(content), + eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), eq(srcIp), eq(srcUser), any(Timestamp.class), eq(appName), + eq(dataId), eq(group), eq(tenant), eq(tag), eq(configInfo.getMd5())), times(1)); + assertEquals(configInfoStateWrapper.getId(), configOperateResult.getId()); + assertEquals(configInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); } @Test - public void testRemoveConfigInfoTag() { + void testRemoveConfigInfoTag() { String dataId = "dataId1112222"; String group = "group22"; String tenant = "tenant2"; @@ -244,12 +235,11 @@ public void testRemoveConfigInfoTag() { embeddedConfigInfoTagPersistService.removeConfigInfoTag(dataId, group, tenant, tag, srcIp, srcUser); //verify delete sql invoked. embeddedStorageContextHolderMockedStatic.verify( - () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(dataId), eq(group), eq(tenant), - eq(tag)), times(1)); + () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(dataId), eq(group), eq(tenant), eq(tag)), times(1)); } @Test - public void testFindConfigInfo4Tag() { + void testFindConfigInfo4Tag() { String dataId = "dataId1112222"; String group = "group22"; String tenant = "tenant2"; @@ -262,24 +252,23 @@ public void testFindConfigInfo4Tag() { Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant, tag}), eq(CONFIG_INFO_TAG_WRAPPER_ROW_MAPPER))).thenReturn(configInfoTagWrapperMocked); - ConfigInfoTagWrapper configInfo4TagReturn = embeddedConfigInfoTagPersistService.findConfigInfo4Tag(dataId, - group, tenant, tag); - Assert.assertEquals(configInfoTagWrapperMocked, configInfo4TagReturn); + ConfigInfoTagWrapper configInfo4TagReturn = embeddedConfigInfoTagPersistService.findConfigInfo4Tag(dataId, group, tenant, tag); + assertEquals(configInfoTagWrapperMocked, configInfo4TagReturn); } @Test - public void testConfigInfoTagCount() { + void testConfigInfoTagCount() { Timestamp timestamp = new Timestamp(System.currentTimeMillis()); //mock count Mockito.when(databaseOperate.queryOne(anyString(), eq(Integer.class))).thenReturn(308); //execute & verify int count = embeddedConfigInfoTagPersistService.configInfoTagCount(); - Assert.assertEquals(308, count); + assertEquals(308, count); } @Test - public void testFindAllConfigInfoTagForDumpAll() { + void testFindAllConfigInfoTagForDumpAll() { //mock count Mockito.when(databaseOperate.queryOne(anyString(), eq(Integer.class))).thenReturn(308); @@ -291,20 +280,18 @@ public void testFindAllConfigInfoTagForDumpAll() { mockTagList.get(1).setLastModified(System.currentTimeMillis()); mockTagList.get(2).setLastModified(System.currentTimeMillis()); //mock query list - Mockito.when( - databaseOperate.queryMany(anyString(), eq(new Object[] {}), eq(CONFIG_INFO_TAG_WRAPPER_ROW_MAPPER))) + Mockito.when(databaseOperate.queryMany(anyString(), eq(new Object[] {}), eq(CONFIG_INFO_TAG_WRAPPER_ROW_MAPPER))) .thenReturn(mockTagList); int pageNo = 3; int pageSize = 100; //execute & verify - Page returnTagPage = embeddedConfigInfoTagPersistService.findAllConfigInfoTagForDumpAll( - pageNo, pageSize); - Assert.assertEquals(308, returnTagPage.getTotalCount()); - Assert.assertEquals(mockTagList, returnTagPage.getPageItems()); + Page returnTagPage = embeddedConfigInfoTagPersistService.findAllConfigInfoTagForDumpAll(pageNo, pageSize); + assertEquals(308, returnTagPage.getTotalCount()); + assertEquals(mockTagList, returnTagPage.getPageItems()); } @Test - public void testFindConfigInfoTags() { + void testFindConfigInfoTags() { String dataId = "dataId1112222"; String group = "group22"; String tenant = "tenant2"; @@ -312,6 +299,6 @@ public void testFindConfigInfoTags() { Mockito.when(databaseOperate.queryMany(anyString(), eq(new Object[] {dataId, group, tenant}), eq(String.class))) .thenReturn(mockedTags); List configInfoTags = embeddedConfigInfoTagPersistService.findConfigInfoTags(dataId, group, tenant); - Assert.assertEquals(mockedTags, configInfoTags); + assertEquals(mockedTags, configInfoTags); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedHistoryConfigInfoPersistServiceImplTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedHistoryConfigInfoPersistServiceImplTest.java index 52b27017329..47a33bf16a2 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedHistoryConfigInfoPersistServiceImplTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedHistoryConfigInfoPersistServiceImplTest.java @@ -25,15 +25,14 @@ import com.alibaba.nacos.persistence.repository.embedded.EmbeddedStorageContextHolder; import com.alibaba.nacos.persistence.repository.embedded.operate.DatabaseOperate; import com.alibaba.nacos.sys.env.EnvUtil; -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.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import java.sql.Timestamp; import java.util.ArrayList; @@ -42,6 +41,7 @@ import static com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER; import static com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.HISTORY_DETAIL_ROW_MAPPER; import static com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.HISTORY_LIST_ROW_MAPPER; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; @@ -52,13 +52,8 @@ * * @author shiyiyue */ -@RunWith(SpringJUnit4ClassRunner.class) -public class EmbeddedHistoryConfigInfoPersistServiceImplTest { - - private EmbeddedHistoryConfigInfoPersistServiceImpl embeddedHistoryConfigInfoPersistService; - - @Mock - private DataSourceService dataSourceService; +@ExtendWith(SpringExtension.class) +class EmbeddedHistoryConfigInfoPersistServiceImplTest { MockedStatic envUtilMockedStatic; @@ -72,28 +67,32 @@ public class EmbeddedHistoryConfigInfoPersistServiceImplTest { @Mock DatabaseOperate databaseOperate; - @Before - public void before() { + private EmbeddedHistoryConfigInfoPersistServiceImpl embeddedHistoryConfigInfoPersistService; + + @Mock + private DataSourceService dataSourceService; + + @BeforeEach + void before() { embeddedStorageContextHolderMockedStatic = Mockito.mockStatic(EmbeddedStorageContextHolder.class); dynamicDataSourceMockedStatic = Mockito.mockStatic(DynamicDataSource.class); envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); when(DynamicDataSource.getInstance()).thenReturn(dynamicDataSource); when(dynamicDataSource.getDataSource()).thenReturn(dataSourceService); when(dataSourceService.getDataSourceType()).thenReturn("derby"); - envUtilMockedStatic.when(() -> EnvUtil.getProperty(anyString(), eq(Boolean.class), eq(false))) - .thenReturn(false); + envUtilMockedStatic.when(() -> EnvUtil.getProperty(anyString(), eq(Boolean.class), eq(false))).thenReturn(false); embeddedHistoryConfigInfoPersistService = new EmbeddedHistoryConfigInfoPersistServiceImpl(databaseOperate); } - @After - public void after() { + @AfterEach + void after() { dynamicDataSourceMockedStatic.close(); envUtilMockedStatic.close(); embeddedStorageContextHolderMockedStatic.close(); } @Test - public void testInsertConfigHistoryAtomic() { + void testInsertConfigHistoryAtomic() { String dataId = "dateId243"; String group = "group243"; String tenant = "tenant243"; @@ -107,18 +106,17 @@ public void testInsertConfigHistoryAtomic() { ConfigInfo configInfo = new ConfigInfo(dataId, group, tenant, appName, content); configInfo.setEncryptedDataKey("key23456"); //expect insert success,verify insert invoked - embeddedHistoryConfigInfoPersistService.insertConfigHistoryAtomic(id, configInfo, srcIp, srcUser, timestamp, - ops); + embeddedHistoryConfigInfoPersistService.insertConfigHistoryAtomic(id, configInfo, srcIp, srcUser, timestamp, ops); //verify insert to be invoked embeddedStorageContextHolderMockedStatic.verify( - () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(id), eq(dataId), eq(group), eq(tenant), - eq(appName), eq(content), eq(configInfo.getMd5()), eq(srcIp), eq(srcUser), eq(timestamp), - eq(ops), eq(configInfo.getEncryptedDataKey())), times(1)); + () -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(id), eq(dataId), eq(group), eq(tenant), eq(appName), + eq(content), eq(configInfo.getMd5()), eq(srcIp), eq(srcUser), eq(timestamp), eq(ops), + eq(configInfo.getEncryptedDataKey())), times(1)); } @Test - public void testRemoveConfigHistory() { + void testRemoveConfigHistory() { Timestamp timestamp = new Timestamp(System.currentTimeMillis()); int pageSize = 1233; embeddedHistoryConfigInfoPersistService.removeConfigHistory(timestamp, pageSize); @@ -128,7 +126,7 @@ public void testRemoveConfigHistory() { } @Test - public void testFindDeletedConfig() { + void testFindDeletedConfig() { //mock query list return ConfigInfoStateWrapper mockObj1 = new ConfigInfoStateWrapper(); @@ -152,47 +150,46 @@ public void testFindDeletedConfig() { Mockito.when(databaseOperate.queryMany(anyString(), eq(new Object[] {timestamp, startId, pageSize}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(list); //execute - List deletedConfig = embeddedHistoryConfigInfoPersistService.findDeletedConfig( - timestamp, startId, pageSize); + List deletedConfig = embeddedHistoryConfigInfoPersistService.findDeletedConfig(timestamp, startId, + pageSize); //expect verify - Assert.assertEquals("data_id1", deletedConfig.get(0).getDataId()); - Assert.assertEquals("group_id1", deletedConfig.get(0).getGroup()); - Assert.assertEquals("tenant_id1", deletedConfig.get(0).getTenant()); - Assert.assertEquals(mockObj1.getLastModified(), deletedConfig.get(0).getLastModified()); - Assert.assertEquals("data_id2", deletedConfig.get(1).getDataId()); - Assert.assertEquals("group_id2", deletedConfig.get(1).getGroup()); - Assert.assertEquals("tenant_id2", deletedConfig.get(1).getTenant()); - Assert.assertEquals(mockObj2.getLastModified(), deletedConfig.get(1).getLastModified()); + assertEquals("data_id1", deletedConfig.get(0).getDataId()); + assertEquals("group_id1", deletedConfig.get(0).getGroup()); + assertEquals("tenant_id1", deletedConfig.get(0).getTenant()); + assertEquals(mockObj1.getLastModified(), deletedConfig.get(0).getLastModified()); + assertEquals("data_id2", deletedConfig.get(1).getDataId()); + assertEquals("group_id2", deletedConfig.get(1).getGroup()); + assertEquals("tenant_id2", deletedConfig.get(1).getTenant()); + assertEquals(mockObj2.getLastModified(), deletedConfig.get(1).getLastModified()); } @Test - public void testFindConfigHistory() { + void testFindConfigHistory() { String dataId = "dataId34567"; String group = "group34567"; String tenant = "tenant34567"; //mock count - Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), eq(Integer.class))) - .thenReturn(300); + Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), eq(Integer.class))).thenReturn(300); //mock list List mockList = new ArrayList<>(); mockList.add(createMockConfigHistoryInfo(0)); mockList.add(createMockConfigHistoryInfo(1)); mockList.add(createMockConfigHistoryInfo(2)); - Mockito.when(databaseOperate.queryMany(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(HISTORY_LIST_ROW_MAPPER))).thenReturn(mockList); + Mockito.when(databaseOperate.queryMany(anyString(), eq(new Object[] {dataId, group, tenant}), eq(HISTORY_LIST_ROW_MAPPER))) + .thenReturn(mockList); int pageSize = 100; int pageNo = 2; //execute & verify - Page historyReturn = embeddedHistoryConfigInfoPersistService.findConfigHistory(dataId, group, - tenant, pageNo, pageSize); - Assert.assertEquals(mockList, historyReturn.getPageItems()); - Assert.assertEquals(300, historyReturn.getTotalCount()); + Page historyReturn = embeddedHistoryConfigInfoPersistService.findConfigHistory(dataId, group, tenant, pageNo, + pageSize); + assertEquals(mockList, historyReturn.getPageItems()); + assertEquals(300, historyReturn.getTotalCount()); } @Test - public void testDetailConfigHistory() { + void testDetailConfigHistory() { long nid = 256789; //mock query @@ -201,11 +198,11 @@ public void testDetailConfigHistory() { .thenReturn(mockConfigHistoryInfo); //execute & verify ConfigHistoryInfo historyReturn = embeddedHistoryConfigInfoPersistService.detailConfigHistory(nid); - Assert.assertEquals(mockConfigHistoryInfo, historyReturn); + assertEquals(mockConfigHistoryInfo, historyReturn); } @Test - public void testDetailPreviousConfigHistory() { + void testDetailPreviousConfigHistory() { long nid = 256789; //mock query ConfigHistoryInfo mockConfigHistoryInfo = createMockConfigHistoryInfo(0); @@ -213,19 +210,18 @@ public void testDetailPreviousConfigHistory() { .thenReturn(mockConfigHistoryInfo); //execute & verify ConfigHistoryInfo historyReturn = embeddedHistoryConfigInfoPersistService.detailPreviousConfigHistory(nid); - Assert.assertEquals(mockConfigHistoryInfo, historyReturn); + assertEquals(mockConfigHistoryInfo, historyReturn); } @Test - public void testFindConfigHistoryCountByTime() { + void testFindConfigHistoryCountByTime() { Timestamp timestamp = new Timestamp(System.currentTimeMillis()); //mock count - Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {timestamp}), eq(Integer.class))) - .thenReturn(308); + Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {timestamp}), eq(Integer.class))).thenReturn(308); //execute & verify int count = embeddedHistoryConfigInfoPersistService.findConfigHistoryCountByTime(timestamp); - Assert.assertEquals(308, count); + assertEquals(308, count); } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalConfigInfoAggrPersistServiceImplTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalConfigInfoAggrPersistServiceImplTest.java index 47922d240e2..93209fb85fa 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalConfigInfoAggrPersistServiceImplTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalConfigInfoAggrPersistServiceImplTest.java @@ -24,18 +24,17 @@ import com.alibaba.nacos.persistence.datasource.DynamicDataSource; import com.alibaba.nacos.persistence.model.Page; import com.alibaba.nacos.sys.env.EnvUtil; -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.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.CannotGetJdbcConnectionException; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.transaction.TransactionSystemException; import org.springframework.transaction.support.TransactionTemplate; @@ -47,13 +46,26 @@ import static com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.CONFIG_INFO_AGGR_ROW_MAPPER; import static com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.CONFIG_INFO_CHANGED_ROW_MAPPER; +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.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; -@RunWith(SpringJUnit4ClassRunner.class) -public class ExternalConfigInfoAggrPersistServiceImplTest { +@ExtendWith(SpringExtension.class) +class ExternalConfigInfoAggrPersistServiceImplTest { + + MockedStatic envUtilMockedStatic; + + MockedStatic externalStorageUtilsMockedStatic; + + MockedStatic dynamicDataSourceMockedStatic; + + @Mock + DynamicDataSource dynamicDataSource; private ExternalConfigInfoAggrPersistServiceImpl externalConfigInfoAggrPersistService; @@ -65,17 +77,8 @@ public class ExternalConfigInfoAggrPersistServiceImplTest { private TransactionTemplate transactionTemplate = TestCaseUtils.createMockTransactionTemplate(); - MockedStatic envUtilMockedStatic; - - MockedStatic externalStorageUtilsMockedStatic; - - MockedStatic dynamicDataSourceMockedStatic; - - @Mock - DynamicDataSource dynamicDataSource; - - @Before - public void before() { + @BeforeEach + void before() { dynamicDataSourceMockedStatic = Mockito.mockStatic(DynamicDataSource.class); envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); externalStorageUtilsMockedStatic = Mockito.mockStatic(ExternalStorageUtils.class); @@ -84,21 +87,20 @@ public void before() { when(dataSourceService.getTransactionTemplate()).thenReturn(transactionTemplate); when(dataSourceService.getJdbcTemplate()).thenReturn(jdbcTemplate); when(dataSourceService.getDataSourceType()).thenReturn("mysql"); - envUtilMockedStatic.when(() -> EnvUtil.getProperty(anyString(), eq(Boolean.class), eq(false))) - .thenReturn(false); + envUtilMockedStatic.when(() -> EnvUtil.getProperty(anyString(), eq(Boolean.class), eq(false))).thenReturn(false); externalConfigInfoAggrPersistService = new ExternalConfigInfoAggrPersistServiceImpl(); } - @After - public void after() { + @AfterEach + void after() { dynamicDataSourceMockedStatic.close(); envUtilMockedStatic.close(); externalStorageUtilsMockedStatic.close(); } @Test - public void testAddAggrConfigInfoOfEqualContent() { + void testAddAggrConfigInfoOfEqualContent() { String dataId = "dataId111"; String group = "group"; String tenant = "tenant"; @@ -108,16 +110,15 @@ public void testAddAggrConfigInfoOfEqualContent() { //mock query datumId and equal with current content param. String existContent = "content1234"; - when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, datumId}), - eq(String.class))).thenReturn(existContent); + when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, datumId}), eq(String.class))).thenReturn( + existContent); - boolean result = externalConfigInfoAggrPersistService.addAggrConfigInfo(dataId, group, tenant, datumId, appName, - content); - Assert.assertTrue(result); + boolean result = externalConfigInfoAggrPersistService.addAggrConfigInfo(dataId, group, tenant, datumId, appName, content); + assertTrue(result); } @Test - public void testAddAggrConfigInfoOfAddNewContent() { + void testAddAggrConfigInfoOfAddNewContent() { String dataId = "dataId111"; String group = "group"; String tenant = "tenant"; @@ -126,20 +127,19 @@ public void testAddAggrConfigInfoOfAddNewContent() { String content = "content1234"; //mock query datumId and throw EmptyResultDataAccessException. - when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, datumId}), - eq(String.class))).thenThrow(new EmptyResultDataAccessException(1)); + when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, datumId}), eq(String.class))).thenThrow( + new EmptyResultDataAccessException(1)); //mock insert success when(jdbcTemplate.update(anyString(), eq(dataId), eq(group), eq(tenant), eq(datumId), eq(appName), eq(content), any(Timestamp.class))).thenReturn(1); //execute - boolean result = externalConfigInfoAggrPersistService.addAggrConfigInfo(dataId, group, tenant, datumId, appName, - content); - Assert.assertTrue(result); + boolean result = externalConfigInfoAggrPersistService.addAggrConfigInfo(dataId, group, tenant, datumId, appName, content); + assertTrue(result); } @Test - public void testAddAggrConfigInfoOfUpdateNotEqualContent() { + void testAddAggrConfigInfoOfUpdateNotEqualContent() { String dataId = "dataId111"; String group = "group"; String tenant = "tenant"; @@ -149,20 +149,19 @@ public void testAddAggrConfigInfoOfUpdateNotEqualContent() { //mock query datumId String existContent = "existContent111"; - when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, datumId}), - eq(String.class))).thenReturn(existContent); + when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, datumId}), eq(String.class))).thenReturn( + existContent); //mock update success,return 1 when(jdbcTemplate.update(anyString(), eq(content), any(Timestamp.class), eq(dataId), eq(group), eq(tenant), eq(datumId))).thenReturn(1); //mock update content - boolean result = externalConfigInfoAggrPersistService.addAggrConfigInfo(dataId, group, tenant, datumId, appName, - content); - Assert.assertTrue(result); + boolean result = externalConfigInfoAggrPersistService.addAggrConfigInfo(dataId, group, tenant, datumId, appName, content); + assertTrue(result); } @Test - public void testAddAggrConfigInfoOfException() { + void testAddAggrConfigInfoOfException() { String dataId = "dataId111"; String group = "group"; String tenant = "tenant"; @@ -171,159 +170,151 @@ public void testAddAggrConfigInfoOfException() { String content = "content1234"; //mock query datumId and throw EmptyResultDataAccessException. - when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, datumId}), - eq(String.class))).thenThrow(new CannotGetJdbcConnectionException("mock exp")); + when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, datumId}), eq(String.class))).thenThrow( + new CannotGetJdbcConnectionException("mock exp")); try { externalConfigInfoAggrPersistService.addAggrConfigInfo(dataId, group, tenant, datumId, appName, content); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception exp) { - Assert.assertEquals("mock exp", exp.getMessage()); + assertEquals("mock exp", exp.getMessage()); } } @Test - public void testBatchPublishAggrSuccess() { + void testBatchPublishAggrSuccess() { String dataId = "dataId111"; String group = "group"; String tenant = "tenant"; //mock query datumId and equal with current content param. - when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, "d1"}), - eq(String.class))).thenReturn("c1"); - when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, "d2"}), - eq(String.class))).thenReturn("c2"); - when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, "d3"}), - eq(String.class))).thenReturn("c3"); + when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, "d1"}), eq(String.class))).thenReturn("c1"); + when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, "d2"}), eq(String.class))).thenReturn("c2"); + when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, "d3"}), eq(String.class))).thenReturn("c3"); Map datumMap = new HashMap<>(); datumMap.put("d1", "c1"); datumMap.put("d2", "c2"); datumMap.put("d3", "c3"); String appName = "appname1234"; - boolean result = externalConfigInfoAggrPersistService.batchPublishAggr(dataId, group, tenant, datumMap, - appName); - Assert.assertTrue(result); + boolean result = externalConfigInfoAggrPersistService.batchPublishAggr(dataId, group, tenant, datumMap, appName); + assertTrue(result); } @Test - public void testBatchPublishAggrException() { + void testBatchPublishAggrException() { String dataId = "dataId111"; String group = "group"; String tenant = "tenant"; //mock query datumId and equal with current content param. - when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, "d1"}), - eq(String.class))).thenThrow(new TransactionSystemException("c1t fail")); + when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, "d1"}), eq(String.class))).thenThrow( + new TransactionSystemException("c1t fail")); Map datumMap = new HashMap<>(); datumMap.put("d1", "c1"); datumMap.put("d2", "c2"); datumMap.put("d3", "c3"); String appName = "appname1234"; - boolean result = externalConfigInfoAggrPersistService.batchPublishAggr(dataId, group, tenant, datumMap, - appName); - Assert.assertFalse(result); + boolean result = externalConfigInfoAggrPersistService.batchPublishAggr(dataId, group, tenant, datumMap, appName); + assertFalse(result); } @Test - public void testAggrConfigInfoCount() { + void testAggrConfigInfoCount() { String dataId = "dataId11122"; String group = "group"; String tenant = "tenant"; //mock select count of aggr. - when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class), eq(dataId), eq(group), eq(tenant))).thenReturn( - new Integer(101)); + when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class), eq(dataId), eq(group), eq(tenant))).thenReturn(new Integer(101)); int result = externalConfigInfoAggrPersistService.aggrConfigInfoCount(dataId, group, tenant); - Assert.assertEquals(101, result); + assertEquals(101, result); } @Test - public void testFindConfigInfoAggrByPage() { + void testFindConfigInfoAggrByPage() { String dataId = "dataId111"; String group = "group"; String tenant = "tenant"; //mock query count. - when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(Integer.class))).thenReturn(101); + when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), eq(Integer.class))).thenReturn(101); //mock query page list List configInfoAggrs = new ArrayList<>(); configInfoAggrs.add(new ConfigInfoAggr()); configInfoAggrs.add(new ConfigInfoAggr()); configInfoAggrs.add(new ConfigInfoAggr()); - when(jdbcTemplate.query(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_AGGR_ROW_MAPPER))).thenReturn(configInfoAggrs); + when(jdbcTemplate.query(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_AGGR_ROW_MAPPER))).thenReturn( + configInfoAggrs); int pageNo = 1; int pageSize = 120; - Page configInfoAggrByPage = externalConfigInfoAggrPersistService.findConfigInfoAggrByPage( - dataId, group, tenant, pageNo, pageSize); - Assert.assertEquals(101, configInfoAggrByPage.getTotalCount()); - Assert.assertEquals(configInfoAggrs, configInfoAggrByPage.getPageItems()); + Page configInfoAggrByPage = externalConfigInfoAggrPersistService.findConfigInfoAggrByPage(dataId, group, tenant, + pageNo, pageSize); + assertEquals(101, configInfoAggrByPage.getTotalCount()); + assertEquals(configInfoAggrs, configInfoAggrByPage.getPageItems()); } @Test - public void testFindConfigInfoAggrByPageOfException() { + void testFindConfigInfoAggrByPageOfException() { String dataId = "dataId111"; String group = "group"; String tenant = "tenant"; //mock query count exception. - when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(Integer.class))).thenThrow(new CannotGetJdbcConnectionException("mock fail222")); + when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), eq(Integer.class))).thenThrow( + new CannotGetJdbcConnectionException("mock fail222")); try { int pageNo = 1; int pageSize = 120; externalConfigInfoAggrPersistService.findConfigInfoAggrByPage(dataId, group, tenant, pageNo, pageSize); - Assert.assertTrue(false); + assertTrue(false); } catch (Throwable throwable) { - Assert.assertEquals("mock fail222", throwable.getMessage()); + assertEquals("mock fail222", throwable.getMessage()); } } @Test - public void testFindAllAggrGroup() { + void testFindAllAggrGroup() { List configList = new ArrayList<>(); configList.add(create("dataId", 0)); configList.add(create("dataId", 1)); //mock return list - when(jdbcTemplate.query(anyString(), eq(new Object[] {}), eq(CONFIG_INFO_CHANGED_ROW_MAPPER))).thenReturn( - configList); + when(jdbcTemplate.query(anyString(), eq(new Object[] {}), eq(CONFIG_INFO_CHANGED_ROW_MAPPER))).thenReturn(configList); List allAggrGroup = externalConfigInfoAggrPersistService.findAllAggrGroup(); - Assert.assertEquals(configList, allAggrGroup); + assertEquals(configList, allAggrGroup); } @Test - public void testFindAllAggrGroupException() { + void testFindAllAggrGroupException() { //mock throw CannotGetJdbcConnectionException when(jdbcTemplate.query(anyString(), eq(new Object[] {}), eq(CONFIG_INFO_CHANGED_ROW_MAPPER))).thenThrow( new CannotGetJdbcConnectionException("mock fail")); try { externalConfigInfoAggrPersistService.findAllAggrGroup(); - Assert.assertTrue(false); + assertTrue(false); } catch (Throwable throwable) { - Assert.assertEquals("mock fail", throwable.getMessage()); + assertEquals("mock fail", throwable.getMessage()); } //mock throw EmptyResultDataAccessException when(jdbcTemplate.query(anyString(), eq(new Object[] {}), eq(CONFIG_INFO_CHANGED_ROW_MAPPER))).thenThrow( new EmptyResultDataAccessException(1)); List allAggrGroup = externalConfigInfoAggrPersistService.findAllAggrGroup(); - Assert.assertEquals(null, allAggrGroup); + assertNull(allAggrGroup); //mock Exception when(jdbcTemplate.query(anyString(), eq(new Object[] {}), eq(CONFIG_INFO_CHANGED_ROW_MAPPER))).thenThrow( new RuntimeException("789")); try { externalConfigInfoAggrPersistService.findAllAggrGroup(); - Assert.assertTrue(false); + assertTrue(false); } catch (Throwable throwable) { - Assert.assertEquals("789", throwable.getCause().getMessage()); + assertEquals("789", throwable.getCause().getMessage()); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalConfigInfoBetaPersistServiceImplTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalConfigInfoBetaPersistServiceImplTest.java index c1ab3fb2f71..a84753b6470 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalConfigInfoBetaPersistServiceImplTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalConfigInfoBetaPersistServiceImplTest.java @@ -28,34 +28,43 @@ import com.alibaba.nacos.persistence.datasource.DynamicDataSource; import com.alibaba.nacos.persistence.model.Page; import com.alibaba.nacos.sys.env.EnvUtil; -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.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.CannotGetJdbcConnectionException; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.transaction.support.TransactionTemplate; -import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import static com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.CONFIG_INFO_BETA_WRAPPER_ROW_MAPPER; import static com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER; -import static org.mockito.ArgumentMatchers.any; +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.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; -@RunWith(SpringJUnit4ClassRunner.class) -public class ExternalConfigInfoBetaPersistServiceImplTest { +@ExtendWith(SpringExtension.class) +class ExternalConfigInfoBetaPersistServiceImplTest { + + MockedStatic envUtilMockedStatic; + + MockedStatic externalStorageUtilsMockedStatic; + + MockedStatic dynamicDataSourceMockedStatic; + + @Mock + DynamicDataSource dynamicDataSource; private ExternalConfigInfoBetaPersistServiceImpl externalConfigInfoBetaPersistService; @@ -67,17 +76,8 @@ public class ExternalConfigInfoBetaPersistServiceImplTest { private TransactionTemplate transactionTemplate = TestCaseUtils.createMockTransactionTemplate(); - MockedStatic envUtilMockedStatic; - - MockedStatic externalStorageUtilsMockedStatic; - - MockedStatic dynamicDataSourceMockedStatic; - - @Mock - DynamicDataSource dynamicDataSource; - - @Before - public void before() { + @BeforeEach + void before() { dynamicDataSourceMockedStatic = Mockito.mockStatic(DynamicDataSource.class); envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); externalStorageUtilsMockedStatic = Mockito.mockStatic(ExternalStorageUtils.class); @@ -86,20 +86,19 @@ public void before() { when(dataSourceService.getTransactionTemplate()).thenReturn(transactionTemplate); when(dataSourceService.getJdbcTemplate()).thenReturn(jdbcTemplate); when(dataSourceService.getDataSourceType()).thenReturn("mysql"); - envUtilMockedStatic.when(() -> EnvUtil.getProperty(anyString(), eq(Boolean.class), eq(false))) - .thenReturn(false); + envUtilMockedStatic.when(() -> EnvUtil.getProperty(anyString(), eq(Boolean.class), eq(false))).thenReturn(false); externalConfigInfoBetaPersistService = new ExternalConfigInfoBetaPersistServiceImpl(); } - @After - public void after() { + @AfterEach + void after() { dynamicDataSourceMockedStatic.close(); envUtilMockedStatic.close(); externalStorageUtilsMockedStatic.close(); } @Test - public void testInsertOrUpdateBetaOfUpdate() { + void testInsertOrUpdateBetaOfUpdate() { String dataId = "betaDataId113"; String group = "group"; String tenant = "tenant"; @@ -111,8 +110,7 @@ public void testInsertOrUpdateBetaOfUpdate() { mockedConfigInfoStateWrapper.setId(123456L); mockedConfigInfoStateWrapper.setLastModified(System.currentTimeMillis()); when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(mockedConfigInfoStateWrapper, - mockedConfigInfoStateWrapper); + eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(mockedConfigInfoStateWrapper, mockedConfigInfoStateWrapper); //execute String betaIps = "betaips..."; String srcIp = "srcUp..."; @@ -121,20 +119,19 @@ public void testInsertOrUpdateBetaOfUpdate() { String content = "content111"; ConfigInfo configInfo = new ConfigInfo(dataId, group, tenant, appName, content); configInfo.setEncryptedDataKey("key34567"); - ConfigOperateResult configOperateResult = externalConfigInfoBetaPersistService.insertOrUpdateBeta(configInfo, - betaIps, srcIp, srcUser); + ConfigOperateResult configOperateResult = externalConfigInfoBetaPersistService.insertOrUpdateBeta(configInfo, betaIps, srcIp, + srcUser); //expect return obj - Assert.assertEquals(mockedConfigInfoStateWrapper.getId(), configOperateResult.getId()); - Assert.assertEquals(mockedConfigInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); + assertEquals(mockedConfigInfoStateWrapper.getId(), configOperateResult.getId()); + assertEquals(mockedConfigInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); //verify update to be invoked Mockito.verify(jdbcTemplate, times(1)) - .update(anyString(), eq(configInfo.getContent()), eq(configInfo.getMd5()), eq(betaIps), eq(srcIp), - eq(srcUser), any(Timestamp.class), eq(configInfo.getAppName()), - eq(configInfo.getEncryptedDataKey()), eq(dataId), eq(group), eq(tenant)); + .update(anyString(), eq(configInfo.getContent()), eq(configInfo.getMd5()), eq(betaIps), eq(srcIp), eq(srcUser), + eq(configInfo.getAppName()), eq(configInfo.getEncryptedDataKey()), eq(dataId), eq(group), eq(tenant)); } @Test - public void testInsertOrUpdateBetaOfAdd() { + void testInsertOrUpdateBetaOfAdd() { String dataId = "betaDataId113"; String group = "group113"; String tenant = "tenant113"; @@ -157,21 +154,20 @@ public void testInsertOrUpdateBetaOfAdd() { ConfigInfo configInfo = new ConfigInfo(dataId, group, tenant, appName, content); configInfo.setEncryptedDataKey("key34567"); //execute - ConfigOperateResult configOperateResult = externalConfigInfoBetaPersistService.insertOrUpdateBeta(configInfo, - betaIps, srcIp, srcUser); + ConfigOperateResult configOperateResult = externalConfigInfoBetaPersistService.insertOrUpdateBeta(configInfo, betaIps, srcIp, + srcUser); //expect return obj - Assert.assertEquals(mockedConfigInfoStateWrapper.getId(), configOperateResult.getId()); - Assert.assertEquals(mockedConfigInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); + assertEquals(mockedConfigInfoStateWrapper.getId(), configOperateResult.getId()); + assertEquals(mockedConfigInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); //verify add to be invoked Mockito.verify(jdbcTemplate, times(1)) - .update(anyString(), eq(dataId), eq(group), eq(tenant), eq(configInfo.getAppName()), - eq(configInfo.getContent()), eq(configInfo.getMd5()), eq(betaIps), eq(srcIp), eq(srcUser), - any(Timestamp.class), any(Timestamp.class), eq(configInfo.getEncryptedDataKey())); + .update(anyString(), eq(dataId), eq(group), eq(tenant), eq(configInfo.getAppName()), eq(configInfo.getContent()), + eq(configInfo.getMd5()), eq(betaIps), eq(srcIp), eq(srcUser), eq(configInfo.getEncryptedDataKey())); } @Test - public void testInsertOrUpdateBetaOfException() { + void testInsertOrUpdateBetaOfException() { String dataId = "betaDataId113"; String group = "group113"; String tenant = "tenant113"; @@ -194,50 +190,47 @@ public void testInsertOrUpdateBetaOfException() { configInfo.setEncryptedDataKey("key34567"); // mock update throw CannotGetJdbcConnectionException - when(jdbcTemplate.update(anyString(), eq(configInfo.getContent()), eq(configInfo.getMd5()), eq(betaIps), - eq(srcIp), eq(srcUser), any(Timestamp.class), eq(configInfo.getAppName()), - eq(configInfo.getEncryptedDataKey()), eq(dataId), eq(group), eq(tenant))).thenThrow( - new CannotGetJdbcConnectionException("mock fail")); + when(jdbcTemplate.update(anyString(), eq(configInfo.getContent()), eq(configInfo.getMd5()), eq(betaIps), eq(srcIp), eq(srcUser), + eq(configInfo.getAppName()), eq(configInfo.getEncryptedDataKey()), eq(dataId), eq(group), + eq(tenant))).thenThrow(new CannotGetJdbcConnectionException("mock fail")); //execute of update& expect. try { externalConfigInfoBetaPersistService.insertOrUpdateBeta(configInfo, betaIps, srcIp, srcUser); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception exception) { - Assert.assertEquals("mock fail", exception.getMessage()); + assertEquals("mock fail", exception.getMessage()); } - + //mock query return null - when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), + when(jdbcTemplate.queryForObject(anyString(), eq(new Object[]{dataId, group, tenant}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(null); //mock add throw CannotGetJdbcConnectionException when(jdbcTemplate.update(anyString(), eq(dataId), eq(group), eq(tenant), eq(configInfo.getAppName()), eq(configInfo.getContent()), eq(configInfo.getMd5()), eq(betaIps), eq(srcIp), eq(srcUser), - any(Timestamp.class), any(Timestamp.class), eq(configInfo.getEncryptedDataKey()))).thenThrow( - new CannotGetJdbcConnectionException("mock fail add")); + eq(configInfo.getEncryptedDataKey()))).thenThrow(new CannotGetJdbcConnectionException("mock fail add")); //execute of add& expect. try { externalConfigInfoBetaPersistService.insertOrUpdateBeta(configInfo, betaIps, srcIp, srcUser); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception exception) { - Assert.assertEquals("mock fail add", exception.getMessage()); + assertEquals("mock fail add", exception.getMessage()); } - + //mock query throw CannotGetJdbcConnectionException when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenThrow( - new CannotGetJdbcConnectionException("get c fail")); + eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenThrow(new CannotGetJdbcConnectionException("get c fail")); //execute of add& expect. try { externalConfigInfoBetaPersistService.insertOrUpdateBeta(configInfo, betaIps, srcIp, srcUser); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception exception) { - Assert.assertEquals("get c fail", exception.getMessage()); + assertEquals("get c fail", exception.getMessage()); } } @Test - public void testInsertOrUpdateBetaCasOfUpdate() { + void testInsertOrUpdateBetaCasOfUpdate() { String dataId = "betaDataId113"; String group = "group"; String tenant = "tenant"; @@ -249,8 +242,7 @@ public void testInsertOrUpdateBetaCasOfUpdate() { mockedConfigInfoStateWrapper.setId(123456L); mockedConfigInfoStateWrapper.setLastModified(System.currentTimeMillis()); when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(mockedConfigInfoStateWrapper, - mockedConfigInfoStateWrapper); + eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(mockedConfigInfoStateWrapper, mockedConfigInfoStateWrapper); //execute String betaIps = "betaips..."; @@ -262,25 +254,24 @@ public void testInsertOrUpdateBetaCasOfUpdate() { configInfo.setEncryptedDataKey("key34567"); configInfo.setMd5("casMd5"); //mock cas update - when(jdbcTemplate.update(anyString(), eq(configInfo.getContent()), - eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), eq(betaIps), eq(srcIp), eq(srcUser), - any(Timestamp.class), eq(appName), eq(dataId), eq(group), eq(tenant), + when(jdbcTemplate.update(anyString(), eq(configInfo.getContent()), eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), + eq(betaIps), eq(srcIp), eq(srcUser), eq(appName), eq(dataId), eq(group), eq(tenant), eq(configInfo.getMd5()))).thenReturn(1); - ConfigOperateResult configOperateResult = externalConfigInfoBetaPersistService.insertOrUpdateBetaCas(configInfo, - betaIps, srcIp, srcUser); + ConfigOperateResult configOperateResult = externalConfigInfoBetaPersistService.insertOrUpdateBetaCas(configInfo, betaIps, srcIp, + srcUser); //expect return obj - Assert.assertEquals(mockedConfigInfoStateWrapper.getId(), configOperateResult.getId()); - Assert.assertEquals(mockedConfigInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); + assertEquals(mockedConfigInfoStateWrapper.getId(), configOperateResult.getId()); + assertEquals(mockedConfigInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); //verify cas update to be invoked - Mockito.verify(jdbcTemplate, times(1)).update(anyString(), eq(configInfo.getContent()), - eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), eq(betaIps), eq(srcIp), eq(srcUser), - any(Timestamp.class), eq(appName), eq(dataId), eq(group), eq(tenant), eq(configInfo.getMd5())); + Mockito.verify(jdbcTemplate, times(1)) + .update(anyString(), eq(configInfo.getContent()), eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), eq(betaIps), + eq(srcIp), eq(srcUser), eq(appName), eq(dataId), eq(group), eq(tenant), eq(configInfo.getMd5())); } @Test - public void testInsertOrUpdateBetaCasOfAdd() { + void testInsertOrUpdateBetaCasOfAdd() { String dataId = "betaDataId113"; String group = "group113"; String tenant = "tenant113"; @@ -303,21 +294,20 @@ public void testInsertOrUpdateBetaCasOfAdd() { ConfigInfo configInfo = new ConfigInfo(dataId, group, tenant, appName, content); configInfo.setEncryptedDataKey("key34567"); //execute - ConfigOperateResult configOperateResult = externalConfigInfoBetaPersistService.insertOrUpdateBetaCas(configInfo, - betaIps, srcIp, srcUser); + ConfigOperateResult configOperateResult = externalConfigInfoBetaPersistService.insertOrUpdateBetaCas(configInfo, betaIps, srcIp, + srcUser); //expect return obj - Assert.assertEquals(mockedConfigInfoStateWrapper.getId(), configOperateResult.getId()); - Assert.assertEquals(mockedConfigInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); + assertEquals(mockedConfigInfoStateWrapper.getId(), configOperateResult.getId()); + assertEquals(mockedConfigInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); //verify add to be invoked Mockito.verify(jdbcTemplate, times(1)) - .update(anyString(), eq(dataId), eq(group), eq(tenant), eq(configInfo.getAppName()), - eq(configInfo.getContent()), eq(configInfo.getMd5()), eq(betaIps), eq(srcIp), eq(srcUser), - any(Timestamp.class), any(Timestamp.class), eq(configInfo.getEncryptedDataKey())); + .update(anyString(), eq(dataId), eq(group), eq(tenant), eq(configInfo.getAppName()), eq(configInfo.getContent()), + eq(configInfo.getMd5()), eq(betaIps), eq(srcIp), eq(srcUser), eq(configInfo.getEncryptedDataKey())); } @Test - public void testInsertOrUpdateBetaCasOfException() { + void testInsertOrUpdateBetaCasOfException() { String dataId = "betaDataId113"; String group = "group113"; String tenant = "tenant113"; @@ -340,51 +330,49 @@ public void testInsertOrUpdateBetaCasOfException() { configInfo.setEncryptedDataKey("key34567"); configInfo.setMd5("casMd5"); // mock update throw CannotGetJdbcConnectionException - when(jdbcTemplate.update(anyString(), eq(configInfo.getContent()), - eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), eq(betaIps), eq(srcIp), eq(srcUser), - any(Timestamp.class), eq(appName), eq(dataId), eq(group), eq(tenant), + when(jdbcTemplate.update(anyString(), eq(configInfo.getContent()), eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), + eq(betaIps), eq(srcIp), eq(srcUser), eq(appName), eq(dataId), eq(group), eq(tenant), eq(configInfo.getMd5()))).thenThrow(new CannotGetJdbcConnectionException("mock fail")); //execute of update& expect. try { externalConfigInfoBetaPersistService.insertOrUpdateBetaCas(configInfo, betaIps, srcIp, srcUser); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception exception) { - Assert.assertEquals("mock fail", exception.getMessage()); + assertEquals("mock fail", exception.getMessage()); } //mock query return null when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(null); //mock add throw CannotGetJdbcConnectionException - when(jdbcTemplate.update(anyString(), eq(dataId), eq(group), eq(tenant), eq(configInfo.getAppName()), - eq(configInfo.getContent()), eq(MD5Utils.md5Hex(configInfo.getContent(), Constants.PERSIST_ENCODE)), - eq(betaIps), eq(srcIp), eq(srcUser), any(Timestamp.class), any(Timestamp.class), - eq(configInfo.getEncryptedDataKey()))).thenThrow(new CannotGetJdbcConnectionException("mock fail add")); + when(jdbcTemplate.update(anyString(), eq(dataId), eq(group), eq(tenant), eq(configInfo.getAppName()), eq(configInfo.getContent()), + eq(MD5Utils.md5Hex(configInfo.getContent(), Constants.PERSIST_ENCODE)), eq(betaIps), eq(srcIp), + eq(srcUser), eq(configInfo.getEncryptedDataKey()))).thenThrow( + new CannotGetJdbcConnectionException("mock fail add")); //execute of add& expect. try { externalConfigInfoBetaPersistService.insertOrUpdateBetaCas(configInfo, betaIps, srcIp, srcUser); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception exception) { - Assert.assertEquals("mock fail add", exception.getMessage()); + assertEquals("mock fail add", exception.getMessage()); } //mock query throw CannotGetJdbcConnectionException when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenThrow( - new CannotGetJdbcConnectionException("get c fail")); + eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenThrow(new CannotGetJdbcConnectionException("get c fail")); //execute of add& expect. try { externalConfigInfoBetaPersistService.insertOrUpdateBetaCas(configInfo, betaIps, srcIp, srcUser); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception exception) { - Assert.assertEquals("get c fail", exception.getMessage()); + assertEquals("get c fail", exception.getMessage()); } } @Test - public void testRemoveConfigInfo4Beta() { + void testRemoveConfigInfo4Beta() { String dataId = "dataId456789"; String group = "group4567"; String tenant = "tenant56789o0"; @@ -404,19 +392,18 @@ public void testRemoveConfigInfo4Beta() { //mock query throw CannotGetJdbcConnectionException when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenThrow( - new CannotGetJdbcConnectionException("mock fail11111")); + eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenThrow(new CannotGetJdbcConnectionException("mock fail11111")); try { externalConfigInfoBetaPersistService.removeConfigInfo4Beta(dataId, group, tenant); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception exception) { - Assert.assertEquals("mock fail11111", exception.getMessage()); + assertEquals("mock fail11111", exception.getMessage()); } } @Test - public void testFindConfigInfo4Beta() { + void testFindConfigInfo4Beta() { String dataId = "dataId456789"; String group = "group4567"; String tenant = "tenant56789o0"; @@ -429,38 +416,35 @@ public void testFindConfigInfo4Beta() { mockedConfigInfoStateWrapper.setLastModified(System.currentTimeMillis()); when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_BETA_WRAPPER_ROW_MAPPER))).thenReturn(mockedConfigInfoStateWrapper); - ConfigInfoBetaWrapper configInfo4BetaReturn = externalConfigInfoBetaPersistService.findConfigInfo4Beta(dataId, - group, tenant); - Assert.assertEquals(mockedConfigInfoStateWrapper, configInfo4BetaReturn); + ConfigInfoBetaWrapper configInfo4BetaReturn = externalConfigInfoBetaPersistService.findConfigInfo4Beta(dataId, group, tenant); + assertEquals(mockedConfigInfoStateWrapper, configInfo4BetaReturn); //mock query throw CannotGetJdbcConnectionException when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_BETA_WRAPPER_ROW_MAPPER))).thenThrow( - new CannotGetJdbcConnectionException("mock fail11111")); + eq(CONFIG_INFO_BETA_WRAPPER_ROW_MAPPER))).thenThrow(new CannotGetJdbcConnectionException("mock fail11111")); try { externalConfigInfoBetaPersistService.findConfigInfo4Beta(dataId, group, tenant); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception exception) { - Assert.assertEquals("mock fail11111", exception.getMessage()); + assertEquals("mock fail11111", exception.getMessage()); } //mock query throw EmptyResultDataAccessException when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_BETA_WRAPPER_ROW_MAPPER))).thenThrow(new EmptyResultDataAccessException(1)); - ConfigInfoBetaWrapper configInfo4BetaNull = externalConfigInfoBetaPersistService.findConfigInfo4Beta(dataId, - group, tenant); - Assert.assertNull(configInfo4BetaNull); + ConfigInfoBetaWrapper configInfo4BetaNull = externalConfigInfoBetaPersistService.findConfigInfo4Beta(dataId, group, tenant); + assertNull(configInfo4BetaNull); } @Test - public void testConfigInfoBetaCount() { + void testConfigInfoBetaCount() { when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class))).thenReturn(101); int returnCount = externalConfigInfoBetaPersistService.configInfoBetaCount(); - Assert.assertEquals(101, returnCount); + assertEquals(101, returnCount); } @Test - public void testFindAllConfigInfoBetaForDumpAll() { + void testFindAllConfigInfoBetaForDumpAll() { //mock count when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class))).thenReturn(12345); @@ -473,27 +457,24 @@ public void testFindAllConfigInfoBetaForDumpAll() { mockList.get(1).setLastModified(System.currentTimeMillis()); mockList.get(2).setLastModified(System.currentTimeMillis()); - when(jdbcTemplate.query(anyString(), eq(new Object[] {}), eq(CONFIG_INFO_BETA_WRAPPER_ROW_MAPPER))).thenReturn( - mockList); + when(jdbcTemplate.query(anyString(), eq(new Object[] {}), eq(CONFIG_INFO_BETA_WRAPPER_ROW_MAPPER))).thenReturn(mockList); int pageNo = 1; int pageSize = 101; when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class))).thenReturn(101); //execute & expect - Page pageReturn = externalConfigInfoBetaPersistService.findAllConfigInfoBetaForDumpAll( - pageNo, pageSize); - Assert.assertEquals(mockList, pageReturn.getPageItems()); - Assert.assertEquals(101, pageReturn.getTotalCount()); + Page pageReturn = externalConfigInfoBetaPersistService.findAllConfigInfoBetaForDumpAll(pageNo, pageSize); + assertEquals(mockList, pageReturn.getPageItems()); + assertEquals(101, pageReturn.getTotalCount()); //mock count throw CannotGetJdbcConnectionException - when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class))).thenThrow( - new CannotGetJdbcConnectionException("345678909fail")); + when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class))).thenThrow(new CannotGetJdbcConnectionException("345678909fail")); //execute &expect try { externalConfigInfoBetaPersistService.findAllConfigInfoBetaForDumpAll(pageNo, pageSize); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception exception) { - Assert.assertEquals("345678909fail", exception.getMessage()); + assertEquals("345678909fail", exception.getMessage()); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalConfigInfoPersistServiceImplTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalConfigInfoPersistServiceImplTest.java index 6ea3e887e4f..bab2bc8cf48 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalConfigInfoPersistServiceImplTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalConfigInfoPersistServiceImplTest.java @@ -36,11 +36,10 @@ import com.alibaba.nacos.plugin.datasource.constants.TableConstant; import com.alibaba.nacos.plugin.datasource.mapper.ConfigInfoMapper; import com.alibaba.nacos.sys.env.EnvUtil; -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; @@ -52,7 +51,7 @@ import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.transaction.support.TransactionTemplate; @@ -72,6 +71,10 @@ import static com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.CONFIG_INFO_ROW_MAPPER; import static com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER; import static com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.CONFIG_INFO_WRAPPER_ROW_MAPPER; +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.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; @@ -79,8 +82,17 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; -@RunWith(SpringJUnit4ClassRunner.class) -public class ExternalConfigInfoPersistServiceImplTest { +@ExtendWith(SpringExtension.class) +class ExternalConfigInfoPersistServiceImplTest { + + MockedStatic envUtilMockedStatic; + + MockedStatic externalStorageUtilsMockedStatic; + + MockedStatic dynamicDataSourceMockedStatic; + + @Mock + DynamicDataSource dynamicDataSource; private ExternalConfigInfoPersistServiceImpl externalConfigInfoPersistService; @@ -95,17 +107,8 @@ public class ExternalConfigInfoPersistServiceImplTest { private TransactionTemplate transactionTemplate = TestCaseUtils.createMockTransactionTemplate(); - MockedStatic envUtilMockedStatic; - - MockedStatic externalStorageUtilsMockedStatic; - - MockedStatic dynamicDataSourceMockedStatic; - - @Mock - DynamicDataSource dynamicDataSource; - - @Before - public void before() { + @BeforeEach + void before() { dynamicDataSourceMockedStatic = Mockito.mockStatic(DynamicDataSource.class); envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); externalStorageUtilsMockedStatic = Mockito.mockStatic(ExternalStorageUtils.class); @@ -116,20 +119,19 @@ public void before() { when(dataSourceService.getDataSourceType()).thenReturn("mysql"); /*when(EnvUtil.getProperty(anyString(), eq(Boolean.class), eq(false))).thenReturn(false);*/ - envUtilMockedStatic.when(() -> EnvUtil.getProperty(anyString(), eq(Boolean.class), eq(false))) - .thenReturn(false); + envUtilMockedStatic.when(() -> EnvUtil.getProperty(anyString(), eq(Boolean.class), eq(false))).thenReturn(false); externalConfigInfoPersistService = new ExternalConfigInfoPersistServiceImpl(historyConfigInfoPersistService); } - @After - public void after() { + @AfterEach + void after() { dynamicDataSourceMockedStatic.close(); envUtilMockedStatic.close(); externalStorageUtilsMockedStatic.close(); } @Test - public void testInsertOrUpdateOfInsertConfigSuccess() { + void testInsertOrUpdateOfInsertConfigSuccess() { String dataId = "dataId"; String group = "group"; @@ -147,24 +149,19 @@ public void testInsertOrUpdateOfInsertConfigSuccess() { eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(null, new ConfigInfoStateWrapper()); //mock insert config info Mockito.when(jdbcTemplate.update(any(PreparedStatementCreator.class), eq(generatedKeyHolder))).thenReturn(1); - Mockito.when(jdbcTemplate.update( - eq(externalConfigInfoPersistService.mapperManager.findMapper(dataSourceService.getDataSourceType(), - TableConstant.CONFIG_TAGS_RELATION) - .insert(Arrays.asList("id", "tag_name", "tag_type", "data_id", "group_id", "tenant_id"))), - eq(insertConfigIndoId), eq("tag1"), eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant))) - .thenReturn(1); - Mockito.when(jdbcTemplate.update( - eq(externalConfigInfoPersistService.mapperManager.findMapper(dataSourceService.getDataSourceType(), - TableConstant.CONFIG_TAGS_RELATION) - .insert(Arrays.asList("id", "tag_name", "tag_type", "data_id", "group_id", "tenant_id"))), - eq(insertConfigIndoId), eq("tag2"), eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant))) - .thenReturn(1); + Mockito.when(jdbcTemplate.update(eq(externalConfigInfoPersistService.mapperManager.findMapper(dataSourceService.getDataSourceType(), + TableConstant.CONFIG_TAGS_RELATION) + .insert(Arrays.asList("id", "tag_name", "tag_type", "data_id", "group_id", "tenant_id"))), eq(insertConfigIndoId), + eq("tag1"), eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant))).thenReturn(1); + Mockito.when(jdbcTemplate.update(eq(externalConfigInfoPersistService.mapperManager.findMapper(dataSourceService.getDataSourceType(), + TableConstant.CONFIG_TAGS_RELATION) + .insert(Arrays.asList("id", "tag_name", "tag_type", "data_id", "group_id", "tenant_id"))), eq(insertConfigIndoId), + eq("tag2"), eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant))).thenReturn(1); String srcIp = "srcIp"; String srcUser = "srcUser"; //mock insert config info Mockito.doNothing().when(historyConfigInfoPersistService) - .insertConfigHistoryAtomic(eq(0), eq(configInfo), eq(srcIp), eq(srcUser), any(Timestamp.class), - eq("I")); + .insertConfigHistoryAtomic(eq(0), eq(configInfo), eq(srcIp), eq(srcUser), any(Timestamp.class), eq("I")); externalConfigInfoPersistService.insertOrUpdate(srcIp, srcUser, configInfo, configAdvanceInfo); //expect insert config info @@ -173,23 +170,22 @@ public void testInsertOrUpdateOfInsertConfigSuccess() { Mockito.verify(jdbcTemplate, times(1)).update(eq( externalConfigInfoPersistService.mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_TAGS_RELATION) - .insert(Arrays.asList("id", "tag_name", "tag_type", "data_id", "group_id", "tenant_id"))), - eq(insertConfigIndoId), eq("tag1"), eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant)); + .insert(Arrays.asList("id", "tag_name", "tag_type", "data_id", "group_id", "tenant_id"))), eq(insertConfigIndoId), + eq("tag1"), eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant)); Mockito.verify(jdbcTemplate, times(1)).update(eq( externalConfigInfoPersistService.mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_TAGS_RELATION) - .insert(Arrays.asList("id", "tag_name", "tag_type", "data_id", "group_id", "tenant_id"))), - eq(insertConfigIndoId), eq("tag2"), eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant)); + .insert(Arrays.asList("id", "tag_name", "tag_type", "data_id", "group_id", "tenant_id"))), eq(insertConfigIndoId), + eq("tag2"), eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant)); //expect insert history info Mockito.verify(historyConfigInfoPersistService, times(1)) - .insertConfigHistoryAtomic(eq(0L), eq(configInfo), eq(srcIp), eq(srcUser), any(Timestamp.class), - eq("I")); + .insertConfigHistoryAtomic(eq(0L), eq(configInfo), eq(srcIp), eq(srcUser), any(Timestamp.class), eq("I")); } @Test - public void testInsertOrUpdateCasOfInsertConfigSuccess() { + void testInsertOrUpdateCasOfInsertConfigSuccess() { Map configAdvanceInfo = new HashMap<>(); configAdvanceInfo.put("config_tags", "tag1,tag2"); @@ -207,24 +203,19 @@ public void testInsertOrUpdateCasOfInsertConfigSuccess() { eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(null, new ConfigInfoStateWrapper()); //mock insert config info Mockito.when(jdbcTemplate.update(any(PreparedStatementCreator.class), eq(generatedKeyHolder))).thenReturn(1); - Mockito.when(jdbcTemplate.update( - eq(externalConfigInfoPersistService.mapperManager.findMapper(dataSourceService.getDataSourceType(), - TableConstant.CONFIG_TAGS_RELATION) - .insert(Arrays.asList("id", "tag_name", "tag_type", "data_id", "group_id", "tenant_id"))), - eq(insertConfigIndoId), eq("tag1"), eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant))) - .thenReturn(1); - Mockito.when(jdbcTemplate.update( - eq(externalConfigInfoPersistService.mapperManager.findMapper(dataSourceService.getDataSourceType(), - TableConstant.CONFIG_TAGS_RELATION) - .insert(Arrays.asList("id", "tag_name", "tag_type", "data_id", "group_id", "tenant_id"))), - eq(insertConfigIndoId), eq("tag2"), eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant))) - .thenReturn(1); + Mockito.when(jdbcTemplate.update(eq(externalConfigInfoPersistService.mapperManager.findMapper(dataSourceService.getDataSourceType(), + TableConstant.CONFIG_TAGS_RELATION) + .insert(Arrays.asList("id", "tag_name", "tag_type", "data_id", "group_id", "tenant_id"))), eq(insertConfigIndoId), + eq("tag1"), eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant))).thenReturn(1); + Mockito.when(jdbcTemplate.update(eq(externalConfigInfoPersistService.mapperManager.findMapper(dataSourceService.getDataSourceType(), + TableConstant.CONFIG_TAGS_RELATION) + .insert(Arrays.asList("id", "tag_name", "tag_type", "data_id", "group_id", "tenant_id"))), eq(insertConfigIndoId), + eq("tag2"), eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant))).thenReturn(1); String srcIp = "srcIp"; String srcUser = "srcUser"; //mock insert config info Mockito.doNothing().when(historyConfigInfoPersistService) - .insertConfigHistoryAtomic(eq(0), eq(configInfo), eq(srcIp), eq(srcUser), any(Timestamp.class), - eq("I")); + .insertConfigHistoryAtomic(eq(0), eq(configInfo), eq(srcIp), eq(srcUser), any(Timestamp.class), eq("I")); externalConfigInfoPersistService.insertOrUpdateCas(srcIp, srcUser, configInfo, configAdvanceInfo); //expect insert config info @@ -233,23 +224,22 @@ public void testInsertOrUpdateCasOfInsertConfigSuccess() { Mockito.verify(jdbcTemplate, times(1)).update(eq( externalConfigInfoPersistService.mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_TAGS_RELATION) - .insert(Arrays.asList("id", "tag_name", "tag_type", "data_id", "group_id", "tenant_id"))), - eq(insertConfigIndoId), eq("tag1"), eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant)); + .insert(Arrays.asList("id", "tag_name", "tag_type", "data_id", "group_id", "tenant_id"))), eq(insertConfigIndoId), + eq("tag1"), eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant)); Mockito.verify(jdbcTemplate, times(1)).update(eq( externalConfigInfoPersistService.mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_TAGS_RELATION) - .insert(Arrays.asList("id", "tag_name", "tag_type", "data_id", "group_id", "tenant_id"))), - eq(insertConfigIndoId), eq("tag2"), eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant)); + .insert(Arrays.asList("id", "tag_name", "tag_type", "data_id", "group_id", "tenant_id"))), eq(insertConfigIndoId), + eq("tag2"), eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant)); //expect insert history info Mockito.verify(historyConfigInfoPersistService, times(1)) - .insertConfigHistoryAtomic(eq(0L), eq(configInfo), eq(srcIp), eq(srcUser), any(Timestamp.class), - eq("I")); + .insertConfigHistoryAtomic(eq(0L), eq(configInfo), eq(srcIp), eq(srcUser), any(Timestamp.class), eq("I")); } @Test - public void testInsertOrUpdateOfException() { + void testInsertOrUpdateOfException() { String dataId = "dataId"; String group = "group"; String tenant = "tenant"; @@ -267,15 +257,15 @@ public void testInsertOrUpdateOfException() { ConfigInfo configInfo = new ConfigInfo(dataId, group, tenant, null, "content"); try { externalConfigInfoPersistService.insertOrUpdate("srcIp", "srcUser", configInfo, configAdvanceInfo); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals(e.getMessage(), "mock fail"); + assertEquals("mock fail", e.getMessage()); } } @Test - public void testInsertOrUpdateOfUpdateConfigSuccess() { + void testInsertOrUpdateOfUpdateConfigSuccess() { Map configAdvanceInfo = new HashMap<>(); configAdvanceInfo.put("config_tags", "tag1,tag2"); @@ -295,8 +285,7 @@ public void testInsertOrUpdateOfUpdateConfigSuccess() { configInfo.setEncryptedDataKey(encryptedDataKey); //mock get config state,first and second is not null Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) - .thenReturn(new ConfigInfoStateWrapper(), new ConfigInfoStateWrapper()); + eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(new ConfigInfoStateWrapper(), new ConfigInfoStateWrapper()); //mock select config info before update ConfigInfoWrapper configInfoWrapperOld = new ConfigInfoWrapper(); @@ -306,34 +295,30 @@ public void testInsertOrUpdateOfUpdateConfigSuccess() { configInfoWrapperOld.setAppName("old_app"); configInfoWrapperOld.setMd5("old_md5"); configInfoWrapperOld.setId(12345678765L); - Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))).thenReturn(configInfoWrapperOld); + Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))) + .thenReturn(configInfoWrapperOld); String srcIp = "srcIp"; String srcUser = "srcUser"; //mock update config info - Mockito.when(jdbcTemplate.update( - eq(externalConfigInfoPersistService.mapperManager.findMapper(dataSourceService.getDataSourceType(), + Mockito.when(jdbcTemplate.update(eq(externalConfigInfoPersistService.mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO) - .update(Arrays.asList("content", "md5", "src_ip", "src_user", "gmt_modified", "app_name", - "c_desc", "c_use", "effect", "type", "c_schema", "encrypted_data_key"), - Arrays.asList("data_id", "group_id", "tenant_id"))), eq(configInfo.getContent()), - eq(configInfo.getMd5()), eq(srcIp), eq(srcUser), any(), eq(configInfoWrapperOld.getAppName()), - eq(configAdvanceInfo.get("desc")), eq(configAdvanceInfo.get("use")), - eq(configAdvanceInfo.get("effect")), eq(configAdvanceInfo.get("type")), - eq(configAdvanceInfo.get("schema")), eq(encryptedDataKey), eq(configInfo.getDataId()), + .update(Arrays.asList("content", "md5", "src_ip", "src_user", "gmt_modified@NOW()", "app_name", "c_desc", "c_use", + "effect", "type", "c_schema", "encrypted_data_key"), Arrays.asList("data_id", "group_id", "tenant_id"))), + eq(configInfo.getContent()), eq(configInfo.getMd5()), eq(srcIp), eq(srcUser), eq(configInfoWrapperOld.getAppName()), + eq(configAdvanceInfo.get("desc")), eq(configAdvanceInfo.get("use")), eq(configAdvanceInfo.get("effect")), + eq(configAdvanceInfo.get("type")), eq(configAdvanceInfo.get("schema")), eq(encryptedDataKey), eq(configInfo.getDataId()), eq(configInfo.getGroup()), eq(tenant))).thenReturn(1); //mock insert config tags. - Mockito.when(jdbcTemplate.update( - eq(externalConfigInfoPersistService.mapperManager.findMapper(dataSourceService.getDataSourceType(), + Mockito.when(jdbcTemplate.update(eq(externalConfigInfoPersistService.mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_TAGS_RELATION) - .insert(Arrays.asList("id", "tag_name", "tag_type", "data_id", "group_id", "tenant_id"))), - eq(12345678765L), anyString(), eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant))).thenReturn(1); + .insert(Arrays.asList("id", "tag_name", "tag_type", "data_id", "group_id", "tenant_id"))), eq(12345678765L), anyString(), + eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant))).thenReturn(1); //mock insert his config info Mockito.doNothing().when(historyConfigInfoPersistService) - .insertConfigHistoryAtomic(eq(configInfoWrapperOld.getId()), eq(configInfo), eq(srcIp), eq(srcUser), - any(Timestamp.class), eq("I")); + .insertConfigHistoryAtomic(eq(configInfoWrapperOld.getId()), eq(configInfo), eq(srcIp), eq(srcUser), any(Timestamp.class), + eq("I")); externalConfigInfoPersistService.insertOrUpdate(srcIp, srcUser, configInfo, configAdvanceInfo); @@ -351,14 +336,13 @@ public void testInsertOrUpdateOfUpdateConfigSuccess() { //expect insert history info Mockito.verify(historyConfigInfoPersistService, times(1)) - .insertConfigHistoryAtomic(eq(configInfoWrapperOld.getId()), any(ConfigInfo.class), eq(srcIp), - eq(srcUser), any(Timestamp.class), eq("U")); + .insertConfigHistoryAtomic(eq(configInfoWrapperOld.getId()), any(ConfigInfo.class), eq(srcIp), eq(srcUser), + any(Timestamp.class), eq("U")); } @Test - public void testInsertOrUpdateCasOfUpdateConfigSuccess() { - + void testInsertOrUpdateCasOfUpdateConfigSuccess() { Map configAdvanceInfo = new HashMap<>(); configAdvanceInfo.put("config_tags", "tag1,tag2"); configAdvanceInfo.put("desc", "desc11"); @@ -378,8 +362,7 @@ public void testInsertOrUpdateCasOfUpdateConfigSuccess() { //mock get config state,first and second is not null Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) - .thenReturn(new ConfigInfoStateWrapper(), new ConfigInfoStateWrapper()); + eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(new ConfigInfoStateWrapper(), new ConfigInfoStateWrapper()); //mock select config info before update ConfigInfoWrapper configInfoWrapperOld = new ConfigInfoWrapper(); @@ -389,41 +372,34 @@ public void testInsertOrUpdateCasOfUpdateConfigSuccess() { configInfoWrapperOld.setAppName("old_app11"); configInfoWrapperOld.setMd5("old_md5"); configInfoWrapperOld.setId(123456799L); - Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))).thenReturn(configInfoWrapperOld); + Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[]{dataId, group, tenant}), eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))) + .thenReturn(configInfoWrapperOld); String srcIp = "srcIp"; String srcUser = "srcUser"; //mock update config info cas - Mockito.when( - jdbcTemplate.update(anyString(), eq(content), eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), - eq(srcIp), eq(srcUser), any(Timestamp.class), eq(configInfoWrapperOld.getAppName()), - eq(configAdvanceInfo.get("desc")), eq(configAdvanceInfo.get("use")), - eq(configAdvanceInfo.get("effect")), eq(configAdvanceInfo.get("type")), - eq(configAdvanceInfo.get("schema")), eq(encryptedDataKey), eq(dataId), eq(group), eq(tenant), - eq(casMd5))).thenReturn(1); - + Mockito.when(jdbcTemplate.update(anyString(), eq(content), eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), + eq(srcIp), eq(srcUser), eq(configInfoWrapperOld.getAppName()), eq(configAdvanceInfo.get("desc")), + eq(configAdvanceInfo.get("use")), eq(configAdvanceInfo.get("effect")), eq(configAdvanceInfo.get("type")), + eq(configAdvanceInfo.get("schema")), eq(encryptedDataKey), eq(dataId), eq(group), eq(tenant), eq(casMd5))).thenReturn(1); + //mock insert config tags. - Mockito.when(jdbcTemplate.update( - eq(externalConfigInfoPersistService.mapperManager.findMapper(dataSourceService.getDataSourceType(), + Mockito.when(jdbcTemplate.update(eq(externalConfigInfoPersistService.mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_TAGS_RELATION) - .insert(Arrays.asList("id", "tag_name", "tag_type", "data_id", "group_id", "tenant_id"))), - eq(configInfoWrapperOld.getId()), anyString(), eq(StringUtils.EMPTY), eq(dataId), eq(group), - eq(tenant))).thenReturn(1); - + .insert(Arrays.asList("id", "tag_name", "tag_type", "data_id", "group_id", "tenant_id"))), eq(configInfoWrapperOld.getId()), + anyString(), eq(StringUtils.EMPTY), eq(dataId), eq(group), eq(tenant))).thenReturn(1); + //mock insert his config info Mockito.doNothing().when(historyConfigInfoPersistService) - .insertConfigHistoryAtomic(eq(configInfoWrapperOld.getId()), eq(configInfo), eq(srcIp), eq(srcUser), - any(Timestamp.class), eq("I")); + .insertConfigHistoryAtomic(eq(configInfoWrapperOld.getId()), eq(configInfo), eq(srcIp), eq(srcUser), any(Timestamp.class), + eq("I")); externalConfigInfoPersistService.insertOrUpdateCas(srcIp, srcUser, configInfo, configAdvanceInfo); //expect update config cas Mockito.verify(jdbcTemplate, times(1)) .update(anyString(), eq(content), eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), eq(srcIp), - eq(srcUser), any(Timestamp.class), eq(configInfoWrapperOld.getAppName()), - eq(configAdvanceInfo.get("desc")), eq(configAdvanceInfo.get("use")), - eq(configAdvanceInfo.get("effect")), eq(configAdvanceInfo.get("type")), - eq(configAdvanceInfo.get("schema")), eq(encryptedDataKey), eq(dataId), eq(group), eq(tenant), - eq(casMd5)); + eq(srcUser), eq(configInfoWrapperOld.getAppName()), eq(configAdvanceInfo.get("desc")), + eq(configAdvanceInfo.get("use")), eq(configAdvanceInfo.get("effect")), eq(configAdvanceInfo.get("type")), + eq(configAdvanceInfo.get("schema")), eq(encryptedDataKey), eq(dataId), eq(group), eq(tenant), eq(casMd5)); //expect update config tags Mockito.verify(jdbcTemplate, times(1)).update(eq( @@ -439,13 +415,13 @@ public void testInsertOrUpdateCasOfUpdateConfigSuccess() { //expect insert history info Mockito.verify(historyConfigInfoPersistService, times(1)) - .insertConfigHistoryAtomic(eq(configInfoWrapperOld.getId()), any(ConfigInfo.class), eq(srcIp), - eq(srcUser), any(Timestamp.class), eq("U")); + .insertConfigHistoryAtomic(eq(configInfoWrapperOld.getId()), any(ConfigInfo.class), eq(srcIp), eq(srcUser), + any(Timestamp.class), eq("U")); } @Test - public void testCreatePsForInsertConfigInfo() throws SQLException { + void testCreatePsForInsertConfigInfo() throws SQLException { Map configAdvanceInfo = new HashMap<>(); configAdvanceInfo.put("config_tags", "tag1,tag2"); @@ -462,21 +438,19 @@ public void testCreatePsForInsertConfigInfo() throws SQLException { Connection mockConnection = Mockito.mock(Connection.class); PreparedStatement preparedStatement = Mockito.mock(PreparedStatement.class); - ConfigInfoMapper configInfoMapper = externalConfigInfoPersistService.mapperManager.findMapper( - dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO); + ConfigInfoMapper configInfoMapper = externalConfigInfoPersistService.mapperManager.findMapper(dataSourceService.getDataSourceType(), + TableConstant.CONFIG_INFO); Mockito.when(mockConnection.prepareStatement(anyString(), any(String[].class))).thenReturn(preparedStatement); String srcIp = "srcIp"; String srcUser = "srcUser"; - externalConfigInfoPersistService.createPsForInsertConfigInfo(srcIp, srcUser, configInfo, configAdvanceInfo, - mockConnection, configInfoMapper); + externalConfigInfoPersistService.createPsForInsertConfigInfo(srcIp, srcUser, configInfo, configAdvanceInfo, mockConnection, + configInfoMapper); Mockito.verify(preparedStatement, times(14)).setString(anyInt(), anyString()); - Mockito.verify(preparedStatement, times(2)).setTimestamp(anyInt(), any(Timestamp.class)); - } @Test - public void testRemoveConfigInfo() { + void testRemoveConfigInfo() { String dataId = "dataId4567"; String group = "group3456789"; String tenant = "tenant4567890"; @@ -491,8 +465,8 @@ public void testRemoveConfigInfo() { configInfoWrapperOld.setMd5("old_md5"); configInfoWrapperOld.setId(12345678765L); configInfoWrapperOld.setEncryptedDataKey("key3456"); - Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))).thenReturn(configInfoWrapperOld); + Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))) + .thenReturn(configInfoWrapperOld); String srcIp = "srcIp1234"; String srcUser = "srcUser"; externalConfigInfoPersistService.removeConfigInfo(dataId, group, tenant, srcIp, srcUser); @@ -503,13 +477,13 @@ public void testRemoveConfigInfo() { Mockito.verify(jdbcTemplate, times(1)).update(anyString(), eq(configInfoWrapperOld.getId())); //expect insert delete history Mockito.verify(historyConfigInfoPersistService, times(1)) - .insertConfigHistoryAtomic(eq(configInfoWrapperOld.getId()), eq(configInfoWrapperOld), eq(srcIp), - eq(srcUser), any(), eq("D")); + .insertConfigHistoryAtomic(eq(configInfoWrapperOld.getId()), eq(configInfoWrapperOld), eq(srcIp), eq(srcUser), any(), + eq("D")); } @Test - public void testRemoveConfigInfoByIds() { + void testRemoveConfigInfoByIds() { //mock exist config info List configInfos = new ArrayList<>(); @@ -518,8 +492,7 @@ public void testRemoveConfigInfoByIds() { List deleteIds = Arrays.asList(12344L, 3456789L); configInfos.get(0).setId(12344L); configInfos.get(1).setId(3456789L); - Mockito.when(jdbcTemplate.query(anyString(), eq(deleteIds.toArray()), eq(CONFIG_INFO_ROW_MAPPER))) - .thenReturn(configInfos); + Mockito.when(jdbcTemplate.query(anyString(), eq(deleteIds.toArray()), eq(CONFIG_INFO_ROW_MAPPER))).thenReturn(configInfos); String srcIp = "srcIp1234"; String srcUser = "srcUser"; externalConfigInfoPersistService.removeConfigInfoByIds(deleteIds, srcIp, srcUser); @@ -531,16 +504,14 @@ public void testRemoveConfigInfoByIds() { Mockito.verify(jdbcTemplate, times(1)).update(anyString(), eq(deleteIds.get(1))); //expect insert delete history Mockito.verify(historyConfigInfoPersistService, times(1)) - .insertConfigHistoryAtomic(eq(configInfos.get(0).getId()), eq(configInfos.get(0)), eq(srcIp), - eq(srcUser), any(), eq("D")); + .insertConfigHistoryAtomic(eq(configInfos.get(0).getId()), eq(configInfos.get(0)), eq(srcIp), eq(srcUser), any(), eq("D")); Mockito.verify(historyConfigInfoPersistService, times(1)) - .insertConfigHistoryAtomic(eq(configInfos.get(1).getId()), eq(configInfos.get(1)), eq(srcIp), - eq(srcUser), any(), eq("D")); + .insertConfigHistoryAtomic(eq(configInfos.get(1).getId()), eq(configInfos.get(1)), eq(srcIp), eq(srcUser), any(), eq("D")); } @Test - public void testBatchInsertOrUpdateOverwrite() throws NacosException { + void testBatchInsertOrUpdateOverwrite() throws NacosException { List configInfoList = new ArrayList<>(); //insert direct configInfoList.add(createMockConfigAllInfo(0)); @@ -556,17 +527,17 @@ public void testBatchInsertOrUpdateOverwrite() throws NacosException { ReflectionTestUtils.setField(externalConfigInfoPersistService, "tjt", transactionTemplateCurrent); //mock add config 1 success,config 2 fail and update success,config 3 success Mockito.when(transactionTemplateCurrent.execute(any())) - .thenReturn(new ConfigOperateResult(true), new ConfigOperateResult(false), - new ConfigOperateResult(true), new ConfigOperateResult(true)); + .thenReturn(new ConfigOperateResult(true), new ConfigOperateResult(false), new ConfigOperateResult(true), + new ConfigOperateResult(true)); - Map stringObjectMap = externalConfigInfoPersistService.batchInsertOrUpdate(configInfoList, - srcUser, srcIp, configAdvanceInfo, SameConfigPolicy.OVERWRITE); - Assert.assertEquals(3, stringObjectMap.get("succCount")); - Assert.assertEquals(0, stringObjectMap.get("skipCount")); + Map stringObjectMap = externalConfigInfoPersistService.batchInsertOrUpdate(configInfoList, srcUser, srcIp, + configAdvanceInfo, SameConfigPolicy.OVERWRITE); + assertEquals(3, stringObjectMap.get("succCount")); + assertEquals(0, stringObjectMap.get("skipCount")); } @Test - public void testBatchInsertOrUpdateSkip() throws NacosException { + void testBatchInsertOrUpdateSkip() throws NacosException { List configInfoList = new ArrayList<>(); //insert direct configInfoList.add(createMockConfigAllInfo(0)); @@ -582,19 +553,17 @@ public void testBatchInsertOrUpdateSkip() throws NacosException { ReflectionTestUtils.setField(externalConfigInfoPersistService, "tjt", transactionTemplateCurrent); //mock add config 1 success,config 2 fail and skip,config 3 success Mockito.when(transactionTemplateCurrent.execute(any())) - .thenReturn(new ConfigOperateResult(true), new ConfigOperateResult(false), - new ConfigOperateResult(true)); + .thenReturn(new ConfigOperateResult(true), new ConfigOperateResult(false), new ConfigOperateResult(true)); - Map stringObjectMap = externalConfigInfoPersistService.batchInsertOrUpdate(configInfoList, - srcUser, srcIp, configAdvanceInfo, SameConfigPolicy.SKIP); - Assert.assertEquals(2, stringObjectMap.get("succCount")); - Assert.assertEquals(1, stringObjectMap.get("skipCount")); - Assert.assertEquals(configInfoList.get(1).getDataId(), - ((List>) stringObjectMap.get("skipData")).get(0).get("dataId")); + Map stringObjectMap = externalConfigInfoPersistService.batchInsertOrUpdate(configInfoList, srcUser, srcIp, + configAdvanceInfo, SameConfigPolicy.SKIP); + assertEquals(2, stringObjectMap.get("succCount")); + assertEquals(1, stringObjectMap.get("skipCount")); + assertEquals(configInfoList.get(1).getDataId(), ((List>) stringObjectMap.get("skipData")).get(0).get("dataId")); } @Test - public void testBatchInsertOrUpdateAbort() throws NacosException { + void testBatchInsertOrUpdateAbort() throws NacosException { List configInfoList = new ArrayList<>(); //insert direct configInfoList.add(createMockConfigAllInfo(0)); @@ -609,19 +578,16 @@ public void testBatchInsertOrUpdateAbort() throws NacosException { TransactionTemplate transactionTemplateCurrent = Mockito.mock(TransactionTemplate.class); ReflectionTestUtils.setField(externalConfigInfoPersistService, "tjt", transactionTemplateCurrent); //mock add config 1 success,config 2 fail and abort,config 3 not operated - Mockito.when(transactionTemplateCurrent.execute(any())) - .thenReturn(new ConfigOperateResult(true), new ConfigOperateResult(false)); + Mockito.when(transactionTemplateCurrent.execute(any())).thenReturn(new ConfigOperateResult(true), new ConfigOperateResult(false)); - Map stringObjectMap = externalConfigInfoPersistService.batchInsertOrUpdate(configInfoList, - srcUser, srcIp, configAdvanceInfo, SameConfigPolicy.ABORT); - Assert.assertEquals(1, stringObjectMap.get("succCount")); - Assert.assertEquals(1, stringObjectMap.get("skipCount")); + Map stringObjectMap = externalConfigInfoPersistService.batchInsertOrUpdate(configInfoList, srcUser, srcIp, + configAdvanceInfo, SameConfigPolicy.ABORT); + assertEquals(1, stringObjectMap.get("succCount")); + assertEquals(1, stringObjectMap.get("skipCount")); // config 2 failed - Assert.assertEquals(configInfoList.get(1).getDataId(), - ((List>) stringObjectMap.get("failData")).get(0).get("dataId")); + assertEquals(configInfoList.get(1).getDataId(), ((List>) stringObjectMap.get("failData")).get(0).get("dataId")); //skip config 3 - Assert.assertEquals(configInfoList.get(2).getDataId(), - ((List>) stringObjectMap.get("skipData")).get(0).get("dataId")); + assertEquals(configInfoList.get(2).getDataId(), ((List>) stringObjectMap.get("skipData")).get(0).get("dataId")); } private ConfigAllInfo createMockConfigAllInfo(long mockId) { @@ -660,45 +626,44 @@ private ConfigInfo createMockConfigInfo(long mockId) { } @Test - public void testFindConfigMaxId() { + void testFindConfigMaxId() { Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(Long.class))).thenReturn(123456L); long configMaxId = externalConfigInfoPersistService.findConfigMaxId(); - Assert.assertEquals(123456L, configMaxId); + assertEquals(123456L, configMaxId); } @Test - public void testFindConfigMaxId0() { + void testFindConfigMaxId0() { Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(Long.class))).thenThrow(new NullPointerException()); long configMaxId = externalConfigInfoPersistService.findConfigMaxId(); - Assert.assertEquals(0, configMaxId); + assertEquals(0, configMaxId); } @Test - public void testFindConfigInfoById() { + void testFindConfigInfoById() { long id = 1234567890876L; ConfigInfo configInfo = new ConfigInfo(); configInfo.setId(id); - Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {id}), eq(CONFIG_INFO_ROW_MAPPER))) - .thenReturn(configInfo); + Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {id}), eq(CONFIG_INFO_ROW_MAPPER))).thenReturn(configInfo); ConfigInfo configReturn = externalConfigInfoPersistService.findConfigInfo(id); - Assert.assertEquals(id, configReturn.getId()); + assertEquals(id, configReturn.getId()); } @Test - public void testFindConfigInfoByIdNull() { + void testFindConfigInfoByIdNull() { long id = 1234567890876L; ConfigInfo configInfo = new ConfigInfo(); configInfo.setId(id); Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {id}), eq(CONFIG_INFO_ROW_MAPPER))) .thenThrow(new EmptyResultDataAccessException(1)); ConfigInfo configReturn = externalConfigInfoPersistService.findConfigInfo(id); - Assert.assertEquals(null, configReturn); + assertNull(configReturn); } @Test - public void testFindConfigInfoByIdGetConFail() { + void testFindConfigInfoByIdGetConFail() { long id = 1234567890876L; ConfigInfo configInfo = new ConfigInfo(); configInfo.setId(id); @@ -706,14 +671,14 @@ public void testFindConfigInfoByIdGetConFail() { .thenThrow(new CannotGetJdbcConnectionException("mocked exp")); try { ConfigInfo configReturn = externalConfigInfoPersistService.findConfigInfo(id); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertTrue(e instanceof CannotGetJdbcConnectionException); + assertTrue(e instanceof CannotGetJdbcConnectionException); } } @Test - public void testFindConfigInfoByDataId() { + void testFindConfigInfoByDataId() { String dataId = "dataId4567"; String group = "group3456789"; String tenant = "tenant4567890"; @@ -722,65 +687,64 @@ public void testFindConfigInfoByDataId() { configInfoWrapper.setGroup(group); configInfoWrapper.setTenant(tenant); - Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))).thenReturn(configInfoWrapper); + Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))) + .thenReturn(configInfoWrapper); ConfigInfo configReturn = externalConfigInfoPersistService.findConfigInfo(dataId, group, tenant); - Assert.assertEquals(dataId, configReturn.getDataId()); + assertEquals(dataId, configReturn.getDataId()); } @Test - public void testFindConfigInfoByDataIdNull() { + void testFindConfigInfoByDataIdNull() { String dataId = "dataId4567"; String group = "group3456789"; String tenant = "tenant4567890"; - Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))).thenThrow(new EmptyResultDataAccessException(1)); + Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))) + .thenThrow(new EmptyResultDataAccessException(1)); ConfigInfoWrapper configReturn = externalConfigInfoPersistService.findConfigInfo(dataId, group, tenant); - Assert.assertEquals(null, configReturn); + assertNull(configReturn); } @Test - public void testFindConfigInfoByDataIdGetConFail() { + void testFindConfigInfoByDataIdGetConFail() { String dataId = "dataId4567222"; String group = "group3456789"; String tenant = "tenant4567890"; - Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))).thenThrow(new CannotGetJdbcConnectionException("mocked exp")); + Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))) + .thenThrow(new CannotGetJdbcConnectionException("mocked exp")); try { externalConfigInfoPersistService.findConfigInfo(dataId, group, tenant); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertTrue(e instanceof CannotGetJdbcConnectionException); + assertTrue(e instanceof CannotGetJdbcConnectionException); } } @Test - public void testFindConfigInfo4Page() { + void testFindConfigInfo4Page() { String dataId = "dataId4567222"; String group = "group3456789"; String tenant = "tenant4567890"; //mock total count - when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {tenant, dataId, group}), - eq(Integer.class))).thenReturn(new Integer(9)); + when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {tenant, dataId, group}), eq(Integer.class))).thenReturn( + new Integer(9)); //mock page list List result = new ArrayList<>(); result.add(createMockConfigInfo(0)); result.add(createMockConfigInfo(1)); result.add(createMockConfigInfo(2)); - when(jdbcTemplate.query(anyString(), eq(new Object[] {tenant, dataId, group}), - eq(CONFIG_INFO_ROW_MAPPER))).thenReturn(result); + when(jdbcTemplate.query(anyString(), eq(new Object[] {tenant, dataId, group}), eq(CONFIG_INFO_ROW_MAPPER))).thenReturn(result); Map configAdvanceInfo = new HashMap<>(); - Page configInfo4Page = externalConfigInfoPersistService.findConfigInfo4Page(1, 3, dataId, group, - tenant, configAdvanceInfo); - Assert.assertEquals(result.size(), configInfo4Page.getPageItems().size()); - Assert.assertEquals(9, configInfo4Page.getTotalCount()); + Page configInfo4Page = externalConfigInfoPersistService.findConfigInfo4Page(1, 3, dataId, group, tenant, + configAdvanceInfo); + assertEquals(result.size(), configInfo4Page.getPageItems().size()); + assertEquals(9, configInfo4Page.getTotalCount()); } @Test - public void testFindConfigInfo4PageWithTags() { + void testFindConfigInfo4PageWithTags() { String dataId = "dataId4567222"; String group = "group3456789"; String tenant = "tenant4567890"; @@ -798,52 +762,51 @@ public void testFindConfigInfo4PageWithTags() { when(jdbcTemplate.query(anyString(), eq(new Object[] {tenant, dataId, group, "tags1", "tags3"}), eq(CONFIG_INFO_ROW_MAPPER))).thenReturn(result); - Page configInfo4Page = externalConfigInfoPersistService.findConfigInfo4Page(1, 3, dataId, group, - tenant, configAdvanceInfo); - Assert.assertEquals(result.size(), configInfo4Page.getPageItems().size()); - Assert.assertEquals(9, configInfo4Page.getTotalCount()); + Page configInfo4Page = externalConfigInfoPersistService.findConfigInfo4Page(1, 3, dataId, group, tenant, + configAdvanceInfo); + assertEquals(result.size(), configInfo4Page.getPageItems().size()); + assertEquals(9, configInfo4Page.getTotalCount()); } @Test - public void testConfigInfoCount() { + void testConfigInfoCount() { //mock total count when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class))).thenReturn(new Integer(9)); int count = externalConfigInfoPersistService.configInfoCount(); - Assert.assertEquals(9, count); + assertEquals(9, count); when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class))).thenReturn(null); try { externalConfigInfoPersistService.configInfoCount(); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertTrue(e instanceof IllegalArgumentException); + assertTrue(e instanceof IllegalArgumentException); } } @Test - public void testConfigInfoCountByTenant() { + void testConfigInfoCountByTenant() { String tenant = "tenant124"; //mock total count - when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {tenant}), eq(Integer.class))).thenReturn( - new Integer(90)); + when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {tenant}), eq(Integer.class))).thenReturn(new Integer(90)); int count = externalConfigInfoPersistService.configInfoCount(tenant); - Assert.assertEquals(90, count); + assertEquals(90, count); when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {tenant}), eq(Integer.class))).thenReturn(null); try { externalConfigInfoPersistService.configInfoCount(tenant); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertTrue(e instanceof IllegalArgumentException); + assertTrue(e instanceof IllegalArgumentException); } } @Test - public void testFindConfigInfoLike4Page() { + void testFindConfigInfoLike4Page() { String dataId = "dataId4567222*"; String group = "group3456789*"; String tenant = "tenant4567890"; @@ -854,26 +817,26 @@ public void testFindConfigInfoLike4Page() { configAdvanceInfo.put("content", content); //mock total count when(jdbcTemplate.queryForObject(anyString(), - eq(new Object[] {tenant, dataId.replaceAll("\\*", "%"), group.replaceAll("\\*", "%"), appName, - content}), eq(Integer.class))).thenReturn(new Integer(9)); + eq(new Object[] {tenant, dataId.replaceAll("\\*", "%"), group.replaceAll("\\*", "%"), appName, content}), + eq(Integer.class))).thenReturn(new Integer(9)); //mock page list List result = new ArrayList<>(); result.add(createMockConfigInfo(0)); result.add(createMockConfigInfo(1)); result.add(createMockConfigInfo(2)); when(jdbcTemplate.query(anyString(), - eq(new Object[] {tenant, dataId.replaceAll("\\*", "%"), group.replaceAll("\\*", "%"), appName, - content}), eq(CONFIG_INFO_ROW_MAPPER))).thenReturn(result); + eq(new Object[] {tenant, dataId.replaceAll("\\*", "%"), group.replaceAll("\\*", "%"), appName, content}), + eq(CONFIG_INFO_ROW_MAPPER))).thenReturn(result); - Page configInfo4Page = externalConfigInfoPersistService.findConfigInfoLike4Page(1, 3, dataId, group, - tenant, configAdvanceInfo); - Assert.assertEquals(result.size(), configInfo4Page.getPageItems().size()); - Assert.assertEquals(9, configInfo4Page.getTotalCount()); + Page configInfo4Page = externalConfigInfoPersistService.findConfigInfoLike4Page(1, 3, dataId, group, tenant, + configAdvanceInfo); + assertEquals(result.size(), configInfo4Page.getPageItems().size()); + assertEquals(9, configInfo4Page.getTotalCount()); } @Test - public void testFindConfigInfoLike4PageWithTags() { + void testFindConfigInfoLike4PageWithTags() { String appName = "appName1234"; String content = "content123"; @@ -886,26 +849,26 @@ public void testFindConfigInfoLike4PageWithTags() { String tenant = "tenant4567890"; //mock total count when(jdbcTemplate.queryForObject(anyString(), - eq(new Object[] {tenant, dataId.replaceAll("\\*", "%"), group.replaceAll("\\*", "%"), appName, content, - "tags", "tag2"}), eq(Integer.class))).thenReturn(new Integer(9)); + eq(new Object[] {tenant, dataId.replaceAll("\\*", "%"), group.replaceAll("\\*", "%"), appName, content, "tags", "tag2"}), + eq(Integer.class))).thenReturn(new Integer(9)); //mock page list List result = new ArrayList<>(); result.add(createMockConfigInfo(0)); result.add(createMockConfigInfo(1)); result.add(createMockConfigInfo(2)); when(jdbcTemplate.query(anyString(), - eq(new Object[] {tenant, dataId.replaceAll("\\*", "%"), group.replaceAll("\\*", "%"), appName, content, - "tags", "tag2"}), eq(CONFIG_INFO_ROW_MAPPER))).thenReturn(result); + eq(new Object[] {tenant, dataId.replaceAll("\\*", "%"), group.replaceAll("\\*", "%"), appName, content, "tags", "tag2"}), + eq(CONFIG_INFO_ROW_MAPPER))).thenReturn(result); - Page configInfo4Page = externalConfigInfoPersistService.findConfigInfoLike4Page(1, 3, dataId, group, - tenant, configAdvanceInfo); - Assert.assertEquals(result.size(), configInfo4Page.getPageItems().size()); - Assert.assertEquals(9, configInfo4Page.getTotalCount()); + Page configInfo4Page = externalConfigInfoPersistService.findConfigInfoLike4Page(1, 3, dataId, group, tenant, + configAdvanceInfo); + assertEquals(result.size(), configInfo4Page.getPageItems().size()); + assertEquals(9, configInfo4Page.getTotalCount()); } @Test - public void testFindChangeConfig() { + void testFindChangeConfig() { //mock page list List result = new ArrayList<>(); @@ -918,13 +881,12 @@ public void testFindChangeConfig() { when(jdbcTemplate.query(anyString(), eq(new Object[] {startTime, lastMaxId, pageSize}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(result); - List configInfo4List = externalConfigInfoPersistService.findChangeConfig(startTime, - lastMaxId, pageSize); - Assert.assertEquals(result.size(), configInfo4List.size()); + List configInfo4List = externalConfigInfoPersistService.findChangeConfig(startTime, lastMaxId, pageSize); + assertEquals(result.size(), configInfo4List.size()); } @Test - public void testFindChangeConfigError() { + void testFindChangeConfigError() { Timestamp startTime = new Timestamp(System.currentTimeMillis() - 1000L); long lastMaxId = 10000L; int pageSize = 30; @@ -932,95 +894,92 @@ public void testFindChangeConfigError() { when(jdbcTemplate.query(anyString(), eq(new Object[] {startTime, lastMaxId, pageSize}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenThrow(new CannotAcquireLockException("mock ex")); try { - List configInfo4List = externalConfigInfoPersistService.findChangeConfig(startTime, - lastMaxId, pageSize); - Assert.assertTrue(false); + List configInfo4List = externalConfigInfoPersistService.findChangeConfig(startTime, lastMaxId, + pageSize); + assertTrue(false); } catch (Exception e) { - Assert.assertTrue(e instanceof CannotAcquireLockException); + assertTrue(e instanceof CannotAcquireLockException); } } @Test - public void testSelectTagByConfig() { + void testSelectTagByConfig() { String dataId = "dataId4567222"; String group = "group3456789"; String tenant = "tenant4567890"; //mock page list List tagStrings = Arrays.asList("", "", ""); - when(jdbcTemplate.queryForList(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(String.class))).thenReturn(tagStrings); + when(jdbcTemplate.queryForList(anyString(), eq(new Object[] {dataId, group, tenant}), eq(String.class))).thenReturn(tagStrings); List configTags = externalConfigInfoPersistService.selectTagByConfig(dataId, group, tenant); - Assert.assertEquals(tagStrings, configTags); + assertEquals(tagStrings, configTags); //mock EmptyResultDataAccessException - when(jdbcTemplate.queryForList(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(String.class))).thenThrow(new EmptyResultDataAccessException(3)); + when(jdbcTemplate.queryForList(anyString(), eq(new Object[] {dataId, group, tenant}), eq(String.class))).thenThrow( + new EmptyResultDataAccessException(3)); List nullResult = externalConfigInfoPersistService.selectTagByConfig(dataId, group, tenant); - Assert.assertTrue(nullResult == null); + assertTrue(nullResult == null); //mock IncorrectResultSizeDataAccessException - when(jdbcTemplate.queryForList(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(String.class))).thenThrow(new IncorrectResultSizeDataAccessException(3)); + when(jdbcTemplate.queryForList(anyString(), eq(new Object[] {dataId, group, tenant}), eq(String.class))).thenThrow( + new IncorrectResultSizeDataAccessException(3)); List nullResult2 = externalConfigInfoPersistService.selectTagByConfig(dataId, group, tenant); - Assert.assertTrue(nullResult2 == null); + assertTrue(nullResult2 == null); //mock IncorrectResultSizeDataAccessException - when(jdbcTemplate.queryForList(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(String.class))).thenThrow(new CannotGetJdbcConnectionException("mock exp")); + when(jdbcTemplate.queryForList(anyString(), eq(new Object[] {dataId, group, tenant}), eq(String.class))).thenThrow( + new CannotGetJdbcConnectionException("mock exp")); try { externalConfigInfoPersistService.selectTagByConfig(dataId, group, tenant); - Assert.assertFalse(true); + assertFalse(true); } catch (Exception e) { - Assert.assertTrue(e instanceof CannotGetJdbcConnectionException); + assertTrue(e instanceof CannotGetJdbcConnectionException); } } @Test - public void testFindConfigInfosByIds() { + void testFindConfigInfosByIds() { //mock page list List result = new ArrayList<>(); result.add(createMockConfigInfo(0)); result.add(createMockConfigInfo(1)); result.add(createMockConfigInfo(2)); - when(jdbcTemplate.query(anyString(), eq(new Object[] {123L, 1232345L}), eq(CONFIG_INFO_ROW_MAPPER))).thenReturn( - result); + when(jdbcTemplate.query(anyString(), eq(new Object[] {123L, 1232345L}), eq(CONFIG_INFO_ROW_MAPPER))).thenReturn(result); String ids = "123,1232345"; List configInfosByIds = externalConfigInfoPersistService.findConfigInfosByIds(ids); - Assert.assertEquals(result.size(), configInfosByIds.size()); - Assert.assertEquals(result.get(2).getDataId(), configInfosByIds.get(2).getDataId()); + assertEquals(result.size(), configInfosByIds.size()); + assertEquals(result.get(2).getDataId(), configInfosByIds.get(2).getDataId()); //mock EmptyResultDataAccessException when(jdbcTemplate.query(anyString(), eq(new Object[] {123L, 1232345L}), eq(CONFIG_INFO_ROW_MAPPER))).thenThrow( new EmptyResultDataAccessException(3)); List nullResult2 = externalConfigInfoPersistService.findConfigInfosByIds(ids); - Assert.assertTrue(nullResult2 == null); + assertTrue(nullResult2 == null); //blank ids. List nullResultBlankIds = externalConfigInfoPersistService.findConfigInfosByIds(""); - Assert.assertTrue(nullResultBlankIds == null); + assertTrue(nullResultBlankIds == null); //mock CannotGetJdbcConnectionException when(jdbcTemplate.query(anyString(), eq(new Object[] {123L, 1232345L}), eq(CONFIG_INFO_ROW_MAPPER))).thenThrow( new CannotGetJdbcConnectionException("mock exp")); try { externalConfigInfoPersistService.findConfigInfosByIds(ids); - Assert.assertFalse(true); + assertFalse(true); } catch (Exception e) { - Assert.assertTrue(e instanceof CannotGetJdbcConnectionException); + assertTrue(e instanceof CannotGetJdbcConnectionException); } } @Test - public void testFindConfigAdvanceInfo() { + void testFindConfigAdvanceInfo() { String dataId = "dataId1324"; String group = "group23546"; String tenant = "tenant13245"; //mock select tags List mockTags = Arrays.asList("tag1", "tag2", "tag3"); - when(jdbcTemplate.queryForList(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(String.class))).thenReturn(mockTags); + when(jdbcTemplate.queryForList(anyString(), eq(new Object[] {dataId, group, tenant}), eq(String.class))).thenReturn(mockTags); String schema = "schema12345654"; //mock select config advance @@ -1030,17 +989,16 @@ public void testFindConfigAdvanceInfo() { eq(CONFIG_ADVANCE_INFO_ROW_MAPPER))).thenReturn(mockedAdvance); //execute return mock obj - ConfigAdvanceInfo configAdvanceInfo = externalConfigInfoPersistService.findConfigAdvanceInfo(dataId, group, - tenant); + ConfigAdvanceInfo configAdvanceInfo = externalConfigInfoPersistService.findConfigAdvanceInfo(dataId, group, tenant); //expect check schema & tags. - Assert.assertEquals(mockedAdvance.getSchema(), configAdvanceInfo.getSchema()); - Assert.assertEquals(String.join(",", mockTags), configAdvanceInfo.getConfigTags()); + assertEquals(mockedAdvance.getSchema(), configAdvanceInfo.getSchema()); + assertEquals(String.join(",", mockTags), configAdvanceInfo.getConfigTags()); //mock EmptyResultDataAccessException when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_ADVANCE_INFO_ROW_MAPPER))).thenThrow(new EmptyResultDataAccessException(1)); //expect return null. - Assert.assertNull(externalConfigInfoPersistService.findConfigAdvanceInfo(dataId, group, tenant)); + assertNull(externalConfigInfoPersistService.findConfigAdvanceInfo(dataId, group, tenant)); //mock CannotGetJdbcConnectionException when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), @@ -1048,58 +1006,57 @@ public void testFindConfigAdvanceInfo() { //expect throw exception. try { externalConfigInfoPersistService.findConfigAdvanceInfo(dataId, group, tenant); - Assert.assertFalse(true); + assertFalse(true); } catch (Exception e) { - Assert.assertTrue(e instanceof CannotGetJdbcConnectionException); - Assert.assertTrue(e.getMessage().endsWith("mock exp")); + assertTrue(e instanceof CannotGetJdbcConnectionException); + assertTrue(e.getMessage().endsWith("mock exp")); } } @Test - public void testFindConfigAllInfo() { + void testFindConfigAllInfo() { String dataId = "dataId1324"; String group = "group23546"; String tenant = "tenant13245"; //mock select tags List mockTags = Arrays.asList("tag1", "tag2", "tag3"); - when(jdbcTemplate.queryForList(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(String.class))).thenReturn(mockTags); + when(jdbcTemplate.queryForList(anyString(), eq(new Object[] {dataId, group, tenant}), eq(String.class))).thenReturn(mockTags); String schema = "schema12345654"; //mock select config advance ConfigAllInfo mockedConfig = new ConfigAllInfo(); mockedConfig.setSchema(schema); - when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_ALL_INFO_ROW_MAPPER))).thenReturn(mockedConfig); + when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_ALL_INFO_ROW_MAPPER))).thenReturn( + mockedConfig); //execute return mock obj ConfigAllInfo configAllInfo = externalConfigInfoPersistService.findConfigAllInfo(dataId, group, tenant); //expect check schema & tags. - Assert.assertEquals(mockedConfig.getSchema(), configAllInfo.getSchema()); - Assert.assertEquals(String.join(",", mockTags), configAllInfo.getConfigTags()); + assertEquals(mockedConfig.getSchema(), configAllInfo.getSchema()); + assertEquals(String.join(",", mockTags), configAllInfo.getConfigTags()); //mock EmptyResultDataAccessException - when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_ALL_INFO_ROW_MAPPER))).thenThrow(new EmptyResultDataAccessException(1)); + when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_ALL_INFO_ROW_MAPPER))).thenThrow( + new EmptyResultDataAccessException(1)); //expect return null. - Assert.assertNull(externalConfigInfoPersistService.findConfigAllInfo(dataId, group, tenant)); + assertNull(externalConfigInfoPersistService.findConfigAllInfo(dataId, group, tenant)); //mock CannotGetJdbcConnectionException - when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), - eq(CONFIG_ALL_INFO_ROW_MAPPER))).thenThrow(new CannotGetJdbcConnectionException("mock exp")); + when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_ALL_INFO_ROW_MAPPER))).thenThrow( + new CannotGetJdbcConnectionException("mock exp")); //expect throw exception. try { externalConfigInfoPersistService.findConfigAllInfo(dataId, group, tenant); - Assert.assertFalse(true); + assertFalse(true); } catch (Exception e) { - Assert.assertTrue(e instanceof CannotGetJdbcConnectionException); - Assert.assertTrue(e.getMessage().endsWith("mock exp")); + assertTrue(e instanceof CannotGetJdbcConnectionException); + assertTrue(e.getMessage().endsWith("mock exp")); } } @Test - public void testFindConfigInfoState() { + void testFindConfigInfoState() { String dataId = "dataId1324"; String group = "group23546"; @@ -1113,17 +1070,16 @@ public void testFindConfigInfoState() { eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(mockedConfig); //execute return mock obj - ConfigInfoStateWrapper configInfoStateWrapper = externalConfigInfoPersistService.findConfigInfoState(dataId, - group, tenant); + ConfigInfoStateWrapper configInfoStateWrapper = externalConfigInfoPersistService.findConfigInfoState(dataId, group, tenant); //expect check schema & tags. - Assert.assertEquals(mockedConfig.getId(), configInfoStateWrapper.getId()); - Assert.assertEquals(mockedConfig.getLastModified(), configInfoStateWrapper.getLastModified()); + assertEquals(mockedConfig.getId(), configInfoStateWrapper.getId()); + assertEquals(mockedConfig.getLastModified(), configInfoStateWrapper.getLastModified()); //mock EmptyResultDataAccessException when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenThrow(new EmptyResultDataAccessException(1)); //expect return null. - Assert.assertNull(externalConfigInfoPersistService.findConfigInfoState(dataId, group, tenant)); + assertNull(externalConfigInfoPersistService.findConfigInfoState(dataId, group, tenant)); //mock CannotGetJdbcConnectionException when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), @@ -1131,15 +1087,15 @@ public void testFindConfigInfoState() { //expect throw exception. try { externalConfigInfoPersistService.findConfigInfoState(dataId, group, tenant); - Assert.assertFalse(true); + assertFalse(true); } catch (Exception e) { - Assert.assertTrue(e instanceof CannotGetJdbcConnectionException); - Assert.assertTrue(e.getMessage().endsWith("mock exp")); + assertTrue(e instanceof CannotGetJdbcConnectionException); + assertTrue(e.getMessage().endsWith("mock exp")); } } @Test - public void testFindAllConfigInfo4Export() { + void testFindAllConfigInfo4Export() { //mock select config state List mockConfigs = new ArrayList<>(); @@ -1153,37 +1109,36 @@ public void testFindAllConfigInfo4Export() { String appName = "appName1243"; List ids = Arrays.asList(132L, 1343L, 245L); - when(jdbcTemplate.query(anyString(), eq(new Object[] {132L, 1343L, 245L}), - eq(CONFIG_ALL_INFO_ROW_MAPPER))).thenReturn(mockConfigs); + when(jdbcTemplate.query(anyString(), eq(new Object[] {132L, 1343L, 245L}), eq(CONFIG_ALL_INFO_ROW_MAPPER))).thenReturn(mockConfigs); //execute return mock obj - List configAllInfosIds = externalConfigInfoPersistService.findAllConfigInfo4Export(dataId, group, - tenant, appName, ids); + List configAllInfosIds = externalConfigInfoPersistService.findAllConfigInfo4Export(dataId, group, tenant, appName, + ids); //expect check - Assert.assertEquals(mockConfigs, configAllInfosIds); + assertEquals(mockConfigs, configAllInfosIds); - when(jdbcTemplate.query(anyString(), eq(new Object[] {tenant, dataId, group, appName}), - eq(CONFIG_ALL_INFO_ROW_MAPPER))).thenReturn(mockConfigs); + when(jdbcTemplate.query(anyString(), eq(new Object[] {tenant, dataId, group, appName}), eq(CONFIG_ALL_INFO_ROW_MAPPER))).thenReturn( + mockConfigs); //execute return mock obj - List configAllInfosWithDataId = externalConfigInfoPersistService.findAllConfigInfo4Export(dataId, - group, tenant, appName, null); + List configAllInfosWithDataId = externalConfigInfoPersistService.findAllConfigInfo4Export(dataId, group, tenant, + appName, null); //expect check - Assert.assertEquals(mockConfigs, configAllInfosWithDataId); + assertEquals(mockConfigs, configAllInfosWithDataId); //mock CannotGetJdbcConnectionException - when(jdbcTemplate.query(anyString(), eq(new Object[] {132L, 1343L, 245L}), - eq(CONFIG_ALL_INFO_ROW_MAPPER))).thenThrow(new CannotGetJdbcConnectionException("mock exp11")); + when(jdbcTemplate.query(anyString(), eq(new Object[] {132L, 1343L, 245L}), eq(CONFIG_ALL_INFO_ROW_MAPPER))).thenThrow( + new CannotGetJdbcConnectionException("mock exp11")); //expect throw exception. try { externalConfigInfoPersistService.findAllConfigInfo4Export(dataId, group, tenant, appName, ids); - Assert.assertFalse(true); + assertFalse(true); } catch (Exception e) { - Assert.assertTrue(e instanceof CannotGetJdbcConnectionException); - Assert.assertTrue(e.getMessage().endsWith("mock exp11")); + assertTrue(e instanceof CannotGetJdbcConnectionException); + assertTrue(e.getMessage().endsWith("mock exp11")); } } @Test - public void testQueryConfigInfoByNamespace() { + void testQueryConfigInfoByNamespace() { //mock select config state List mockConfigs = new ArrayList<>(); @@ -1191,22 +1146,19 @@ public void testQueryConfigInfoByNamespace() { mockConfigs.add(createMockConfigInfoWrapper(1)); mockConfigs.add(createMockConfigInfoWrapper(2)); String tenant = "tenant13245"; - when(jdbcTemplate.query(anyString(), eq(new Object[] {tenant}), eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))).thenReturn( - mockConfigs); + when(jdbcTemplate.query(anyString(), eq(new Object[] {tenant}), eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))).thenReturn(mockConfigs); //execute return mock obj - List configInfoWrappers = externalConfigInfoPersistService.queryConfigInfoByNamespace( - tenant); + List configInfoWrappers = externalConfigInfoPersistService.queryConfigInfoByNamespace(tenant); //expect check - Assert.assertEquals(mockConfigs, configInfoWrappers); + assertEquals(mockConfigs, configInfoWrappers); //mock CannotGetJdbcConnectionException when(jdbcTemplate.query(anyString(), eq(new Object[] {tenant}), eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))).thenThrow( new EmptyResultDataAccessException(2)); //execute return mock obj - List configInfoWrapperNull = externalConfigInfoPersistService.queryConfigInfoByNamespace( - tenant); + List configInfoWrapperNull = externalConfigInfoPersistService.queryConfigInfoByNamespace(tenant); //expect check - Assert.assertEquals(Collections.EMPTY_LIST, configInfoWrapperNull); + assertEquals(Collections.EMPTY_LIST, configInfoWrapperNull); //mock CannotGetJdbcConnectionException when(jdbcTemplate.query(anyString(), eq(new Object[] {tenant}), eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))).thenThrow( @@ -1214,15 +1166,15 @@ public void testQueryConfigInfoByNamespace() { //expect throw exception. try { externalConfigInfoPersistService.queryConfigInfoByNamespace(tenant); - Assert.assertFalse(true); + assertFalse(true); } catch (Exception e) { - Assert.assertTrue(e instanceof CannotGetJdbcConnectionException); - Assert.assertTrue(e.getMessage().endsWith("mock exp1111")); + assertTrue(e instanceof CannotGetJdbcConnectionException); + assertTrue(e.getMessage().endsWith("mock exp1111")); } } @Test - public void testGetTenantIdList() { + void testGetTenantIdList() { int page = 10; int pageSize = 100; @@ -1233,11 +1185,11 @@ public void testGetTenantIdList() { List returnTenants = externalConfigInfoPersistService.getTenantIdList(page, pageSize); //expect check - Assert.assertEquals(tenantStrings, returnTenants); + assertEquals(tenantStrings, returnTenants); } @Test - public void testGetGroupIdList() { + void testGetGroupIdList() { int page = 10; int pageSize = 100; @@ -1248,34 +1200,32 @@ public void testGetGroupIdList() { List returnGroups = externalConfigInfoPersistService.getGroupIdList(page, pageSize); //expect check - Assert.assertEquals(groupStrings, returnGroups); + assertEquals(groupStrings, returnGroups); } @Test - public void testFindAllConfigInfoFragment() { + void testFindAllConfigInfoFragment() { //mock page list List mockConfigs = new ArrayList<>(); mockConfigs.add(createMockConfigInfoWrapper(0)); mockConfigs.add(createMockConfigInfoWrapper(1)); mockConfigs.add(createMockConfigInfoWrapper(2)); long lastId = 10111L; - when(jdbcTemplate.query(anyString(), eq(new Object[] {lastId}), eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))).thenReturn( - mockConfigs); + when(jdbcTemplate.query(anyString(), eq(new Object[] {lastId}), eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))).thenReturn(mockConfigs); int pageSize = 100; //execute return mock obj - Page returnConfigPage = externalConfigInfoPersistService.findAllConfigInfoFragment(lastId, - pageSize, true); + Page returnConfigPage = externalConfigInfoPersistService.findAllConfigInfoFragment(lastId, pageSize, true); //expect check - Assert.assertEquals(mockConfigs, returnConfigPage.getPageItems()); + assertEquals(mockConfigs, returnConfigPage.getPageItems()); when(jdbcTemplate.query(anyString(), eq(new Object[] {lastId}), eq(CONFIG_INFO_WRAPPER_ROW_MAPPER))).thenThrow( new CannotGetJdbcConnectionException("mock fail")); try { externalConfigInfoPersistService.findAllConfigInfoFragment(lastId, pageSize, true); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("mock fail", e.getMessage()); + assertEquals("mock fail", e.getMessage()); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalConfigInfoTagPersistServiceImplTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalConfigInfoTagPersistServiceImplTest.java index 9dd2771f092..e19fc4224e0 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalConfigInfoTagPersistServiceImplTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalConfigInfoTagPersistServiceImplTest.java @@ -28,18 +28,17 @@ import com.alibaba.nacos.persistence.datasource.DynamicDataSource; import com.alibaba.nacos.persistence.model.Page; import com.alibaba.nacos.sys.env.EnvUtil; -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.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.CannotGetJdbcConnectionException; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.transaction.support.TransactionTemplate; import java.sql.Timestamp; @@ -49,14 +48,26 @@ import static com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER; import static com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.CONFIG_INFO_TAG_WRAPPER_ROW_MAPPER; +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.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; -@RunWith(SpringJUnit4ClassRunner.class) -public class ExternalConfigInfoTagPersistServiceImplTest { +@ExtendWith(SpringExtension.class) +class ExternalConfigInfoTagPersistServiceImplTest { + + MockedStatic envUtilMockedStatic; + + MockedStatic externalStorageUtilsMockedStatic; + + MockedStatic dynamicDataSourceMockedStatic; + + @Mock + DynamicDataSource dynamicDataSource; private ExternalConfigInfoTagPersistServiceImpl externalConfigInfoTagPersistService; @@ -68,17 +79,8 @@ public class ExternalConfigInfoTagPersistServiceImplTest { private TransactionTemplate transactionTemplate = TestCaseUtils.createMockTransactionTemplate(); - MockedStatic envUtilMockedStatic; - - MockedStatic externalStorageUtilsMockedStatic; - - MockedStatic dynamicDataSourceMockedStatic; - - @Mock - DynamicDataSource dynamicDataSource; - - @Before - public void before() { + @BeforeEach + void before() { dynamicDataSourceMockedStatic = Mockito.mockStatic(DynamicDataSource.class); envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); externalStorageUtilsMockedStatic = Mockito.mockStatic(ExternalStorageUtils.class); @@ -87,20 +89,19 @@ public void before() { when(dataSourceService.getTransactionTemplate()).thenReturn(transactionTemplate); when(dataSourceService.getJdbcTemplate()).thenReturn(jdbcTemplate); when(dataSourceService.getDataSourceType()).thenReturn("mysql"); - envUtilMockedStatic.when(() -> EnvUtil.getProperty(anyString(), eq(Boolean.class), eq(false))) - .thenReturn(false); + envUtilMockedStatic.when(() -> EnvUtil.getProperty(anyString(), eq(Boolean.class), eq(false))).thenReturn(false); externalConfigInfoTagPersistService = new ExternalConfigInfoTagPersistServiceImpl(); } - @After - public void after() { + @AfterEach + void after() { dynamicDataSourceMockedStatic.close(); envUtilMockedStatic.close(); externalStorageUtilsMockedStatic.close(); } @Test - public void testInsertOrUpdateTagOfAdd() { + void testInsertOrUpdateTagOfAdd() { String dataId = "dataId111222"; String group = "group"; String tenant = "tenant"; @@ -119,20 +120,18 @@ public void testInsertOrUpdateTagOfAdd() { .thenReturn(configInfoStateWrapper); String srcIp = "ip345678"; String srcUser = "user1234567"; - ConfigOperateResult configOperateResult = externalConfigInfoTagPersistService.insertOrUpdateTag(configInfo, tag, - srcIp, srcUser); + ConfigOperateResult configOperateResult = externalConfigInfoTagPersistService.insertOrUpdateTag(configInfo, tag, srcIp, srcUser); //verify insert to be invoked Mockito.verify(jdbcTemplate, times(1)) - .update(anyString(), eq(dataId), eq(group), eq(tenant), eq(tag), eq(appName), - eq(configInfo.getContent()), eq(configInfo.getMd5()), eq(srcIp), eq(srcUser), - any(Timestamp.class), any(Timestamp.class)); - Assert.assertEquals(configInfoStateWrapper.getId(), configOperateResult.getId()); - Assert.assertEquals(configInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); + .update(anyString(), eq(dataId), eq(group), eq(tenant), eq(tag), eq(appName), eq(configInfo.getContent()), + eq(configInfo.getMd5()), eq(srcIp), eq(srcUser), any(Timestamp.class), any(Timestamp.class)); + assertEquals(configInfoStateWrapper.getId(), configOperateResult.getId()); + assertEquals(configInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); } @Test - public void testInsertOrUpdateTagOfUpdate() { + void testInsertOrUpdateTagOfUpdate() { String dataId = "dataId111222"; String group = "group"; String tenant = "tenant"; @@ -147,23 +146,21 @@ public void testInsertOrUpdateTagOfUpdate() { configInfoStateWrapper.setId(234567890L); String tag = "tag123"; Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, tag}), - eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(new ConfigInfoStateWrapper()) - .thenReturn(configInfoStateWrapper); + eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(new ConfigInfoStateWrapper()).thenReturn(configInfoStateWrapper); String srcIp = "ip345678"; String srcUser = "user1234567"; - ConfigOperateResult configOperateResult = externalConfigInfoTagPersistService.insertOrUpdateTag(configInfo, tag, - srcIp, srcUser); + ConfigOperateResult configOperateResult = externalConfigInfoTagPersistService.insertOrUpdateTag(configInfo, tag, srcIp, srcUser); //verify update to be invoked Mockito.verify(jdbcTemplate, times(1)) - .update(anyString(), eq(configInfo.getContent()), eq(configInfo.getMd5()), eq(srcIp), eq(srcUser), - any(Timestamp.class), eq(appName), eq(dataId), eq(group), eq(tenant), eq(tag)); - Assert.assertEquals(configInfoStateWrapper.getId(), configOperateResult.getId()); - Assert.assertEquals(configInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); + .update(anyString(), eq(configInfo.getContent()), eq(configInfo.getMd5()), eq(srcIp), eq(srcUser), any(Timestamp.class), + eq(appName), eq(dataId), eq(group), eq(tenant), eq(tag)); + assertEquals(configInfoStateWrapper.getId(), configOperateResult.getId()); + assertEquals(configInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); } @Test - public void testInsertOrUpdateTagCasOfAdd() { + void testInsertOrUpdateTagCasOfAdd() { String dataId = "dataId111222"; String group = "group"; String tenant = "tenant"; @@ -183,21 +180,19 @@ public void testInsertOrUpdateTagCasOfAdd() { .thenReturn(configInfoStateWrapper); String srcIp = "ip345678"; String srcUser = "user1234567"; - ConfigOperateResult configOperateResult = externalConfigInfoTagPersistService.insertOrUpdateTagCas(configInfo, - tag, srcIp, srcUser); + ConfigOperateResult configOperateResult = externalConfigInfoTagPersistService.insertOrUpdateTagCas(configInfo, tag, srcIp, srcUser); //verify insert to be invoked Mockito.verify(jdbcTemplate, times(1)) - .update(anyString(), eq(dataId), eq(group), eq(tenant), eq(tag), eq(appName), - eq(configInfo.getContent()), + .update(anyString(), eq(dataId), eq(group), eq(tenant), eq(tag), eq(appName), eq(configInfo.getContent()), eq(MD5Utils.md5Hex(configInfo.getContent(), Constants.PERSIST_ENCODE)), eq(srcIp), eq(srcUser), any(Timestamp.class), any(Timestamp.class)); - Assert.assertEquals(configInfoStateWrapper.getId(), configOperateResult.getId()); - Assert.assertEquals(configInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); + assertEquals(configInfoStateWrapper.getId(), configOperateResult.getId()); + assertEquals(configInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); } @Test - public void testInsertOrUpdateTagCasOfUpdate() { + void testInsertOrUpdateTagCasOfUpdate() { String dataId = "dataId111222"; String group = "group"; String tenant = "tenant"; @@ -213,28 +208,26 @@ public void testInsertOrUpdateTagCasOfUpdate() { configInfoStateWrapper.setId(234567890L); String tag = "tag123"; Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, tag}), - eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(new ConfigInfoStateWrapper()) - .thenReturn(configInfoStateWrapper); + eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(new ConfigInfoStateWrapper()).thenReturn(configInfoStateWrapper); String srcIp = "ip345678"; String srcUser = "user1234567"; //mock cas update return 1 Mockito.when(jdbcTemplate.update(anyString(), eq(configInfo.getContent()), - eq(MD5Utils.md5Hex(configInfo.getContent(), Constants.PERSIST_ENCODE)), eq(srcIp), eq(srcUser), - any(Timestamp.class), eq(appName), eq(dataId), eq(group), eq(tenant), eq(tag), eq(configInfo.getMd5()))) - .thenReturn(1); - ConfigOperateResult configOperateResult = externalConfigInfoTagPersistService.insertOrUpdateTagCas(configInfo, - tag, srcIp, srcUser); + eq(MD5Utils.md5Hex(configInfo.getContent(), Constants.PERSIST_ENCODE)), eq(srcIp), eq(srcUser), any(Timestamp.class), + eq(appName), eq(dataId), eq(group), eq(tenant), eq(tag), eq(configInfo.getMd5()))).thenReturn(1); + ConfigOperateResult configOperateResult = externalConfigInfoTagPersistService.insertOrUpdateTagCas(configInfo, tag, srcIp, srcUser); //verify update to be invoked - Mockito.verify(jdbcTemplate, times(1)).update(anyString(), eq(configInfo.getContent()), - eq(MD5Utils.md5Hex(configInfo.getContent(), Constants.PERSIST_ENCODE)), eq(srcIp), eq(srcUser), - any(Timestamp.class), eq(appName), eq(dataId), eq(group), eq(tenant), eq(tag), eq(configInfo.getMd5())); - Assert.assertEquals(configInfoStateWrapper.getId(), configOperateResult.getId()); - Assert.assertEquals(configInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); + Mockito.verify(jdbcTemplate, times(1)) + .update(anyString(), eq(configInfo.getContent()), eq(MD5Utils.md5Hex(configInfo.getContent(), Constants.PERSIST_ENCODE)), + eq(srcIp), eq(srcUser), any(Timestamp.class), eq(appName), eq(dataId), eq(group), eq(tenant), eq(tag), + eq(configInfo.getMd5())); + assertEquals(configInfoStateWrapper.getId(), configOperateResult.getId()); + assertEquals(configInfoStateWrapper.getLastModified(), configOperateResult.getLastModified()); } @Test - public void testInsertOrUpdateTagCasOfException() { + void testInsertOrUpdateTagCasOfException() { String dataId = "dataId111222"; String group = "group"; String tenant = "tenant"; @@ -250,47 +243,45 @@ public void testInsertOrUpdateTagCasOfException() { configInfoStateWrapper.setId(234567890L); String tag = "tag123"; Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, tag}), - eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) - .thenThrow(new CannotGetJdbcConnectionException("state query throw exception")); + eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenThrow(new CannotGetJdbcConnectionException("state query throw exception")); String srcIp = "ip345678"; String srcUser = "user1234567"; try { externalConfigInfoTagPersistService.insertOrUpdateTagCas(configInfo, tag, srcIp, srcUser); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("state query throw exception", e.getMessage()); + assertEquals("state query throw exception", e.getMessage()); } //mock get state return null,and execute add throw CannotGetJdbcConnectionException Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, tag}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(null); - Mockito.when(jdbcTemplate.update(anyString(), eq(dataId), eq(group), eq(tenant), eq(tag), eq(appName), - eq(configInfo.getContent()), eq(MD5Utils.md5Hex(configInfo.getContent(), Constants.PERSIST_ENCODE)), - eq(srcIp), eq(srcUser), any(Timestamp.class), any(Timestamp.class))) - .thenThrow(new CannotGetJdbcConnectionException("throw exception add config tag")); + Mockito.when(jdbcTemplate.update(anyString(), eq(dataId), eq(group), eq(tenant), eq(tag), eq(appName), eq(configInfo.getContent()), + eq(MD5Utils.md5Hex(configInfo.getContent(), Constants.PERSIST_ENCODE)), eq(srcIp), eq(srcUser), any(Timestamp.class), + any(Timestamp.class))).thenThrow(new CannotGetJdbcConnectionException("throw exception add config tag")); try { externalConfigInfoTagPersistService.insertOrUpdateTagCas(configInfo, tag, srcIp, srcUser); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("throw exception add config tag", e.getMessage()); + assertEquals("throw exception add config tag", e.getMessage()); } //mock get state return obj,and execute update throw CannotGetJdbcConnectionException Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, tag}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(configInfoStateWrapper); Mockito.when(jdbcTemplate.update(anyString(), eq(configInfo.getContent()), - eq(MD5Utils.md5Hex(configInfo.getContent(), Constants.PERSIST_ENCODE)), eq(srcIp), eq(srcUser), - any(Timestamp.class), eq(appName), eq(dataId), eq(group), eq(tenant), eq(tag), eq(configInfo.getMd5()))) + eq(MD5Utils.md5Hex(configInfo.getContent(), Constants.PERSIST_ENCODE)), eq(srcIp), eq(srcUser), any(Timestamp.class), + eq(appName), eq(dataId), eq(group), eq(tenant), eq(tag), eq(configInfo.getMd5()))) .thenThrow(new CannotGetJdbcConnectionException("throw exception update config tag")); try { externalConfigInfoTagPersistService.insertOrUpdateTagCas(configInfo, tag, srcIp, srcUser); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("throw exception update config tag", e.getMessage()); + assertEquals("throw exception update config tag", e.getMessage()); } } @Test - public void testRemoveConfigInfoTag() { + void testRemoveConfigInfoTag() { String dataId = "dataId1112222"; String group = "group22"; String tenant = "tenant2"; @@ -307,14 +298,14 @@ public void testRemoveConfigInfoTag() { .thenThrow(new CannotGetJdbcConnectionException("delete fail")); try { externalConfigInfoTagPersistService.removeConfigInfoTag(dataId, group, tenant, tag, srcIp, srcUser); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("delete fail", e.getMessage()); + assertEquals("delete fail", e.getMessage()); } } @Test - public void testFindConfigInfo4Tag() { + void testFindConfigInfo4Tag() { String dataId = "dataId1112222"; String group = "group22"; String tenant = "tenant2"; @@ -326,50 +317,48 @@ public void testFindConfigInfo4Tag() { Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, tag}), eq(CONFIG_INFO_TAG_WRAPPER_ROW_MAPPER))).thenReturn(configInfoTagWrapperMocked); - ConfigInfoTagWrapper configInfo4TagReturn = externalConfigInfoTagPersistService.findConfigInfo4Tag(dataId, - group, tenant, tag); - Assert.assertEquals(configInfoTagWrapperMocked, configInfo4TagReturn); + ConfigInfoTagWrapper configInfo4TagReturn = externalConfigInfoTagPersistService.findConfigInfo4Tag(dataId, group, tenant, tag); + assertEquals(configInfoTagWrapperMocked, configInfo4TagReturn); //mock query tag throw EmptyResultDataAccessException Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, tag}), eq(CONFIG_INFO_TAG_WRAPPER_ROW_MAPPER))).thenThrow(new EmptyResultDataAccessException(1)); - ConfigInfoTagWrapper configInfo4Tag = externalConfigInfoTagPersistService.findConfigInfo4Tag(dataId, group, - tenant, tag); - Assert.assertNull(configInfo4Tag); + ConfigInfoTagWrapper configInfo4Tag = externalConfigInfoTagPersistService.findConfigInfo4Tag(dataId, group, tenant, tag); + assertNull(configInfo4Tag); //mock query tag throw CannotGetJdbcConnectionException Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant, tag}), eq(CONFIG_INFO_TAG_WRAPPER_ROW_MAPPER))).thenThrow(new CannotGetJdbcConnectionException("con error")); try { externalConfigInfoTagPersistService.findConfigInfo4Tag(dataId, group, tenant, tag); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("con error", e.getMessage()); + assertEquals("con error", e.getMessage()); } } @Test - public void testConfigInfoTagCount() { + void testConfigInfoTagCount() { Timestamp timestamp = new Timestamp(System.currentTimeMillis()); //mock count Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class))).thenReturn(308); //execute & verify int count = externalConfigInfoTagPersistService.configInfoTagCount(); - Assert.assertEquals(308, count); + assertEquals(308, count); //mock count is null Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class))).thenReturn(null); //execute & verify try { externalConfigInfoTagPersistService.configInfoTagCount(); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("configInfoTagCount error", e.getMessage()); + assertEquals("configInfoTagCount error", e.getMessage()); } } @Test - public void testFindAllConfigInfoTagForDumpAll() { + void testFindAllConfigInfoTagForDumpAll() { //mock count Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class))).thenReturn(308); @@ -381,15 +370,13 @@ public void testFindAllConfigInfoTagForDumpAll() { mockTagList.get(1).setLastModified(System.currentTimeMillis()); mockTagList.get(2).setLastModified(System.currentTimeMillis()); //mock query list - Mockito.when(jdbcTemplate.query(anyString(), eq(new Object[] {}), eq(CONFIG_INFO_TAG_WRAPPER_ROW_MAPPER))) - .thenReturn(mockTagList); + Mockito.when(jdbcTemplate.query(anyString(), eq(new Object[] {}), eq(CONFIG_INFO_TAG_WRAPPER_ROW_MAPPER))).thenReturn(mockTagList); int pageNo = 3; int pageSize = 100; //execute & verify - Page returnTagPage = externalConfigInfoTagPersistService.findAllConfigInfoTagForDumpAll( - pageNo, pageSize); - Assert.assertEquals(308, returnTagPage.getTotalCount()); - Assert.assertEquals(mockTagList, returnTagPage.getPageItems()); + Page returnTagPage = externalConfigInfoTagPersistService.findAllConfigInfoTagForDumpAll(pageNo, pageSize); + assertEquals(308, returnTagPage.getTotalCount()); + assertEquals(mockTagList, returnTagPage.getPageItems()); //mock count CannotGetJdbcConnectionException Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class))) @@ -397,14 +384,14 @@ public void testFindAllConfigInfoTagForDumpAll() { //execute & verify try { externalConfigInfoTagPersistService.findAllConfigInfoTagForDumpAll(pageNo, pageSize); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("conn error111", e.getMessage()); + assertEquals("conn error111", e.getMessage()); } } @Test - public void testFindConfigInfoTags() { + void testFindConfigInfoTags() { String dataId = "dataId1112222"; String group = "group22"; String tenant = "tenant2"; @@ -413,7 +400,7 @@ public void testFindConfigInfoTags() { .thenReturn(mockedTags); List configInfoTags = externalConfigInfoTagPersistService.findConfigInfoTags(dataId, group, tenant); - Assert.assertEquals(mockedTags, configInfoTags); + assertEquals(mockedTags, configInfoTags); } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalHistoryConfigInfoPersistServiceImplTest.java b/config/src/test/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalHistoryConfigInfoPersistServiceImplTest.java index 779f592b6ff..e7509fd31ba 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalHistoryConfigInfoPersistServiceImplTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalHistoryConfigInfoPersistServiceImplTest.java @@ -25,18 +25,17 @@ import com.alibaba.nacos.persistence.datasource.DynamicDataSource; import com.alibaba.nacos.persistence.model.Page; import com.alibaba.nacos.sys.env.EnvUtil; -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.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.CannotGetJdbcConnectionException; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.transaction.support.TransactionTemplate; import java.sql.Timestamp; @@ -46,13 +45,25 @@ import static com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER; import static com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.HISTORY_DETAIL_ROW_MAPPER; import static com.alibaba.nacos.config.server.service.repository.ConfigRowMapperInjector.HISTORY_LIST_ROW_MAPPER; +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.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; -@RunWith(SpringJUnit4ClassRunner.class) -public class ExternalHistoryConfigInfoPersistServiceImplTest { +@ExtendWith(SpringExtension.class) +class ExternalHistoryConfigInfoPersistServiceImplTest { + + MockedStatic envUtilMockedStatic; + + MockedStatic externalStorageUtilsMockedStatic; + + MockedStatic dynamicDataSourceMockedStatic; + + @Mock + DynamicDataSource dynamicDataSource; private ExternalHistoryConfigInfoPersistServiceImpl externalHistoryConfigInfoPersistService; @@ -64,17 +75,8 @@ public class ExternalHistoryConfigInfoPersistServiceImplTest { private TransactionTemplate transactionTemplate = TestCaseUtils.createMockTransactionTemplate(); - MockedStatic envUtilMockedStatic; - - MockedStatic externalStorageUtilsMockedStatic; - - MockedStatic dynamicDataSourceMockedStatic; - - @Mock - DynamicDataSource dynamicDataSource; - - @Before - public void before() { + @BeforeEach + void before() { dynamicDataSourceMockedStatic = Mockito.mockStatic(DynamicDataSource.class); envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); externalStorageUtilsMockedStatic = Mockito.mockStatic(ExternalStorageUtils.class); @@ -83,20 +85,19 @@ public void before() { when(dataSourceService.getTransactionTemplate()).thenReturn(transactionTemplate); when(dataSourceService.getJdbcTemplate()).thenReturn(jdbcTemplate); when(dataSourceService.getDataSourceType()).thenReturn("mysql"); - envUtilMockedStatic.when(() -> EnvUtil.getProperty(anyString(), eq(Boolean.class), eq(false))) - .thenReturn(false); + envUtilMockedStatic.when(() -> EnvUtil.getProperty(anyString(), eq(Boolean.class), eq(false))).thenReturn(false); externalHistoryConfigInfoPersistService = new ExternalHistoryConfigInfoPersistServiceImpl(); } - @After - public void after() { + @AfterEach + void after() { dynamicDataSourceMockedStatic.close(); envUtilMockedStatic.close(); externalStorageUtilsMockedStatic.close(); } @Test - public void testInsertConfigHistoryAtomic() { + void testInsertConfigHistoryAtomic() { String dataId = "dateId243"; String group = "group243"; String tenant = "tenant243"; @@ -110,29 +111,24 @@ public void testInsertConfigHistoryAtomic() { ConfigInfo configInfo = new ConfigInfo(dataId, group, tenant, appName, content); configInfo.setEncryptedDataKey("key23456"); //expect insert success,verify insert invoked - externalHistoryConfigInfoPersistService.insertConfigHistoryAtomic(id, configInfo, srcIp, srcUser, timestamp, - ops); + externalHistoryConfigInfoPersistService.insertConfigHistoryAtomic(id, configInfo, srcIp, srcUser, timestamp, ops); Mockito.verify(jdbcTemplate, times(1)) - .update(anyString(), eq(id), eq(dataId), eq(group), eq(tenant), eq(appName), eq(content), - eq(configInfo.getMd5()), eq(srcIp), eq(srcUser), eq(timestamp), eq(ops), - eq(configInfo.getEncryptedDataKey())); + .update(anyString(), eq(id), eq(dataId), eq(group), eq(tenant), eq(appName), eq(content), eq(configInfo.getMd5()), + eq(srcIp), eq(srcUser), eq(timestamp), eq(ops), eq(configInfo.getEncryptedDataKey())); - Mockito.when( - jdbcTemplate.update(anyString(), eq(id), eq(dataId), eq(group), eq(tenant), eq(appName), eq(content), - eq(configInfo.getMd5()), eq(srcIp), eq(srcUser), eq(timestamp), eq(ops), - eq(configInfo.getEncryptedDataKey()))) + Mockito.when(jdbcTemplate.update(anyString(), eq(id), eq(dataId), eq(group), eq(tenant), eq(appName), eq(content), + eq(configInfo.getMd5()), eq(srcIp), eq(srcUser), eq(timestamp), eq(ops), eq(configInfo.getEncryptedDataKey()))) .thenThrow(new CannotGetJdbcConnectionException("mock ex...")); try { - externalHistoryConfigInfoPersistService.insertConfigHistoryAtomic(id, configInfo, srcIp, srcUser, timestamp, - ops); - Assert.assertTrue(false); + externalHistoryConfigInfoPersistService.insertConfigHistoryAtomic(id, configInfo, srcIp, srcUser, timestamp, ops); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("mock ex...", e.getMessage()); + assertEquals("mock ex...", e.getMessage()); } } @Test - public void testRemoveConfigHistory() { + void testRemoveConfigHistory() { Timestamp timestamp = new Timestamp(System.currentTimeMillis()); int pageSize = 1233; externalHistoryConfigInfoPersistService.removeConfigHistory(timestamp, pageSize); @@ -141,7 +137,7 @@ public void testRemoveConfigHistory() { } @Test - public void testFindDeletedConfig() { + void testFindDeletedConfig() { //mock query list return ConfigInfoStateWrapper mockObj1 = new ConfigInfoStateWrapper(); @@ -162,75 +158,72 @@ public void testFindDeletedConfig() { int pageSize = 1233; long startId = 23456; Timestamp timestamp = new Timestamp(System.currentTimeMillis()); - Mockito.when(jdbcTemplate.query(anyString(), eq(new Object[] {timestamp, startId, pageSize}), - eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(list); + Mockito.when( + jdbcTemplate.query(anyString(), eq(new Object[] {timestamp, startId, pageSize}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) + .thenReturn(list); //execute - List deletedConfig = externalHistoryConfigInfoPersistService.findDeletedConfig( - timestamp, startId, pageSize); + List deletedConfig = externalHistoryConfigInfoPersistService.findDeletedConfig(timestamp, startId, + pageSize); //expect verify - Assert.assertEquals("data_id1", deletedConfig.get(0).getDataId()); - Assert.assertEquals("group_id1", deletedConfig.get(0).getGroup()); - Assert.assertEquals("tenant_id1", deletedConfig.get(0).getTenant()); - Assert.assertEquals(mockObj1.getLastModified(), deletedConfig.get(0).getLastModified()); - Assert.assertEquals("data_id2", deletedConfig.get(1).getDataId()); - Assert.assertEquals("group_id2", deletedConfig.get(1).getGroup()); - Assert.assertEquals("tenant_id2", deletedConfig.get(1).getTenant()); - Assert.assertEquals(mockObj2.getLastModified(), deletedConfig.get(1).getLastModified()); + assertEquals("data_id1", deletedConfig.get(0).getDataId()); + assertEquals("group_id1", deletedConfig.get(0).getGroup()); + assertEquals("tenant_id1", deletedConfig.get(0).getTenant()); + assertEquals(mockObj1.getLastModified(), deletedConfig.get(0).getLastModified()); + assertEquals("data_id2", deletedConfig.get(1).getDataId()); + assertEquals("group_id2", deletedConfig.get(1).getGroup()); + assertEquals("tenant_id2", deletedConfig.get(1).getTenant()); + assertEquals(mockObj2.getLastModified(), deletedConfig.get(1).getLastModified()); //mock exception - Mockito.when(jdbcTemplate.query(anyString(), eq(new Object[] {timestamp, startId, pageSize}), - eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) + Mockito.when( + jdbcTemplate.query(anyString(), eq(new Object[] {timestamp, startId, pageSize}), eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))) .thenThrow(new CannotGetJdbcConnectionException("conn error")); try { externalHistoryConfigInfoPersistService.findDeletedConfig(timestamp, startId, pageSize); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("conn error", e.getMessage()); + assertEquals("conn error", e.getMessage()); } } @Test - public void testFindConfigHistory() { + void testFindConfigHistory() { String dataId = "dataId34567"; String group = "group34567"; String tenant = "tenant34567"; //mock count - Mockito.when( - jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), eq(Integer.class))) - .thenReturn(300); + Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), eq(Integer.class))).thenReturn(300); //mock list List mockList = new ArrayList<>(); mockList.add(createMockConfigHistoryInfo(0)); mockList.add(createMockConfigHistoryInfo(1)); mockList.add(createMockConfigHistoryInfo(2)); - Mockito.when( - jdbcTemplate.query(anyString(), eq(new Object[] {dataId, group, tenant}), eq(HISTORY_LIST_ROW_MAPPER))) + Mockito.when(jdbcTemplate.query(anyString(), eq(new Object[] {dataId, group, tenant}), eq(HISTORY_LIST_ROW_MAPPER))) .thenReturn(mockList); int pageSize = 100; int pageNo = 2; //execute & verify - Page historyReturn = externalHistoryConfigInfoPersistService.findConfigHistory(dataId, group, - tenant, pageNo, pageSize); - Assert.assertEquals(mockList, historyReturn.getPageItems()); - Assert.assertEquals(300, historyReturn.getTotalCount()); + Page historyReturn = externalHistoryConfigInfoPersistService.findConfigHistory(dataId, group, tenant, pageNo, + pageSize); + assertEquals(mockList, historyReturn.getPageItems()); + assertEquals(300, historyReturn.getTotalCount()); //mock exception - Mockito.when( - jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), eq(Integer.class))) + Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}), eq(Integer.class))) .thenThrow(new CannotGetJdbcConnectionException("conn error111")); try { externalHistoryConfigInfoPersistService.findConfigHistory(dataId, group, tenant, pageNo, pageSize); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("conn error111", e.getMessage()); + assertEquals("conn error111", e.getMessage()); } } @Test - public void testDetailConfigHistory() { + void testDetailConfigHistory() { long nid = 256789; //mock query @@ -239,27 +232,27 @@ public void testDetailConfigHistory() { .thenReturn(mockConfigHistoryInfo); //execute & verify ConfigHistoryInfo historyReturn = externalHistoryConfigInfoPersistService.detailConfigHistory(nid); - Assert.assertEquals(mockConfigHistoryInfo, historyReturn); + assertEquals(mockConfigHistoryInfo, historyReturn); //mock exception EmptyResultDataAccessException Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {nid}), eq(HISTORY_DETAIL_ROW_MAPPER))) .thenThrow(new EmptyResultDataAccessException(1)); ConfigHistoryInfo historyReturnNull = externalHistoryConfigInfoPersistService.detailConfigHistory(nid); - Assert.assertNull(historyReturnNull); + assertNull(historyReturnNull); //mock exception CannotGetJdbcConnectionException Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {nid}), eq(HISTORY_DETAIL_ROW_MAPPER))) .thenThrow(new CannotGetJdbcConnectionException("conn error111")); try { externalHistoryConfigInfoPersistService.detailConfigHistory(nid); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("conn error111", e.getMessage()); + assertEquals("conn error111", e.getMessage()); } } @Test - public void testDetailPreviousConfigHistory() { + void testDetailPreviousConfigHistory() { long nid = 256789; //mock query ConfigHistoryInfo mockConfigHistoryInfo = createMockConfigHistoryInfo(0); @@ -267,45 +260,43 @@ public void testDetailPreviousConfigHistory() { .thenReturn(mockConfigHistoryInfo); //execute & verify ConfigHistoryInfo historyReturn = externalHistoryConfigInfoPersistService.detailPreviousConfigHistory(nid); - Assert.assertEquals(mockConfigHistoryInfo, historyReturn); + assertEquals(mockConfigHistoryInfo, historyReturn); //mock exception EmptyResultDataAccessException Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {nid}), eq(HISTORY_DETAIL_ROW_MAPPER))) .thenThrow(new EmptyResultDataAccessException(1)); ConfigHistoryInfo historyReturnNull = externalHistoryConfigInfoPersistService.detailPreviousConfigHistory(nid); - Assert.assertNull(historyReturnNull); + assertNull(historyReturnNull); //mock exception CannotGetJdbcConnectionException Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {nid}), eq(HISTORY_DETAIL_ROW_MAPPER))) .thenThrow(new CannotGetJdbcConnectionException("conn error111")); try { externalHistoryConfigInfoPersistService.detailPreviousConfigHistory(nid); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("conn error111", e.getMessage()); + assertEquals("conn error111", e.getMessage()); } } @Test - public void testFindConfigHistoryCountByTime() { + void testFindConfigHistoryCountByTime() { Timestamp timestamp = new Timestamp(System.currentTimeMillis()); //mock count - Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {timestamp}), eq(Integer.class))) - .thenReturn(308); + Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {timestamp}), eq(Integer.class))).thenReturn(308); //execute & verify int count = externalHistoryConfigInfoPersistService.findConfigHistoryCountByTime(timestamp); - Assert.assertEquals(308, count); + assertEquals(308, count); //mock count is null - Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {timestamp}), eq(Integer.class))) - .thenReturn(null); + Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {timestamp}), eq(Integer.class))).thenReturn(null); //execute & verify try { externalHistoryConfigInfoPersistService.findConfigHistoryCountByTime(timestamp); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertEquals("findConfigHistoryCountByTime error", e.getMessage()); + assertEquals("findConfigHistoryCountByTime error", e.getMessage()); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/AccumulateStatCountTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/AccumulateStatCountTest.java index c12959cccf4..d72b94518b7 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/AccumulateStatCountTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/AccumulateStatCountTest.java @@ -16,28 +16,29 @@ package com.alibaba.nacos.config.server.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class AccumulateStatCountTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class AccumulateStatCountTest { @Test - public void testIncrease() { + void testIncrease() { AccumulateStatCount accumulateStatCount = new AccumulateStatCount(); long result = accumulateStatCount.increase(); - Assert.assertEquals(1, result); + assertEquals(1, result); } @Test - public void testStat() { + void testStat() { AccumulateStatCount accumulateStatCount = new AccumulateStatCount(); long stat = accumulateStatCount.stat(); - Assert.assertEquals(0, stat); + assertEquals(0, stat); accumulateStatCount.increase(); stat = accumulateStatCount.stat(); - Assert.assertEquals(1, stat); + assertEquals(1, stat); accumulateStatCount.increase(); stat = accumulateStatCount.stat(); - Assert.assertEquals(1, stat); + assertEquals(1, stat); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/AppNameUtilsTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/AppNameUtilsTest.java index b3df6c87642..e3b42bc6631 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/AppNameUtilsTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/AppNameUtilsTest.java @@ -16,12 +16,13 @@ package com.alibaba.nacos.config.server.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; -public class AppNameUtilsTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class AppNameUtilsTest { private static final String PARAM_MARKING_PROJECT = "project.name"; @@ -44,25 +45,25 @@ public class AppNameUtilsTest { private static final String DEFAULT_APP_NAME = "unknown"; @Test - public void testGetAppName() { + void testGetAppName() { System.setProperty(PARAM_MARKING_PROJECT, SERVER_UNKNOWN); - Assert.assertEquals(SERVER_UNKNOWN, AppNameUtils.getAppName()); + assertEquals(SERVER_UNKNOWN, AppNameUtils.getAppName()); System.clearProperty(PARAM_MARKING_PROJECT); System.setProperty(PARAM_MARKING_JBOSS, LINUX_ADMIN_HOME + SERVER_JBOSS + File.separator); - Assert.assertEquals(SERVER_JBOSS, AppNameUtils.getAppName()); + assertEquals(SERVER_JBOSS, AppNameUtils.getAppName()); System.clearProperty(PARAM_MARKING_JBOSS); System.setProperty(PARAM_MARKING_JETTY, LINUX_ADMIN_HOME + SERVER_JETTY + File.separator); - Assert.assertEquals(SERVER_JETTY, AppNameUtils.getAppName()); + assertEquals(SERVER_JETTY, AppNameUtils.getAppName()); System.clearProperty(PARAM_MARKING_JETTY); System.setProperty(PARAM_MARKING_TOMCAT, LINUX_ADMIN_HOME + SERVER_TOMCAT + File.separator); - Assert.assertEquals(SERVER_TOMCAT, AppNameUtils.getAppName()); + assertEquals(SERVER_TOMCAT, AppNameUtils.getAppName()); System.clearProperty(PARAM_MARKING_TOMCAT); - - Assert.assertEquals(DEFAULT_APP_NAME, AppNameUtils.getAppName()); + + assertEquals(DEFAULT_APP_NAME, AppNameUtils.getAppName()); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/ConfigExecutorTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/ConfigExecutorTest.java index b10e3d78d9c..597328efb4d 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/ConfigExecutorTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/ConfigExecutorTest.java @@ -16,16 +16,18 @@ package com.alibaba.nacos.config.server.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -public class ConfigExecutorTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ConfigExecutorTest { @Test - public void testScheduleConfigTask() throws InterruptedException { + void testScheduleConfigTask() throws InterruptedException { AtomicInteger atomicInteger = new AtomicInteger(); @@ -35,12 +37,12 @@ public void testScheduleConfigTask() throws InterruptedException { TimeUnit.MILLISECONDS.sleep(10); - Assert.assertTrue(atomicInteger.get() >= 1); + assertTrue(atomicInteger.get() >= 1); } @Test - public void testScheduleCorrectUsageTask() throws InterruptedException { + void testScheduleCorrectUsageTask() throws InterruptedException { AtomicInteger atomicInteger = new AtomicInteger(); @@ -50,12 +52,12 @@ public void testScheduleCorrectUsageTask() throws InterruptedException { TimeUnit.MILLISECONDS.sleep(10); - Assert.assertTrue(atomicInteger.get() >= 1); + assertTrue(atomicInteger.get() >= 1); } @Test - public void testExecuteAsyncNotify() throws InterruptedException { + void testExecuteAsyncNotify() throws InterruptedException { AtomicInteger atomicInteger = new AtomicInteger(); @@ -65,12 +67,12 @@ public void testExecuteAsyncNotify() throws InterruptedException { TimeUnit.MILLISECONDS.sleep(20); - Assert.assertEquals(1, atomicInteger.get()); + assertEquals(1, atomicInteger.get()); } @Test - public void testScheduleAsyncNotify() throws InterruptedException { + void testScheduleAsyncNotify() throws InterruptedException { AtomicInteger atomicInteger = new AtomicInteger(); @@ -78,15 +80,15 @@ public void testScheduleAsyncNotify() throws InterruptedException { ConfigExecutor.scheduleAsyncNotify(runnable, 20, TimeUnit.MILLISECONDS); - Assert.assertEquals(0, atomicInteger.get()); + assertEquals(0, atomicInteger.get()); TimeUnit.MILLISECONDS.sleep(40); - Assert.assertEquals(1, atomicInteger.get()); + assertEquals(1, atomicInteger.get()); } @Test - public void testScheduleLongPollingV1() throws InterruptedException { + void testScheduleLongPollingV1() throws InterruptedException { AtomicInteger atomicInteger = new AtomicInteger(); @@ -96,11 +98,11 @@ public void testScheduleLongPollingV1() throws InterruptedException { TimeUnit.MILLISECONDS.sleep(10); - Assert.assertTrue(atomicInteger.get() >= 1); + assertTrue(atomicInteger.get() >= 1); } @Test - public void testScheduleLongPollingV2() throws InterruptedException { + void testScheduleLongPollingV2() throws InterruptedException { AtomicInteger atomicInteger = new AtomicInteger(); @@ -108,15 +110,15 @@ public void testScheduleLongPollingV2() throws InterruptedException { ConfigExecutor.scheduleLongPolling(runnable, 20, TimeUnit.MILLISECONDS); - Assert.assertEquals(0, atomicInteger.get()); + assertEquals(0, atomicInteger.get()); TimeUnit.MILLISECONDS.sleep(40); - Assert.assertEquals(1, atomicInteger.get()); + assertEquals(1, atomicInteger.get()); } @Test - public void testExecuteLongPolling() throws InterruptedException { + void testExecuteLongPolling() throws InterruptedException { AtomicInteger atomicInteger = new AtomicInteger(); @@ -126,6 +128,6 @@ public void testExecuteLongPolling() throws InterruptedException { TimeUnit.MILLISECONDS.sleep(20); - Assert.assertEquals(1, atomicInteger.get()); + assertEquals(1, atomicInteger.get()); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/ContentUtilsTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/ContentUtilsTest.java index 45c0cf6b309..c4cb3ce125c 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/ContentUtilsTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/ContentUtilsTest.java @@ -17,91 +17,94 @@ package com.alibaba.nacos.config.server.utils; import com.alibaba.nacos.config.server.constant.Constants; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ContentUtilsTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; + +class ContentUtilsTest { @Test - public void testVerifyIncrementPubContent() { + void testVerifyIncrementPubContent() { String content = ""; try { ContentUtils.verifyIncrementPubContent(content); - Assert.fail(); + fail(); } catch (IllegalArgumentException e) { - Assert.assertNotNull(e.toString()); + assertNotNull(e.toString()); } content = "\r"; try { ContentUtils.verifyIncrementPubContent(content); - Assert.fail(); + fail(); } catch (IllegalArgumentException e) { - Assert.assertNotNull(e.toString()); + assertNotNull(e.toString()); } content = "\n"; try { ContentUtils.verifyIncrementPubContent(content); - Assert.fail(); + fail(); } catch (IllegalArgumentException e) { - Assert.assertNotNull(e.toString()); + assertNotNull(e.toString()); } content = Constants.WORD_SEPARATOR + "test"; try { ContentUtils.verifyIncrementPubContent(content); - Assert.fail(); + fail(); } catch (IllegalArgumentException e) { - Assert.assertNotNull(e.toString()); + assertNotNull(e.toString()); } } @Test - public void testGetContentIdentity() { + void testGetContentIdentity() { String content = "abc" + Constants.WORD_SEPARATOR + "edf"; String result = ContentUtils.getContentIdentity(content); - Assert.assertEquals("abc", result); + assertEquals("abc", result); content = "test"; try { ContentUtils.getContentIdentity(content); - Assert.fail(); + fail(); } catch (IllegalArgumentException e) { - Assert.assertNotNull(e.toString()); + assertNotNull(e.toString()); } } @Test - public void testGetContent() { + void testGetContent() { String content = "abc" + Constants.WORD_SEPARATOR + "edf"; String result = ContentUtils.getContent(content); - Assert.assertEquals("edf", result); + assertEquals("edf", result); content = "test"; try { ContentUtils.getContent(content); - Assert.fail(); + fail(); } catch (IllegalArgumentException e) { - Assert.assertNotNull(e.toString()); + assertNotNull(e.toString()); } } @Test - public void testTruncateContent() { + void testTruncateContent() { String content = "test"; String result = ContentUtils.truncateContent(content); - Assert.assertEquals(content, result); + assertEquals(content, result); String content2 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"; String result2 = ContentUtils.truncateContent(content2); String expected = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv..."; - Assert.assertEquals(expected, result2); + assertEquals(expected, result2); - Assert.assertEquals("", ContentUtils.truncateContent(null)); + assertEquals("", ContentUtils.truncateContent(null)); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/GroupKey2Test.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/GroupKey2Test.java index 64eba22b8f1..9ad309c4895 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/GroupKey2Test.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/GroupKey2Test.java @@ -16,27 +16,27 @@ package com.alibaba.nacos.config.server.utils; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.web.WebAppConfiguration; -@RunWith(SpringJUnit4ClassRunner.class) +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; + +@ExtendWith(SpringExtension.class) @WebAppConfiguration -public class GroupKey2Test { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); +class GroupKey2Test { @Test - public void testParseInvalidGroupKey2() { + void testParseInvalidGroupKey2() { String key = "11111+222+333333+444"; try { GroupKey2.parseKey(key); - Assert.fail(); + fail(); } catch (IllegalArgumentException e) { System.out.println(e.toString()); } @@ -44,7 +44,7 @@ public void testParseInvalidGroupKey2() { key = "11111+"; try { GroupKey2.parseKey(key); - Assert.fail(); + fail(); } catch (IllegalArgumentException e) { System.out.println(e.toString()); } @@ -52,7 +52,7 @@ public void testParseInvalidGroupKey2() { key = "11111%29+222"; try { GroupKey2.parseKey(key); - Assert.fail(); + fail(); } catch (IllegalArgumentException e) { System.out.println(e.toString()); } @@ -60,79 +60,82 @@ public void testParseInvalidGroupKey2() { key = "11111%2b+222"; try { GroupKey2.parseKey(key); - Assert.fail(); + fail(); } catch (IllegalArgumentException e) { System.out.println(e.toString()); } key = "11111%25+222"; String[] pair = GroupKey2.parseKey(key); - Assert.assertEquals("11111%", pair[0]); - Assert.assertEquals("222", pair[1]); + assertEquals("11111%", pair[0]); + assertEquals("222", pair[1]); } @Test - public void testGetKeyByThreeParams() { + void testGetKeyByThreeParams() { // Act final String actual = GroupKey2.getKey(",", ",", "3"); // Assert result - Assert.assertEquals(",+,+3", actual); + assertEquals(",+,+3", actual); } @Test - public void testGetKeyByTwoParams() { + void testGetKeyByTwoParams() { // Act final String actual = GroupKey2.getKey("3", "'"); // Assert result - Assert.assertEquals("3+'", actual); + assertEquals("3+'", actual); } @Test - public void testParseKeyBySingleCharacter() { + void testParseKeyBySingleCharacter() { // Act final String[] actual = GroupKey2.parseKey("/"); // Assert result - Assert.assertArrayEquals(new String[] {null, "/", null}, actual); + assertArrayEquals(new String[] {null, "/", null}, actual); } @Test - public void testParseKeyForPlusIllegalArgumentException() { - - // Act - thrown.expect(IllegalArgumentException.class); - GroupKey2.parseKey("+"); + void testParseKeyForPlusIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> { + GroupKey2.parseKey("+"); + + // Method is not expected to return due to exception thrown + }); // Method is not expected to return due to exception thrown } @Test - public void testParseKeyForPercentIllegalArgumentException() { - - // Act - thrown.expect(IllegalArgumentException.class); - GroupKey2.parseKey("%%%5\u0000??????????????"); + void testParseKeyForPercentIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> { + GroupKey2.parseKey("%%%5\u0000??????????????"); + + // Method is not expected to return due to exception thrown + }); // Method is not expected to return due to exception thrown } @Test - public void testParseKeyForInvalidStringIndexOutOfBoundsException() { - - // Act - thrown.expect(StringIndexOutOfBoundsException.class); - GroupKey2.parseKey("++%"); + void testParseKeyForInvalidStringIndexOutOfBoundsException() { + assertThrows(StringIndexOutOfBoundsException.class, () -> { + GroupKey2.parseKey("++%"); + + // Method is not expected to return due to exception thrown + }); // Method is not expected to return due to exception thrown } @Test - public void testUrlEncodePlus() { + void testUrlEncodePlus() { // Arrange final StringBuilder sb = new StringBuilder("????"); @@ -141,12 +144,12 @@ public void testUrlEncodePlus() { GroupKey2.urlEncode("+", sb); // Assert side effects - Assert.assertNotNull(sb); - Assert.assertEquals("????%2B", sb.toString()); + assertNotNull(sb); + assertEquals("????%2B", sb.toString()); } @Test - public void testUrlEncodeByPercent() { + void testUrlEncodeByPercent() { // Arrange final StringBuilder sb = new StringBuilder("??????"); @@ -155,16 +158,17 @@ public void testUrlEncodeByPercent() { GroupKey2.urlEncode("%", sb); // Assert side effects - Assert.assertNotNull(sb); - Assert.assertEquals("??????%25", sb.toString()); + assertNotNull(sb); + assertEquals("??????%25", sb.toString()); } @Test - public void testUrlEncodeForNullStringBuilder() { - - // Act - thrown.expect(NullPointerException.class); - GroupKey2.urlEncode("+", null); + void testUrlEncodeForNullStringBuilder() { + assertThrows(NullPointerException.class, () -> { + GroupKey2.urlEncode("+", null); + + // Method is not expected to return due to exception thrown + }); // Method is not expected to return due to exception thrown } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/GroupKeyTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/GroupKeyTest.java index e7826b597ff..68c65ef52ed 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/GroupKeyTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/GroupKeyTest.java @@ -16,27 +16,27 @@ package com.alibaba.nacos.config.server.utils; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.web.WebAppConfiguration; -@RunWith(SpringJUnit4ClassRunner.class) +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; + +@ExtendWith(SpringExtension.class) @WebAppConfiguration -public class GroupKeyTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); +class GroupKeyTest { @Test - public void testParseInvalidGroupKey() { + void testParseInvalidGroupKey() { String key = "11111+222+333333+444"; try { GroupKey.parseKey(key); - Assert.fail(); + fail(); } catch (IllegalArgumentException e) { System.out.println(e.toString()); } @@ -44,7 +44,7 @@ public void testParseInvalidGroupKey() { key = "11111+"; try { GroupKey.parseKey(key); - Assert.fail(); + fail(); } catch (IllegalArgumentException e) { System.out.println(e.toString()); } @@ -52,7 +52,7 @@ public void testParseInvalidGroupKey() { key = "11111%29+222"; try { GroupKey.parseKey(key); - Assert.fail(); + fail(); } catch (IllegalArgumentException e) { System.out.println(e.toString()); } @@ -60,99 +60,102 @@ public void testParseInvalidGroupKey() { key = "11111%2b+222"; try { GroupKey.parseKey(key); - Assert.fail(); + fail(); } catch (IllegalArgumentException e) { System.out.println(e.toString()); } key = "11111%25+222"; String[] pair = GroupKey.parseKey(key); - Assert.assertEquals("11111%", pair[0]); - Assert.assertEquals("222", pair[1]); + assertEquals("11111%", pair[0]); + assertEquals("222", pair[1]); } @Test - public void testGetKeyByThreeParams() { + void testGetKeyByThreeParams() { // Act final String actual = GroupKey.getKey(",", ",", "3"); // Assert result - Assert.assertEquals(",+,+3", actual); + assertEquals(",+,+3", actual); } @Test - public void testGetKeyByTwoParams() { + void testGetKeyByTwoParams() { // Act final String actual = GroupKey.getKey("3", "'"); // Assert result - Assert.assertEquals("3+'", actual); + assertEquals("3+'", actual); } @Test - public void testGetKeyTenantByPlusThreeParams() { + void testGetKeyTenantByPlusThreeParams() { // Act final String actual = GroupKey.getKeyTenant("3", "1", ","); // Assert result - Assert.assertEquals("3+1+,", actual); + assertEquals("3+1+,", actual); } @Test - public void testGetKeyTenantByPercentThreeParams() { + void testGetKeyTenantByPercentThreeParams() { // Act final String actual = GroupKey.getKeyTenant("\u0000\u0000", "%+", null); // Assert result - Assert.assertEquals("\u0000\u0000+%25%2B", actual); + assertEquals("\u0000\u0000+%25%2B", actual); } @Test - public void testParseKeyBySingleCharacter() { + void testParseKeyBySingleCharacter() { // Act final String[] actual = GroupKey.parseKey("/"); // Assert result - Assert.assertArrayEquals(new String[] {null, "/", null}, actual); + assertArrayEquals(new String[] {null, "/", null}, actual); } @Test - public void testParseKeyForPlusIllegalArgumentException() { - - // Act - thrown.expect(IllegalArgumentException.class); - GroupKey.parseKey("+"); + void testParseKeyForPlusIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> { + GroupKey.parseKey("+"); + + // Method is not expected to return due to exception thrown + }); // Method is not expected to return due to exception thrown } @Test - public void testParseKeyForPercentIllegalArgumentException() { - - // Act - thrown.expect(IllegalArgumentException.class); - GroupKey.parseKey("%%%5\u0000??????????????"); + void testParseKeyForPercentIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> { + GroupKey.parseKey("%%%5\u0000??????????????"); + + // Method is not expected to return due to exception thrown + }); // Method is not expected to return due to exception thrown } @Test - public void testParseKeyForInvalidStringIndexOutOfBoundsException() { - - // Act - thrown.expect(StringIndexOutOfBoundsException.class); - GroupKey.parseKey("++%"); + void testParseKeyForInvalidStringIndexOutOfBoundsException() { + assertThrows(StringIndexOutOfBoundsException.class, () -> { + GroupKey.parseKey("++%"); + + // Method is not expected to return due to exception thrown + }); // Method is not expected to return due to exception thrown } @Test - public void testUrlEncodePlus() { + void testUrlEncodePlus() { // Arrange final StringBuilder sb = new StringBuilder("????"); @@ -161,12 +164,12 @@ public void testUrlEncodePlus() { GroupKey.urlEncode("+", sb); // Assert side effects - Assert.assertNotNull(sb); - Assert.assertEquals("????%2B", sb.toString()); + assertNotNull(sb); + assertEquals("????%2B", sb.toString()); } @Test - public void testUrlEncodeByPercent() { + void testUrlEncodeByPercent() { // Arrange final StringBuilder sb = new StringBuilder("??????"); @@ -175,16 +178,17 @@ public void testUrlEncodeByPercent() { GroupKey.urlEncode("%", sb); // Assert side effects - Assert.assertNotNull(sb); - Assert.assertEquals("??????%25", sb.toString()); + assertNotNull(sb); + assertEquals("??????%25", sb.toString()); } @Test - public void testUrlEncodeForNullStringBuilder() { - - // Act - thrown.expect(NullPointerException.class); - GroupKey.urlEncode("+", null); + void testUrlEncodeForNullStringBuilder() { + assertThrows(NullPointerException.class, () -> { + GroupKey.urlEncode("+", null); + + // Method is not expected to return due to exception thrown + }); // Method is not expected to return due to exception thrown } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/LogUtilTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/LogUtilTest.java index c33f009e205..407200e6dd2 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/LogUtilTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/LogUtilTest.java @@ -17,49 +17,50 @@ package com.alibaba.nacos.config.server.utils; import ch.qos.logback.classic.Logger; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class LogUtilTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class LogUtilTest { @Test - public void testSetLogLevel() { + void testSetLogLevel() { LogUtil.setLogLevel("config-server", "INFO"); ch.qos.logback.classic.Logger defaultLog = (Logger) LogUtil.DEFAULT_LOG; - Assert.assertEquals("INFO", defaultLog.getLevel().levelStr); + assertEquals("INFO", defaultLog.getLevel().levelStr); LogUtil.setLogLevel("config-fatal", "INFO"); ch.qos.logback.classic.Logger fatalLog = (Logger) LogUtil.FATAL_LOG; - Assert.assertEquals("INFO", fatalLog.getLevel().levelStr); + assertEquals("INFO", fatalLog.getLevel().levelStr); LogUtil.setLogLevel("config-pull", "INFO"); ch.qos.logback.classic.Logger pullLog = (Logger) LogUtil.PULL_LOG; - Assert.assertEquals("INFO", pullLog.getLevel().levelStr); + assertEquals("INFO", pullLog.getLevel().levelStr); LogUtil.setLogLevel("config-pull-check", "INFO"); ch.qos.logback.classic.Logger pullCheckLog = (Logger) LogUtil.PULL_CHECK_LOG; - Assert.assertEquals("INFO", pullCheckLog.getLevel().levelStr); + assertEquals("INFO", pullCheckLog.getLevel().levelStr); LogUtil.setLogLevel("config-dump", "INFO"); ch.qos.logback.classic.Logger dumpLog = (Logger) LogUtil.DUMP_LOG; - Assert.assertEquals("INFO", dumpLog.getLevel().levelStr); + assertEquals("INFO", dumpLog.getLevel().levelStr); LogUtil.setLogLevel("config-memory", "INFO"); ch.qos.logback.classic.Logger memoryLog = (Logger) LogUtil.MEMORY_LOG; - Assert.assertEquals("INFO", memoryLog.getLevel().levelStr); + assertEquals("INFO", memoryLog.getLevel().levelStr); LogUtil.setLogLevel("config-client-request", "INFO"); ch.qos.logback.classic.Logger clientRequestLog = (Logger) LogUtil.CLIENT_LOG; - Assert.assertEquals("INFO", clientRequestLog.getLevel().levelStr); + assertEquals("INFO", clientRequestLog.getLevel().levelStr); LogUtil.setLogLevel("config-trace", "INFO"); ch.qos.logback.classic.Logger traceLog = (Logger) LogUtil.TRACE_LOG; - Assert.assertEquals("INFO", traceLog.getLevel().levelStr); + assertEquals("INFO", traceLog.getLevel().levelStr); LogUtil.setLogLevel("config-notify", "INFO"); ch.qos.logback.classic.Logger notifyLog = (Logger) LogUtil.NOTIFY_LOG; - Assert.assertEquals("INFO", notifyLog.getLevel().levelStr); + assertEquals("INFO", notifyLog.getLevel().levelStr); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/MD5UtilTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/MD5UtilTest.java index c1798655316..75ba6c1a82e 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/MD5UtilTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/MD5UtilTest.java @@ -18,8 +18,7 @@ import com.alibaba.nacos.config.server.service.ConfigCacheService; import org.apache.commons.io.IOUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.springframework.mock.web.MockHttpServletRequest; @@ -37,20 +36,18 @@ import java.util.List; import java.util.Map; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; -public class MD5UtilTest { +class MD5UtilTest { @Test - public void testCompareMd5() { + void testCompareMd5() { - final MockedStatic configCacheServiceMockedStatic = Mockito - .mockStatic(ConfigCacheService.class); + final MockedStatic configCacheServiceMockedStatic = Mockito.mockStatic(ConfigCacheService.class); - when(ConfigCacheService - .isUptodate(anyString(), anyString(), anyString(), anyString())) - .thenReturn(false); + when(ConfigCacheService.isUptodate(anyString(), anyString(), anyString(), anyString())).thenReturn(false); Map clientMd5Map = new HashMap<>(); clientMd5Map.put("test", "test"); @@ -61,14 +58,14 @@ public void testCompareMd5() { List changedGroupKeys = MD5Util.compareMd5(request, response, clientMd5Map); - Assert.assertEquals(1, changedGroupKeys.size()); - Assert.assertEquals("test", changedGroupKeys.get(0)); + assertEquals(1, changedGroupKeys.size()); + assertEquals("test", changedGroupKeys.get(0)); configCacheServiceMockedStatic.close(); } @Test - public void testCompareMd5OldResult() { + void testCompareMd5OldResult() { final MockedStatic groupKey2MockedStatic = Mockito.mockStatic(GroupKey2.class); @@ -83,13 +80,13 @@ public void testCompareMd5OldResult() { String actualValue = MD5Util.compareMd5OldResult(changedGroupKeys); - Assert.assertEquals("test0:test1;", actualValue); + assertEquals("test0:test1;", actualValue); groupKey2MockedStatic.close(); } @Test - public void testCompareMd5ResultString() { + void testCompareMd5ResultString() { final MockedStatic groupKey2MockedStatic = Mockito.mockStatic(GroupKey2.class); @@ -104,7 +101,7 @@ public void testCompareMd5ResultString() { try { String actualValue = MD5Util.compareMd5ResultString(changedGroupKeys); - Assert.assertEquals("test0%02test1%02test2%01", actualValue); + assertEquals("test0%02test1%02test2%01", actualValue); } catch (IOException e) { System.out.println(e.toString()); } @@ -113,55 +110,54 @@ public void testCompareMd5ResultString() { } @Test - public void testGetClientMd5Map() { + void testGetClientMd5Map() { String configKeysString = - "test0" + MD5Util.WORD_SEPARATOR_CHAR + "test1" + MD5Util.WORD_SEPARATOR_CHAR + "test2" - + MD5Util.LINE_SEPARATOR_CHAR; + "test0" + MD5Util.WORD_SEPARATOR_CHAR + "test1" + MD5Util.WORD_SEPARATOR_CHAR + "test2" + MD5Util.LINE_SEPARATOR_CHAR; Map actualValueMap = MD5Util.getClientMd5Map(configKeysString); - Assert.assertEquals("test2", actualValueMap.get("test0+test1")); + assertEquals("test2", actualValueMap.get("test0+test1")); } @Test - public void testGetClientMd5MapForNewProtocol() { + void testGetClientMd5MapForNewProtocol() { String configKeysString = - "test0" + MD5Util.WORD_SEPARATOR_CHAR + "test1" + MD5Util.WORD_SEPARATOR_CHAR + "test2" - + MD5Util.WORD_SEPARATOR_CHAR + "test3" + MD5Util.LINE_SEPARATOR_CHAR; + "test0" + MD5Util.WORD_SEPARATOR_CHAR + "test1" + MD5Util.WORD_SEPARATOR_CHAR + "test2" + MD5Util.WORD_SEPARATOR_CHAR + + "test3" + MD5Util.LINE_SEPARATOR_CHAR; Map actualValueMap = MD5Util.getClientMd5Map(configKeysString); - Assert.assertEquals("test2", actualValueMap.get("test0+test1+test3")); + assertEquals("test2", actualValueMap.get("test0+test1+test3")); } @Test - public void testToStringV1() { + void testToStringV1() { try { InputStream input = IOUtils.toInputStream("test", StandardCharsets.UTF_8); String actualValue = MD5Util.toString(input, "UTF-8"); - Assert.assertEquals("test", actualValue); + assertEquals("test", actualValue); } catch (IOException e) { System.out.println(e.toString()); } } @Test - public void testToStringV2() { + void testToStringV2() { try { Reader reader = new CharArrayReader("test".toCharArray()); String actualValue = MD5Util.toString(reader); - Assert.assertEquals("test", actualValue); + assertEquals("test", actualValue); } catch (IOException e) { System.out.println(e.toString()); } } @Test - public void testCopy() { + void testCopy() { try { String content = "test"; @@ -169,8 +165,8 @@ public void testCopy() { Writer output = new CharArrayWriter(); long actualValue = MD5Util.copy(input, output); - Assert.assertEquals(content.length(), actualValue); - Assert.assertEquals(content, output.toString()); + assertEquals(content.length(), actualValue); + assertEquals(content, output.toString()); } catch (IOException e) { System.out.println(e.toString()); diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/ParamUtilsTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/ParamUtilsTest.java index 7672dca5d53..8b9b6c3ae16 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/ParamUtilsTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/ParamUtilsTest.java @@ -17,25 +17,28 @@ package com.alibaba.nacos.config.server.utils; import com.alibaba.nacos.api.exception.NacosException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; -public class ParamUtilsTest { +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +class ParamUtilsTest { @Test - public void testIsValid() { - Assert.assertTrue(ParamUtils.isValid("test")); - Assert.assertTrue(ParamUtils.isValid("test1234")); - Assert.assertTrue(ParamUtils.isValid("test_-.:")); - Assert.assertFalse(ParamUtils.isValid("test!")); - Assert.assertFalse(ParamUtils.isValid("test~")); + void testIsValid() { + assertTrue(ParamUtils.isValid("test")); + assertTrue(ParamUtils.isValid("test1234")); + assertTrue(ParamUtils.isValid("test_-.:")); + assertFalse(ParamUtils.isValid("test!")); + assertFalse(ParamUtils.isValid("test~")); } @Test - public void testCheckParamV1() { + void testCheckParamV1() { //dataId is empty String dataId = ""; String group = "test"; @@ -43,7 +46,7 @@ public void testCheckParamV1() { String content = "test"; try { ParamUtils.checkParam(dataId, group, datumId, content); - Assert.fail(); + fail(); } catch (NacosException e) { System.out.println(e.toString()); } @@ -54,7 +57,7 @@ public void testCheckParamV1() { content = "test"; try { ParamUtils.checkParam(dataId, group, datumId, content); - Assert.fail(); + fail(); } catch (NacosException e) { System.out.println(e.toString()); } @@ -65,7 +68,7 @@ public void testCheckParamV1() { content = "test"; try { ParamUtils.checkParam(dataId, group, datumId, content); - Assert.fail(); + fail(); } catch (NacosException e) { System.out.println(e.toString()); } @@ -76,7 +79,7 @@ public void testCheckParamV1() { content = ""; try { ParamUtils.checkParam(dataId, group, datumId, content); - Assert.fail(); + fail(); } catch (NacosException e) { System.out.println(e.toString()); } @@ -87,7 +90,7 @@ public void testCheckParamV1() { content = "test"; try { ParamUtils.checkParam(dataId, group, datumId, content); - Assert.fail(); + fail(); } catch (NacosException e) { System.out.println(e.toString()); } @@ -98,7 +101,7 @@ public void testCheckParamV1() { content = "test"; try { ParamUtils.checkParam(dataId, group, datumId, content); - Assert.fail(); + fail(); } catch (NacosException e) { System.out.println(e.toString()); } @@ -109,7 +112,7 @@ public void testCheckParamV1() { content = "test"; try { ParamUtils.checkParam(dataId, group, datumId, content); - Assert.fail(); + fail(); } catch (NacosException e) { System.out.println(e.toString()); } @@ -126,19 +129,19 @@ public void testCheckParamV1() { try { ParamUtils.checkParam(dataId, group, datumId, content); - Assert.fail(); + fail(); } catch (NacosException e) { System.out.println(e.toString()); } } @Test - public void testCheckParamV2() { + void testCheckParamV2() { //tag invalid String tag = "test!"; try { ParamUtils.checkParam(tag); - Assert.fail(); + fail(); } catch (IllegalArgumentException e) { System.out.println(e.toString()); } @@ -147,7 +150,7 @@ public void testCheckParamV2() { tag = "testtesttesttest1"; try { ParamUtils.checkParam(tag); - Assert.fail(); + fail(); } catch (IllegalArgumentException e) { System.out.println(e.toString()); } @@ -155,13 +158,13 @@ public void testCheckParamV2() { } @Test - public void testCheckParamV3() { + void testCheckParamV3() { //tag size over 5 Map configAdvanceInfo = new HashMap<>(); configAdvanceInfo.put("config_tags", "test,test,test,test,test,test"); try { ParamUtils.checkParam(configAdvanceInfo); - Assert.fail(); + fail(); } catch (NacosException e) { System.out.println(e.toString()); } @@ -174,7 +177,7 @@ public void testCheckParamV3() { configAdvanceInfo.put("config_tags", tagBuilder.toString()); try { ParamUtils.checkParam(configAdvanceInfo); - Assert.fail(); + fail(); } catch (NacosException e) { System.out.println(e.toString()); } @@ -188,7 +191,7 @@ public void testCheckParamV3() { configAdvanceInfo.put("desc", descBuilder.toString()); try { ParamUtils.checkParam(configAdvanceInfo); - Assert.fail(); + fail(); } catch (NacosException e) { System.out.println(e.toString()); } @@ -202,7 +205,7 @@ public void testCheckParamV3() { configAdvanceInfo.put("use", useBuilder.toString()); try { ParamUtils.checkParam(configAdvanceInfo); - Assert.fail(); + fail(); } catch (NacosException e) { System.out.println(e.toString()); } @@ -216,7 +219,7 @@ public void testCheckParamV3() { configAdvanceInfo.put("effect", effectBuilder.toString()); try { ParamUtils.checkParam(configAdvanceInfo); - Assert.fail(); + fail(); } catch (NacosException e) { System.out.println(e.toString()); } @@ -230,7 +233,7 @@ public void testCheckParamV3() { configAdvanceInfo.put("type", typeBuilder.toString()); try { ParamUtils.checkParam(configAdvanceInfo); - Assert.fail(); + fail(); } catch (NacosException e) { System.out.println(e.toString()); } @@ -244,7 +247,7 @@ public void testCheckParamV3() { configAdvanceInfo.put("schema", schemaBuilder.toString()); try { ParamUtils.checkParam(configAdvanceInfo); - Assert.fail(); + fail(); } catch (NacosException e) { System.out.println(e.toString()); } @@ -254,19 +257,19 @@ public void testCheckParamV3() { configAdvanceInfo.put("test", "test"); try { ParamUtils.checkParam(configAdvanceInfo); - Assert.fail(); + fail(); } catch (NacosException e) { System.out.println(e.toString()); } } @Test - public void testCheckTenant() { + void testCheckTenant() { //tag invalid String tenant = "test!"; try { ParamUtils.checkTenant(tenant); - Assert.fail(); + fail(); } catch (IllegalArgumentException e) { System.out.println(e.toString()); } @@ -280,7 +283,7 @@ public void testCheckTenant() { tenant = tenantBuilder.toString(); try { ParamUtils.checkTenant(tenant); - Assert.fail(); + fail(); } catch (IllegalArgumentException e) { System.out.println(e.toString()); } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/PropertyUtilTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/PropertyUtilTest.java index 0038b8f1405..5224b7c62ea 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/PropertyUtilTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/PropertyUtilTest.java @@ -18,38 +18,38 @@ import com.alibaba.nacos.sys.env.EnvUtil; import org.apache.commons.io.FileUtils; -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.MockedStatic; import org.mockito.Mockito; import org.springframework.security.util.FieldUtils; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import java.io.File; import java.lang.reflect.Field; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.eq; -@RunWith(SpringJUnit4ClassRunner.class) -public class PropertyUtilTest { +@ExtendWith(SpringExtension.class) +class PropertyUtilTest { MockedStatic envUtilMockedStatic; private String mockMem = "tmpmocklimitfile.txt"; - @Before - public void setUp() { + @BeforeEach + void setUp() { envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); - envUtilMockedStatic.when(() -> EnvUtil.getProperty(eq("memory_limit_file_path"), - eq("/sys/fs/cgroup/memory/memory.limit_in_bytes"))).thenReturn(mockMem); + envUtilMockedStatic.when(() -> EnvUtil.getProperty(eq("memory_limit_file_path"), eq("/sys/fs/cgroup/memory/memory.limit_in_bytes"))) + .thenReturn(mockMem); } - @After - public void after() { + @AfterEach + void after() { envUtilMockedStatic.close(); File file = new File(mockMem); if (file.exists()) { @@ -58,18 +58,18 @@ public void after() { } @Test - public void testGetPropertyV1() { + void testGetPropertyV1() { envUtilMockedStatic.when(() -> EnvUtil.getProperty(eq("test"))).thenReturn("test"); - Assert.assertEquals("test", new PropertyUtil().getProperty("test")); + assertEquals("test", new PropertyUtil().getProperty("test")); } @Test - public void testGetPropertyV2() { + void testGetPropertyV2() { envUtilMockedStatic.when(() -> EnvUtil.getProperty(eq("test"), eq("default"))).thenReturn("default"); - Assert.assertEquals("default", new PropertyUtil().getProperty("test", "default")); + assertEquals("default", new PropertyUtil().getProperty("test", "default")); } private void clearAllDumpFiled() throws Exception { @@ -79,7 +79,7 @@ private void clearAllDumpFiled() throws Exception { } @Test - public void testGetAllDumpPageSize() throws Exception { + void testGetAllDumpPageSize() throws Exception { clearAllDumpFiled(); File file = new File(mockMem); @@ -89,14 +89,14 @@ public void testGetAllDumpPageSize() throws Exception { FileUtils.writeStringToFile(file, String.valueOf(gb2)); int allDumpPageSizeNormal = PropertyUtil.getAllDumpPageSize(); //expect 2*2*50 - Assert.assertEquals(200, allDumpPageSizeNormal); + assertEquals(200, allDumpPageSizeNormal); clearAllDumpFiled(); // 12G pageSize over 1000 long gb12 = 12L * 1024L * 1024L * 1024L; FileUtils.writeStringToFile(file, String.valueOf(gb12)); int allDumpPageSizeOverMax = PropertyUtil.getAllDumpPageSize(); - Assert.assertEquals(1000, allDumpPageSizeOverMax); + assertEquals(1000, allDumpPageSizeOverMax); clearAllDumpFiled(); //100MB @@ -104,11 +104,11 @@ public void testGetAllDumpPageSize() throws Exception { FileUtils.writeStringToFile(file, String.valueOf(mb100)); int allDumpPageSizeUnderMin = PropertyUtil.getAllDumpPageSize(); - Assert.assertEquals(50, allDumpPageSizeUnderMin); + assertEquals(50, allDumpPageSizeUnderMin); } @Test - public void testGetAllDumpPageSizeWithJvmArgs() throws Exception { + void testGetAllDumpPageSizeWithJvmArgs() throws Exception { File file = new File(mockMem); if (file.exists()) { @@ -118,11 +118,11 @@ public void testGetAllDumpPageSizeWithJvmArgs() throws Exception { long maxMem = Runtime.getRuntime().maxMemory(); long pageSize = maxMem / 1024 / 1024 / 512 * 50; if (pageSize < 50) { - Assert.assertEquals(50, allDumpPageSizeUnderMin); + assertEquals(50, allDumpPageSizeUnderMin); } else if (pageSize > 1000) { - Assert.assertEquals(1000, allDumpPageSizeUnderMin); + assertEquals(1000, allDumpPageSizeUnderMin); } else { - Assert.assertEquals(pageSize, allDumpPageSizeUnderMin); + assertEquals(pageSize, allDumpPageSizeUnderMin); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/ProtocolTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/ProtocolTest.java index b134a31231d..5adb7c23a3f 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/ProtocolTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/ProtocolTest.java @@ -16,20 +16,21 @@ package com.alibaba.nacos.config.server.utils; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.test.context.junit.jupiter.SpringExtension; -@RunWith(SpringJUnit4ClassRunner.class) -public class ProtocolTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +@ExtendWith(SpringExtension.class) +class ProtocolTest { @Test - public void testGetVersionNumber() { + void testGetVersionNumber() { - Assert.assertEquals(-1, Protocol.getVersionNumber(null)); - Assert.assertEquals(0, Protocol.getVersionNumber("")); - Assert.assertEquals(120, Protocol.getVersionNumber("1.2.0")); - Assert.assertEquals(10, Protocol.getVersionNumber("1.A.0")); + assertEquals(-1, Protocol.getVersionNumber(null)); + assertEquals(0, Protocol.getVersionNumber("")); + assertEquals(120, Protocol.getVersionNumber("1.2.0")); + assertEquals(10, Protocol.getVersionNumber("1.A.0")); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/RegexParserTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/RegexParserTest.java index bc537c09b90..3bbf3231487 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/RegexParserTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/RegexParserTest.java @@ -16,27 +16,31 @@ package com.alibaba.nacos.config.server.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class RegexParserTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +class RegexParserTest { @Test - public void testRegexFormat() { + void testRegexFormat() { try { RegexParser.regexFormat(null); - Assert.fail(); + fail(); } catch (NullPointerException e) { System.out.println(e.toString()); } - Assert.assertEquals("^test.*\\!.{1}xxxx$", RegexParser.regexFormat("test*!?xxxx")); + assertEquals("^test.*\\!.{1}xxxx$", RegexParser.regexFormat("test*!?xxxx")); } @Test - public void testContainsWildcard() { - Assert.assertFalse(RegexParser.containsWildcard("test")); - Assert.assertTrue(RegexParser.containsWildcard("?")); - Assert.assertTrue(RegexParser.containsWildcard("*")); + void testContainsWildcard() { + assertFalse(RegexParser.containsWildcard("test")); + assertTrue(RegexParser.containsWildcard("?")); + assertTrue(RegexParser.containsWildcard("*")); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/RequestUtilTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/RequestUtilTest.java index b190799f493..d272e221083 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/RequestUtilTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/RequestUtilTest.java @@ -17,70 +17,79 @@ package com.alibaba.nacos.config.server.utils; import com.alibaba.nacos.api.common.Constants; -import org.junit.Assert; -import org.junit.Test; +import com.alibaba.nacos.core.context.RequestContextHolder; +import com.alibaba.nacos.plugin.auth.api.IdentityContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.eq; -public class RequestUtilTest { +class RequestUtilTest { private static final String X_REAL_IP = "X-Real-IP"; private static final String X_FORWARDED_FOR = "X-Forwarded-For"; + @AfterEach + void tearDown() { + RequestContextHolder.removeContext(); + } + @Test - public void testGetRemoteIp() { + void testGetRemoteIpFromRequest() { HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getRemoteAddr()).thenReturn("127.0.0.1"); - Assert.assertEquals("127.0.0.1", RequestUtil.getRemoteIp(request)); + assertEquals("127.0.0.1", RequestUtil.getRemoteIp(request)); Mockito.when(request.getHeader(eq(X_REAL_IP))).thenReturn("127.0.0.2"); - Assert.assertEquals("127.0.0.2", RequestUtil.getRemoteIp(request)); + assertEquals("127.0.0.2", RequestUtil.getRemoteIp(request)); Mockito.when(request.getHeader(eq(X_FORWARDED_FOR))).thenReturn("127.0.0.3"); - Assert.assertEquals("127.0.0.3", RequestUtil.getRemoteIp(request)); + assertEquals("127.0.0.3", RequestUtil.getRemoteIp(request)); Mockito.when(request.getHeader(eq(X_FORWARDED_FOR))).thenReturn("127.0.0.3, 127.0.0.4"); - Assert.assertEquals("127.0.0.3", RequestUtil.getRemoteIp(request)); + assertEquals("127.0.0.3", RequestUtil.getRemoteIp(request)); Mockito.when(request.getHeader(eq(X_FORWARDED_FOR))).thenReturn(""); - Assert.assertEquals("127.0.0.2", RequestUtil.getRemoteIp(request)); + assertEquals("127.0.0.2", RequestUtil.getRemoteIp(request)); Mockito.when(request.getHeader(eq(X_REAL_IP))).thenReturn(""); - Assert.assertEquals("127.0.0.1", RequestUtil.getRemoteIp(request)); + assertEquals("127.0.0.1", RequestUtil.getRemoteIp(request)); } @Test - public void testGetAppName() { + void testGetAppNameFromContext() { + RequestContextHolder.getContext().getBasicContext().setApp("contextApp"); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getHeader(eq(RequestUtil.CLIENT_APPNAME_HEADER))).thenReturn("test"); - Assert.assertEquals("test", RequestUtil.getAppName(request)); + assertEquals("contextApp", RequestUtil.getAppName(request)); } @Test - public void testGetSrcUserNameV1() { + void testGetAppNameFromRequest() { HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - HttpSession session = Mockito.mock(HttpSession.class); - Mockito.when(request.getSession()).thenReturn(session); - Mockito.when(session.getAttribute(eq(com.alibaba.nacos.plugin.auth.constant.Constants.Identity.IDENTITY_ID))) - .thenReturn("test"); - Assert.assertEquals("test", RequestUtil.getSrcUserName(request)); + Mockito.when(request.getHeader(eq(RequestUtil.CLIENT_APPNAME_HEADER))).thenReturn("test"); + assertEquals("test", RequestUtil.getAppName(request)); } @Test - public void testGetSrcUserNameV2() { + void testGetSrcUserNameFromContext() { + IdentityContext identityContext = new IdentityContext(); + identityContext.setParameter(com.alibaba.nacos.plugin.auth.constant.Constants.Identity.IDENTITY_ID, "test"); + RequestContextHolder.getContext().getAuthContext().setIdentityContext(identityContext); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - HttpSession session = Mockito.mock(HttpSession.class); - Mockito.when(request.getSession()).thenReturn(session); - Mockito.when(session.getAttribute(eq(com.alibaba.nacos.plugin.auth.constant.Constants.Identity.IDENTITY_ID))) - .thenReturn(null); - Mockito.when(request.getParameter(eq(Constants.USERNAME))).thenReturn("parameterName"); - Assert.assertEquals("parameterName", RequestUtil.getSrcUserName(request)); + assertEquals("test", RequestUtil.getSrcUserName(request)); } + @Test + void testGetSrcUserNameFromRequest() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + Mockito.when(request.getParameter(eq(Constants.USERNAME))).thenReturn("parameterName"); + assertEquals("parameterName", RequestUtil.getSrcUserName(request)); + } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/ResponseUtilTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/ResponseUtilTest.java index 940b85efa41..92cf48d5f5e 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/ResponseUtilTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/ResponseUtilTest.java @@ -16,23 +16,24 @@ package com.alibaba.nacos.config.server.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletResponse; import java.io.UnsupportedEncodingException; -public class ResponseUtilTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ResponseUtilTest { String lineSeparator = System.lineSeparator(); @Test - public void testWriteErrMsg() { + void testWriteErrMsg() { MockHttpServletResponse response = new MockHttpServletResponse(); ResponseUtil.writeErrMsg(response, 404, "test"); - Assert.assertEquals(404, response.getStatus()); + assertEquals(404, response.getStatus()); try { - Assert.assertEquals("test" + lineSeparator, response.getContentAsString()); + assertEquals("test" + lineSeparator, response.getContentAsString()); } catch (UnsupportedEncodingException e) { System.out.println(e.toString()); } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/SimpleCacheTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/SimpleCacheTest.java index de50c5efaa5..d0415cc7fc7 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/SimpleCacheTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/SimpleCacheTest.java @@ -16,23 +16,25 @@ package com.alibaba.nacos.config.server.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; -public class SimpleCacheTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class SimpleCacheTest { @Test - public void testPutAndGet() throws InterruptedException { + void testPutAndGet() throws InterruptedException { SimpleCache simpleCache = new SimpleCache<>(); simpleCache.put("key", "value", 1000); - Assert.assertEquals("value", simpleCache.get("key")); + assertEquals("value", simpleCache.get("key")); //time expire TimeUnit.MILLISECONDS.sleep(1100); Object value = simpleCache.get("key"); - Assert.assertNull(value); + assertNull(value); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/SimpleFlowDataTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/SimpleFlowDataTest.java index 031bb99f4a5..a52f91eee92 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/SimpleFlowDataTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/SimpleFlowDataTest.java @@ -16,62 +16,63 @@ package com.alibaba.nacos.config.server.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class SimpleFlowDataTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SimpleFlowDataTest { @Test - public void testAddAndGet() { + void testAddAndGet() { SimpleFlowData simpleFlowData = new SimpleFlowData(5, 10000); - Assert.assertEquals(10, simpleFlowData.addAndGet(10)); - Assert.assertEquals(20, simpleFlowData.addAndGet(10)); + assertEquals(10, simpleFlowData.addAndGet(10)); + assertEquals(20, simpleFlowData.addAndGet(10)); } @Test - public void testIncrementAndGet() { + void testIncrementAndGet() { SimpleFlowData simpleFlowData = new SimpleFlowData(5, 10000); - Assert.assertEquals(1, simpleFlowData.incrementAndGet()); - Assert.assertEquals(2, simpleFlowData.incrementAndGet()); - Assert.assertEquals(3, simpleFlowData.incrementAndGet()); + assertEquals(1, simpleFlowData.incrementAndGet()); + assertEquals(2, simpleFlowData.incrementAndGet()); + assertEquals(3, simpleFlowData.incrementAndGet()); } @Test - public void testGetSlotInfo() { + void testGetSlotInfo() { SimpleFlowData simpleFlowData = new SimpleFlowData(5, 10000); simpleFlowData.incrementAndGet(); simpleFlowData.incrementAndGet(); simpleFlowData.incrementAndGet(); - Assert.assertEquals("0 0 0 0 3", simpleFlowData.getSlotInfo()); + assertEquals("0 0 0 0 3", simpleFlowData.getSlotInfo()); } @Test - public void testGetSlotInfo2() { + void testGetSlotInfo2() { SimpleFlowData simpleFlowData = new SimpleFlowData(5, 10000); simpleFlowData.incrementAndGet(); simpleFlowData.rotateSlot(); simpleFlowData.addAndGet(9); simpleFlowData.rotateSlot(); simpleFlowData.incrementAndGet(); - Assert.assertEquals("0 0 1 9 1", simpleFlowData.getSlotInfo()); - Assert.assertEquals(1, simpleFlowData.getCurrentCount()); - Assert.assertEquals(2, simpleFlowData.getAverageCount()); - Assert.assertEquals(5, simpleFlowData.getSlotCount()); + assertEquals("0 0 1 9 1", simpleFlowData.getSlotInfo()); + assertEquals(1, simpleFlowData.getCurrentCount()); + assertEquals(2, simpleFlowData.getAverageCount()); + assertEquals(5, simpleFlowData.getSlotCount()); } @Test - public void testGetCount() { + void testGetCount() { SimpleFlowData simpleFlowData = new SimpleFlowData(5, 10000); simpleFlowData.addAndGet(2); simpleFlowData.rotateSlot(); simpleFlowData.addAndGet(3); simpleFlowData.rotateSlot(); simpleFlowData.incrementAndGet(); - Assert.assertEquals("0 0 2 3 1", simpleFlowData.getSlotInfo()); - Assert.assertEquals(2, simpleFlowData.getCount(2)); + assertEquals("0 0 2 3 1", simpleFlowData.getSlotInfo()); + assertEquals(2, simpleFlowData.getCount(2)); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/SimpleIpFlowDataTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/SimpleIpFlowDataTest.java index 5a9a44816e4..5338222f235 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/SimpleIpFlowDataTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/SimpleIpFlowDataTest.java @@ -16,33 +16,34 @@ package com.alibaba.nacos.config.server.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class SimpleIpFlowDataTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SimpleIpFlowDataTest { @Test - public void testIncrementAndGet() { + void testIncrementAndGet() { SimpleIpFlowData simpleIpFlowData = new SimpleIpFlowData(5, 10000); - Assert.assertEquals(1, simpleIpFlowData.incrementAndGet("127.0.0.1")); - Assert.assertEquals(2, simpleIpFlowData.incrementAndGet("127.0.0.1")); - Assert.assertEquals(3, simpleIpFlowData.incrementAndGet("127.0.0.1")); - Assert.assertEquals(1, simpleIpFlowData.incrementAndGet("127.0.0.2")); - Assert.assertEquals(2, simpleIpFlowData.incrementAndGet("127.0.0.2")); + assertEquals(1, simpleIpFlowData.incrementAndGet("127.0.0.1")); + assertEquals(2, simpleIpFlowData.incrementAndGet("127.0.0.1")); + assertEquals(3, simpleIpFlowData.incrementAndGet("127.0.0.1")); + assertEquals(1, simpleIpFlowData.incrementAndGet("127.0.0.2")); + assertEquals(2, simpleIpFlowData.incrementAndGet("127.0.0.2")); } @Test - public void testGetCurrentCount() { + void testGetCurrentCount() { SimpleIpFlowData simpleIpFlowData = new SimpleIpFlowData(3, 10000); simpleIpFlowData.incrementAndGet("127.0.0.1"); simpleIpFlowData.incrementAndGet("127.0.0.1"); simpleIpFlowData.incrementAndGet("127.0.0.1"); - Assert.assertEquals(3, simpleIpFlowData.getCurrentCount("127.0.0.1")); + assertEquals(3, simpleIpFlowData.getCurrentCount("127.0.0.1")); simpleIpFlowData.rotateSlot(); - Assert.assertEquals(0, simpleIpFlowData.getCurrentCount("127.0.0.1")); - Assert.assertEquals(1, simpleIpFlowData.getAverageCount()); + assertEquals(0, simpleIpFlowData.getCurrentCount("127.0.0.1")); + assertEquals(1, simpleIpFlowData.getAverageCount()); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/SimpleReadWriteLockTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/SimpleReadWriteLockTest.java index c6ed47423ed..eebed2b93e7 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/SimpleReadWriteLockTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/SimpleReadWriteLockTest.java @@ -16,18 +16,18 @@ package com.alibaba.nacos.config.server.utils; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.test.context.junit.jupiter.SpringExtension; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -@RunWith(SpringJUnit4ClassRunner.class) -public class SimpleReadWriteLockTest { +@ExtendWith(SpringExtension.class) +class SimpleReadWriteLockTest { @Test - public void testDoubleReadLockByAllReleaseAndWriteLock() { + void testDoubleReadLockByAllReleaseAndWriteLock() { SimpleReadWriteLock lock = new SimpleReadWriteLock(); assertTrue(lock.tryReadLock()); assertTrue(lock.tryReadLock()); @@ -39,14 +39,14 @@ public void testDoubleReadLockByAllReleaseAndWriteLock() { } @Test - public void testAddWriteLock() { + void testAddWriteLock() { SimpleReadWriteLock lock = new SimpleReadWriteLock(); assertTrue(lock.tryWriteLock()); lock.releaseWriteLock(); } @Test - public void testDoubleWriteLock() { + void testDoubleWriteLock() { SimpleReadWriteLock lock = new SimpleReadWriteLock(); assertTrue(lock.tryWriteLock()); @@ -54,7 +54,7 @@ public void testDoubleWriteLock() { } @Test - public void testFirstReadLockThenWriteLock() { + void testFirstReadLockThenWriteLock() { SimpleReadWriteLock lock = new SimpleReadWriteLock(); assertTrue(lock.tryReadLock()); @@ -62,7 +62,7 @@ public void testFirstReadLockThenWriteLock() { } @Test - public void testFirstWriteLockThenReadLock() { + void testFirstWriteLockThenReadLock() { SimpleReadWriteLock lock = new SimpleReadWriteLock(); assertTrue(lock.tryWriteLock()); @@ -70,7 +70,7 @@ public void testFirstWriteLockThenReadLock() { } @Test - public void testDoubleReadLockAndOneReleaseOneFailed() { + void testDoubleReadLockAndOneReleaseOneFailed() { SimpleReadWriteLock lock = new SimpleReadWriteLock(); assertTrue(lock.tryReadLock()); assertTrue(lock.tryReadLock()); diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/SystemConfigTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/SystemConfigTest.java index 21e66d13160..ea291cb2261 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/SystemConfigTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/SystemConfigTest.java @@ -16,15 +16,16 @@ package com.alibaba.nacos.config.server.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class SystemConfigTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SystemConfigTest { @Test - public void testGetHostAddress() { + void testGetHostAddress() { System.setProperty("nacos.server.ip", "127.0.0.1"); - Assert.assertEquals("127.0.0.1", SystemConfig.LOCAL_IP); + assertEquals("127.0.0.1", SystemConfig.LOCAL_IP); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/TimeUtilsTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/TimeUtilsTest.java index ddc6f8817cd..da1723437e5 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/TimeUtilsTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/TimeUtilsTest.java @@ -16,23 +16,24 @@ package com.alibaba.nacos.config.server.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; -public class TimeUtilsTest { +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class TimeUtilsTest { @Test - public void testGetCurrentTimeStr() throws ParseException { + void testGetCurrentTimeStr() throws ParseException { Date date1 = new Date(TimeUtils.getCurrentTime().getTime()); - Assert.assertNotNull(date1.toString()); - + assertNotNull(date1.toString()); + Date date2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(TimeUtils.getCurrentTimeStr()); - Assert.assertNotNull(date2.toString()); + assertNotNull(date2.toString()); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/TimeoutUtilsTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/TimeoutUtilsTest.java index 9a5e512b9d2..e6c987d2df7 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/TimeoutUtilsTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/TimeoutUtilsTest.java @@ -16,36 +16,39 @@ package com.alibaba.nacos.config.server.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class TimeoutUtilsTest { +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 TimeoutUtilsTest { @Test - public void testAddTotalTime() { + void testAddTotalTime() { TimeoutUtils timeoutUtils = new TimeoutUtils(10, 1); timeoutUtils.initLastResetTime(); timeoutUtils.addTotalTime(1); - Assert.assertEquals(1L, timeoutUtils.getTotalTime().get()); + assertEquals(1L, timeoutUtils.getTotalTime().get()); } @Test - public void testIsTimeout() { + void testIsTimeout() { TimeoutUtils timeoutUtils = new TimeoutUtils(10, 1); timeoutUtils.initLastResetTime(); timeoutUtils.addTotalTime(1); - Assert.assertFalse(timeoutUtils.isTimeout()); + assertFalse(timeoutUtils.isTimeout()); timeoutUtils.addTotalTime(10); - Assert.assertTrue(timeoutUtils.isTimeout()); + assertTrue(timeoutUtils.isTimeout()); } @Test - public void testResetTotalTime() { + void testResetTotalTime() { TimeoutUtils timeoutUtils = new TimeoutUtils(10, -1); timeoutUtils.initLastResetTime(); timeoutUtils.addTotalTime(1); - Assert.assertEquals(1L, timeoutUtils.getTotalTime().get()); + assertEquals(1L, timeoutUtils.getTotalTime().get()); timeoutUtils.resetTotalTime(); - Assert.assertEquals(0L, timeoutUtils.getTotalTime().get()); + assertEquals(0L, timeoutUtils.getTotalTime().get()); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/TraceLogUtilTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/TraceLogUtilTest.java index 9444554c020..3fde8014eb2 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/TraceLogUtilTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/TraceLogUtilTest.java @@ -16,19 +16,20 @@ package com.alibaba.nacos.config.server.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; -public class TraceLogUtilTest { +import static org.junit.jupiter.api.Assertions.assertTrue; +class TraceLogUtilTest { + @Test - public void testRequestLog() { - + void testRequestLog() { + Logger requestLog = TraceLogUtil.requestLog; - Assert.assertTrue(requestLog instanceof Logger); - + assertTrue(requestLog instanceof Logger); + Logger pollingLog = TraceLogUtil.pollingLog; - Assert.assertTrue(pollingLog instanceof Logger); + assertTrue(pollingLog instanceof Logger); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/UrlAnalysisUtilsTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/UrlAnalysisUtilsTest.java index 12eb79c0f95..00c1040b810 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/UrlAnalysisUtilsTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/UrlAnalysisUtilsTest.java @@ -16,21 +16,23 @@ package com.alibaba.nacos.config.server.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class UrlAnalysisUtilsTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class UrlAnalysisUtilsTest { @Test - public void testGetContentIdentity() { + void testGetContentIdentity() { String url = "http://127.0.0.1:8080/test?paramA=A¶mB=B"; - Assert.assertEquals("http://127.0.0.1:8080", UrlAnalysisUtils.getContentIdentity(url)); + assertEquals("http://127.0.0.1:8080", UrlAnalysisUtils.getContentIdentity(url)); String url2 = "127.0.0.1:8080/test?paramA=A¶mB=B"; - Assert.assertEquals("127.0.0.1:8080", UrlAnalysisUtils.getContentIdentity(url2)); - + assertEquals("127.0.0.1:8080", UrlAnalysisUtils.getContentIdentity(url2)); + String url3 = ""; - Assert.assertNull(UrlAnalysisUtils.getContentIdentity(url3)); + assertNull(UrlAnalysisUtils.getContentIdentity(url3)); } } diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/YamlParserUtilTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/YamlParserUtilTest.java index c371167fa24..c81bcee170e 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/YamlParserUtilTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/YamlParserUtilTest.java @@ -17,27 +17,29 @@ package com.alibaba.nacos.config.server.utils; import com.alibaba.nacos.config.server.model.ConfigMetadata; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.yaml.snakeyaml.constructor.ConstructorException; import java.util.ArrayList; import java.util.List; -public class YamlParserUtilTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class YamlParserUtilTest { private static final String CONFIG_METADATA_STRING = - "metadata:\n" + "- dataId: testData1\n" + " group: testGroup1\n" + " type: text\n" - + "- appName: testAppName\n" + " dataId: testData2\n" + " desc: test desc\n" - + " group: testGroup2\n" + " type: yaml\n"; + "metadata:\n" + "- dataId: testData1\n" + " group: testGroup1\n" + " type: text\n" + "- appName: testAppName\n" + + " dataId: testData2\n" + " desc: test desc\n" + " group: testGroup2\n" + " type: yaml\n"; private ConfigMetadata.ConfigExportItem item1; private ConfigMetadata.ConfigExportItem item2; - @Before - public void setUp() { + @BeforeEach + void setUp() { item1 = new ConfigMetadata.ConfigExportItem(); item1.setDataId("testData1"); item1.setGroup("testGroup1"); @@ -52,7 +54,7 @@ public void setUp() { } @Test - public void testDumpObject() { + void testDumpObject() { ConfigMetadata configMetadata = new ConfigMetadata(); List configMetadataItems = new ArrayList<>(); configMetadataItems.add(item1); @@ -60,26 +62,28 @@ public void testDumpObject() { configMetadata.setMetadata(configMetadataItems); String parseString = YamlParserUtil.dumpObject(configMetadata); - Assert.assertEquals(CONFIG_METADATA_STRING, parseString); + assertEquals(CONFIG_METADATA_STRING, parseString); } @Test - public void testLoadObject() { + void testLoadObject() { ConfigMetadata configMetadata = YamlParserUtil.loadObject(CONFIG_METADATA_STRING, ConfigMetadata.class); - Assert.assertNotNull(configMetadata); + assertNotNull(configMetadata); List metadataList = configMetadata.getMetadata(); - Assert.assertNotNull(metadataList); - Assert.assertEquals(metadataList.size(), 2); + assertNotNull(metadataList); + assertEquals(2, metadataList.size()); ConfigMetadata.ConfigExportItem configExportItem1 = metadataList.get(0); ConfigMetadata.ConfigExportItem configExportItem2 = metadataList.get(1); - Assert.assertEquals(configExportItem1, item1); - Assert.assertEquals(configExportItem2, item2); + assertEquals(configExportItem1, item1); + assertEquals(configExportItem2, item2); } - @Test(expected = ConstructorException.class) - public void testNotSupportType() { - YamlParserUtil.loadObject("name: test", YamlTest.class); + @Test + void testNotSupportType() { + assertThrows(ConstructorException.class, () -> { + YamlParserUtil.loadObject("name: test", YamlTest.class); + }); } private static class YamlTest { diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/ZipUtilsTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/ZipUtilsTest.java index 50f280983fb..0688ed9278a 100644 --- a/config/src/test/java/com/alibaba/nacos/config/server/utils/ZipUtilsTest.java +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/ZipUtilsTest.java @@ -16,35 +16,37 @@ package com.alibaba.nacos.config.server.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; -public class ZipUtilsTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ZipUtilsTest { @Test - public void testZip() { + void testZip() { List zipItemList = new ArrayList<>(); zipItemList.add(new ZipUtils.ZipItem("test", "content")); byte[] zip = ZipUtils.zip(zipItemList); - Assert.assertTrue(zip != null && zip.length > 0); + assertTrue(zip != null && zip.length > 0); } @Test - public void testUnzip() { + void testUnzip() { List zipItemList = new ArrayList<>(); zipItemList.add(new ZipUtils.ZipItem("test", "content")); byte[] zip = ZipUtils.zip(zipItemList); - Assert.assertTrue(zip != null && zip.length > 0); + assertTrue(zip != null && zip.length > 0); ZipUtils.UnZipResult unZipResult = ZipUtils.unzip(zip); List result = unZipResult.getZipItemList(); - Assert.assertEquals(zipItemList.size(), result.size()); - Assert.assertEquals(zipItemList.get(0).getItemName(), result.get(0).getItemName()); - Assert.assertEquals(zipItemList.get(0).getItemData(), result.get(0).getItemData()); + assertEquals(zipItemList.size(), result.size()); + assertEquals(zipItemList.get(0).getItemName(), result.get(0).getItemName()); + assertEquals(zipItemList.get(0).getItemData(), result.get(0).getItemData()); } } diff --git a/config/src/test/resources/log4j.properties b/config/src/test/resources/log4j.properties index fa72fc136a6..3346a21acd2 100644 --- a/config/src/test/resources/log4j.properties +++ b/config/src/test/resources/log4j.properties @@ -13,7 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # -log4j.rootLogger=DEBUG, ServerDailyRollingFile,stdout +log4j.rootLogger=INFO, ServerDailyRollingFile,stdout log4j.appender.ServerDailyRollingFile=org.apache.log4j.DailyRollingFileAppender log4j.appender.ServerDailyRollingFile.DatePattern='.'yyyy-MM-dd_HH log4j.appender.ServerDailyRollingFile.File=${webapp.root}/WEB-INF/logs/nacos-server.log diff --git a/config/src/test/resources/logback-test.xml b/config/src/test/resources/logback-test.xml new file mode 100644 index 00000000000..e726ab228a6 --- /dev/null +++ b/config/src/test/resources/logback-test.xml @@ -0,0 +1,19 @@ + + + + + \ No newline at end of file diff --git a/consistency/src/test/java/com/alibaba/nacos/consistency/ProtoMessageUtilTest.java b/consistency/src/test/java/com/alibaba/nacos/consistency/ProtoMessageUtilTest.java index c6a69f009f8..c49d6ed2d03 100644 --- a/consistency/src/test/java/com/alibaba/nacos/consistency/ProtoMessageUtilTest.java +++ b/consistency/src/test/java/com/alibaba/nacos/consistency/ProtoMessageUtilTest.java @@ -21,16 +21,16 @@ import com.alibaba.nacos.consistency.entity.ReadRequest; import com.alibaba.nacos.consistency.entity.WriteRequest; import com.google.protobuf.ByteString; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; import java.nio.ByteBuffer; -public class ProtoMessageUtilTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ProtoMessageUtilTest { @Test - public void testProto() throws Exception { + void testProto() throws Exception { WriteRequest request = WriteRequest.newBuilder().setKey("test-proto-new").build(); byte[] bytes = request.toByteArray(); @@ -39,7 +39,7 @@ public void testProto() throws Exception { } @Test - public void testParseReadRequestWithRequestTypeField() { + void testParseReadRequestWithRequestTypeField() { String group = "test"; ByteString data = ByteString.copyFrom("data".getBytes()); ReadRequest testCase = ReadRequest.newBuilder().setGroup(group).setData(data).build(); @@ -49,8 +49,8 @@ public void testParseReadRequestWithRequestTypeField() { requestTypeFieldBytes[1] = ProtoMessageUtil.REQUEST_TYPE_READ; byte[] dataBytes = testCase.toByteArray(); - ByteBuffer byteBuffer = (ByteBuffer) ByteBuffer.allocate(requestTypeFieldBytes.length + dataBytes.length) - .put(requestTypeFieldBytes).put(dataBytes).position(0); + ByteBuffer byteBuffer = (ByteBuffer) ByteBuffer.allocate(requestTypeFieldBytes.length + dataBytes.length).put(requestTypeFieldBytes) + .put(dataBytes).position(0); Object actual = ProtoMessageUtil.parse(byteBuffer.array()); assertEquals(ReadRequest.class, testCase.getClass()); @@ -59,7 +59,7 @@ public void testParseReadRequestWithRequestTypeField() { } @Test - public void testParseWriteRequestWithRequestTypeField() { + void testParseWriteRequestWithRequestTypeField() { String group = "test"; ByteString data = ByteString.copyFrom("data".getBytes()); WriteRequest testCase = WriteRequest.newBuilder().setGroup(group).setData(data).build(); @@ -69,8 +69,8 @@ public void testParseWriteRequestWithRequestTypeField() { requestTypeFieldBytes[1] = ProtoMessageUtil.REQUEST_TYPE_WRITE; byte[] dataBytes = testCase.toByteArray(); - ByteBuffer byteBuffer = (ByteBuffer) ByteBuffer.allocate(requestTypeFieldBytes.length + dataBytes.length) - .put(requestTypeFieldBytes).put(dataBytes).position(0); + ByteBuffer byteBuffer = (ByteBuffer) ByteBuffer.allocate(requestTypeFieldBytes.length + dataBytes.length).put(requestTypeFieldBytes) + .put(dataBytes).position(0); Object actual = ProtoMessageUtil.parse(byteBuffer.array()); assertEquals(WriteRequest.class, testCase.getClass()); @@ -79,7 +79,7 @@ public void testParseWriteRequestWithRequestTypeField() { } @Test - public void testParseReadRequest() { + void testParseReadRequest() { String group = "test"; ByteString data = ByteString.copyFrom("data".getBytes()); ReadRequest testCase = ReadRequest.newBuilder().setGroup(group).setData(data).build(); @@ -90,7 +90,7 @@ public void testParseReadRequest() { } @Test - public void testParseWriteRequest() { + void testParseWriteRequest() { String group = "test"; ByteString data = ByteString.copyFrom("data".getBytes()); WriteRequest testCase = WriteRequest.newBuilder().setGroup(group).setData(data).build(); @@ -101,7 +101,7 @@ public void testParseWriteRequest() { } @Test - public void testConvertToReadRequest() { + void testConvertToReadRequest() { ByteString data = ByteString.copyFrom("data".getBytes()); String group = "test"; @@ -116,10 +116,9 @@ public void testConvertToReadRequest() { } @Test - public void testConvertToWriteRequest() { + void testConvertToWriteRequest() { ByteString data = ByteString.copyFrom("data".getBytes()); - Log log = Log.newBuilder().setKey("key").setGroup("group").setData(data).setOperation("o") - .putExtendInfo("k", "v").build(); + Log log = Log.newBuilder().setKey("key").setGroup("group").setData(data).setOperation("o").putExtendInfo("k", "v").build(); WriteRequest writeRequest = ProtoMessageUtil.convertToWriteRequest(log); assertEquals(1, writeRequest.getExtendInfoCount()); diff --git a/consistency/src/test/java/com/alibaba/nacos/consistency/ProtocolMetaDataTest.java b/consistency/src/test/java/com/alibaba/nacos/consistency/ProtocolMetaDataTest.java index 9c5dc48d9f9..84011e95052 100644 --- a/consistency/src/test/java/com/alibaba/nacos/consistency/ProtocolMetaDataTest.java +++ b/consistency/src/test/java/com/alibaba/nacos/consistency/ProtocolMetaDataTest.java @@ -17,8 +17,7 @@ package com.alibaba.nacos.consistency; import com.alibaba.nacos.common.utils.JacksonUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Date; import java.util.HashMap; @@ -27,10 +26,12 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -public class ProtocolMetaDataTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ProtocolMetaDataTest { @Test - public void testProtocolMetaData() throws Exception { + void testProtocolMetaData() throws Exception { Map> map = new HashMap<>(); Map data = new HashMap<>(); data.put("test-1", new Date()); @@ -68,7 +69,7 @@ public void testProtocolMetaData() throws Exception { latch.await(10_000L, TimeUnit.MILLISECONDS); - Assert.assertEquals(2, count.get()); + assertEquals(2, count.get()); } diff --git a/consistency/src/test/java/com/alibaba/nacos/consistency/SerializeFactoryTest.java b/consistency/src/test/java/com/alibaba/nacos/consistency/SerializeFactoryTest.java index d3edc7517b8..0e0025f9293 100644 --- a/consistency/src/test/java/com/alibaba/nacos/consistency/SerializeFactoryTest.java +++ b/consistency/src/test/java/com/alibaba/nacos/consistency/SerializeFactoryTest.java @@ -17,8 +17,7 @@ package com.alibaba.nacos.consistency; import com.alibaba.nacos.consistency.serialize.JacksonSerializer; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.HashMap; @@ -27,10 +26,13 @@ import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; -public class SerializeFactoryTest { +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SerializeFactoryTest { @Test - public void testListSerialize() { + void testListSerialize() { Serializer serializer = SerializeFactory.getDefault(); List logsList = new ArrayList<>(); @@ -38,27 +40,27 @@ public void testListSerialize() { logsList.add(i); } byte[] data = serializer.serialize(logsList); - Assert.assertNotEquals(0, data.length); + assertNotEquals(0, data.length); ArrayList list = serializer.deserialize(data, ArrayList.class); System.out.println(list); } @Test - public void testMapSerialize() { + void testMapSerialize() { Serializer serializer = SerializeFactory.getDefault(); Map logsMap = new HashMap<>(); for (int i = 0; i < 4; i++) { logsMap.put(i, i); } byte[] data = serializer.serialize(logsMap); - Assert.assertNotEquals(0, data.length); + assertNotEquals(0, data.length); Map result = serializer.deserialize(data, HashMap.class); System.out.println(result); } @Test - public void testSetSerialize() { + void testSetSerialize() { Serializer serializer = SerializeFactory.getDefault(); Set logsMap = new CopyOnWriteArraySet<>(); for (int i = 0; i < 4; i++) { @@ -66,14 +68,14 @@ public void testSetSerialize() { } byte[] data = serializer.serialize(logsMap); - Assert.assertNotEquals(0, data.length); + assertNotEquals(0, data.length); Set result = serializer.deserialize(data, CopyOnWriteArraySet.class); System.out.println(result); } @Test - public void testGetSerializer() { + void testGetSerializer() { Serializer serializer = SerializeFactory.getSerializer("JSON"); - Assert.assertTrue(serializer instanceof JacksonSerializer); + assertTrue(serializer instanceof JacksonSerializer); } } diff --git a/consistency/src/test/java/com/alibaba/nacos/consistency/serialize/HessianSerializerTest.java b/consistency/src/test/java/com/alibaba/nacos/consistency/serialize/HessianSerializerTest.java index 4b224444d8e..f03b3c14663 100644 --- a/consistency/src/test/java/com/alibaba/nacos/consistency/serialize/HessianSerializerTest.java +++ b/consistency/src/test/java/com/alibaba/nacos/consistency/serialize/HessianSerializerTest.java @@ -19,66 +19,69 @@ import com.alibaba.nacos.api.exception.runtime.NacosDeserializationException; import org.apache.http.HttpException; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.Serializable; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + /** * {@link HessianSerializer} unit test. * * @author Chenhao26 * @date 2022-08-13 */ -public class HessianSerializerTest { +class HessianSerializerTest { private HessianSerializer hessianSerializer; - @Before - public void setUp() { + @BeforeEach + void setUp() { hessianSerializer = new HessianSerializer(); } @Test - public void testSerializerAndDeserialize() { + void testSerializerAndDeserialize() { String data = "xxx"; byte[] bytes = hessianSerializer.serialize(data); try { hessianSerializer.deserialize(bytes); } catch (Exception e) { - Assert.assertTrue(e instanceof RuntimeException); + assertTrue(e instanceof RuntimeException); } String res1 = hessianSerializer.deserialize(bytes, String.class); - Assert.assertEquals(data, res1); + assertEquals(data, res1); String res2 = hessianSerializer.deserialize(bytes, "java.lang.String"); - Assert.assertEquals(data, res2); + assertEquals(data, res2); } @Test - public void testSerializerAndDeserializeForNotAllowClass() { + void testSerializerAndDeserializeForNotAllowClass() { Serializable data = new HttpException(); byte[] bytes = hessianSerializer.serialize(data); try { HttpException res = hessianSerializer.deserialize(bytes); - Assert.fail("deserialize success which is not expected"); + fail("deserialize success which is not expected"); } catch (Exception e) { - Assert.assertTrue(e instanceof ClassCastException); + assertTrue(e instanceof ClassCastException); } try { HttpException res1 = hessianSerializer.deserialize(bytes, HttpException.class); } catch (Exception e) { - Assert.assertTrue(e instanceof NacosDeserializationException); + assertTrue(e instanceof NacosDeserializationException); } } @Test - public void testName() { - Assert.assertEquals("Hessian", hessianSerializer.name()); + void testName() { + assertEquals("Hessian", hessianSerializer.name()); } } diff --git a/consistency/src/test/java/com/alibaba/nacos/consistency/serialize/JacksonSerializerTest.java b/consistency/src/test/java/com/alibaba/nacos/consistency/serialize/JacksonSerializerTest.java index 2eda593395a..90c9ac15785 100644 --- a/consistency/src/test/java/com/alibaba/nacos/consistency/serialize/JacksonSerializerTest.java +++ b/consistency/src/test/java/com/alibaba/nacos/consistency/serialize/JacksonSerializerTest.java @@ -17,9 +17,11 @@ package com.alibaba.nacos.consistency.serialize; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link JacksonSerializer} unit test. @@ -27,35 +29,35 @@ * @author chenglu * @date 2021-07-27 18:32 */ -public class JacksonSerializerTest { +class JacksonSerializerTest { private JacksonSerializer jacksonSerializer; - @Before - public void setUp() { + @BeforeEach + void setUp() { jacksonSerializer = new JacksonSerializer(); } @Test - public void testSerializerAndDeserialize() { + void testSerializerAndDeserialize() { String data = "xxx"; byte[] bytes = jacksonSerializer.serialize(data); try { jacksonSerializer.deserialize(bytes); } catch (Exception e) { - Assert.assertTrue(e instanceof UnsupportedOperationException); + assertTrue(e instanceof UnsupportedOperationException); } String res1 = jacksonSerializer.deserialize(bytes, String.class); - Assert.assertEquals(data, res1); + assertEquals(data, res1); String res2 = jacksonSerializer.deserialize(bytes, "java.lang.String"); - Assert.assertEquals(data, res2); + assertEquals(data, res2); } @Test - public void testName() { - Assert.assertEquals("JSON", jacksonSerializer.name()); + void testName() { + assertEquals("JSON", jacksonSerializer.name()); } } diff --git a/consistency/src/test/java/com/alibaba/nacos/consistency/snapshot/LocalFileMetaTest.java b/consistency/src/test/java/com/alibaba/nacos/consistency/snapshot/LocalFileMetaTest.java index 09bb810a91f..50599db409c 100644 --- a/consistency/src/test/java/com/alibaba/nacos/consistency/snapshot/LocalFileMetaTest.java +++ b/consistency/src/test/java/com/alibaba/nacos/consistency/snapshot/LocalFileMetaTest.java @@ -17,9 +17,10 @@ package com.alibaba.nacos.consistency.snapshot; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * {@link LocalFileMeta} unit test. @@ -27,18 +28,18 @@ * @author chenglu * @date 2021-07-27 18:43 */ -public class LocalFileMetaTest { +class LocalFileMetaTest { private LocalFileMeta fileMeta; - @Before - public void setUp() { + @BeforeEach + void setUp() { fileMeta = new LocalFileMeta(); } @Test - public void testAppendAndGet() { + void testAppendAndGet() { fileMeta.append("key", "value"); - Assert.assertEquals("value", fileMeta.get("key")); + assertEquals("value", fileMeta.get("key")); } } diff --git a/consistency/src/test/java/com/alibaba/nacos/consistency/snapshot/ReaderTest.java b/consistency/src/test/java/com/alibaba/nacos/consistency/snapshot/ReaderTest.java index acce96d4cba..e5b44333ab4 100644 --- a/consistency/src/test/java/com/alibaba/nacos/consistency/snapshot/ReaderTest.java +++ b/consistency/src/test/java/com/alibaba/nacos/consistency/snapshot/ReaderTest.java @@ -17,26 +17,27 @@ package com.alibaba.nacos.consistency.snapshot; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; import java.util.Properties; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * {@link Reader} unit test. * * @author chenglu * @date 2021-07-27 18:46 */ -public class ReaderTest { +class ReaderTest { private Reader reader; - @Before - public void setUp() { + @BeforeEach + void setUp() { Map map = new HashMap<>(2); Properties properties = new Properties(); properties.put("k", "v"); @@ -45,11 +46,11 @@ public void setUp() { } @Test - public void test() { - Assert.assertEquals("test", reader.getPath()); + void test() { + assertEquals("test", reader.getPath()); - Assert.assertEquals(1, reader.listFiles().size()); + assertEquals(1, reader.listFiles().size()); - Assert.assertEquals("v", reader.getFileMeta("a").getFileMeta().getProperty("k")); + assertEquals("v", reader.getFileMeta("a").getFileMeta().getProperty("k")); } } diff --git a/consistency/src/test/java/com/alibaba/nacos/consistency/snapshot/WriterTest.java b/consistency/src/test/java/com/alibaba/nacos/consistency/snapshot/WriterTest.java index 21cf399628c..0791b78078b 100644 --- a/consistency/src/test/java/com/alibaba/nacos/consistency/snapshot/WriterTest.java +++ b/consistency/src/test/java/com/alibaba/nacos/consistency/snapshot/WriterTest.java @@ -17,9 +17,11 @@ package com.alibaba.nacos.consistency.snapshot; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link Writer} unit test. @@ -27,27 +29,27 @@ * @author chenglu * @date 2021-07-28 18:50 */ -public class WriterTest { +class WriterTest { private Writer writer; - @Before - public void setUp() { + @BeforeEach + void setUp() { writer = new Writer("test"); } @Test - public void test() { - Assert.assertEquals("test", writer.getPath()); - - Assert.assertTrue(writer.addFile("a")); + void test() { + assertEquals("test", writer.getPath()); + + assertTrue(writer.addFile("a")); - Assert.assertTrue(writer.addFile("b", new LocalFileMeta())); + assertTrue(writer.addFile("b", new LocalFileMeta())); - Assert.assertEquals(2, writer.listFiles().size()); + assertEquals(2, writer.listFiles().size()); - Assert.assertTrue(writer.removeFile("a")); + assertTrue(writer.removeFile("a")); - Assert.assertEquals(1, writer.listFiles().size()); + assertEquals(1, writer.listFiles().size()); } } diff --git a/console-ui/README.md b/console-ui/README.md index 2ce5277c16d..236227a6413 100644 --- a/console-ui/README.md +++ b/console-ui/README.md @@ -13,8 +13,7 @@ yarn --registry=https://registry.npm.taobao.org NodeJS提供了一些安装程序,都可以在[nodejs.org](https://nodejs.org/download/release/) 这里下载并安装。mac系统选择.pkg结尾的文件下载安装。 注意node版本号过高可能导致 `npm install` 时失败,建议版本: -- node:v8.16.0 -- npm:6.4.1 +- node:v14.20.1 ## 安装依赖 ```sh diff --git a/console-ui/package.json b/console-ui/package.json index 5f61f4317a8..10c6fd6a08e 100644 --- a/console-ui/package.json +++ b/console-ui/package.json @@ -69,6 +69,7 @@ "@alifd/theme-design-pro": "0.x", "@iarna/toml": "^3.0.0", "axios": "^0.21.1", + "core-js": "^3.6.4", "js-yaml": "^4.1.0", "moment": "^2.23.0", "prop-types": "^15.6.2", @@ -81,7 +82,6 @@ "react-router-dom": "^5.1.2", "react-router-redux": "^4.0.8", "redux": "^4.0.5", - "redux-thunk": "^2.3.0", - "core-js": "^3.6.4" + "redux-thunk": "^2.3.0" } } diff --git a/console-ui/src/components/NameSpaceList/NameSpaceList.js b/console-ui/src/components/NameSpaceList/NameSpaceList.js index 825337cfd53..0b2355a4972 100644 --- a/console-ui/src/components/NameSpaceList/NameSpaceList.js +++ b/console-ui/src/components/NameSpaceList/NameSpaceList.js @@ -16,10 +16,11 @@ import React from 'react'; import PropTypes from 'prop-types'; -import { ConfigProvider, Dialog } from '@alifd/next'; +import { ConfigProvider, Dialog, Select } from '@alifd/next'; import { getParams, setParams, request } from '../../globalLib'; import './index.scss'; +import { NAME_SHOW } from '../../constants'; /** * 命名空间列表 @@ -42,6 +43,7 @@ class NameSpaceList extends React.Component { this.state = { nownamespace: window.nownamespace || this._namespace || '', namespaceList: window.namespaceList || [], + nameShow: localStorage.getItem(NAME_SHOW), // namespaceShowName: window.namespaceShowName || this._namespaceShowName || '', // _dingdingLink: "", // _forumLink: "" @@ -100,6 +102,11 @@ class NameSpaceList extends React.Component { this.props.setNowNameSpace && this.props.setNowNameSpace(nsName, ns, nsDesc); } + changeName(...value) { + let space = value[2]; + this.changeNameSpace(space.namespace, space.namespaceShowName, space.namespaceDesc); + } + calleeParent(needclean = false) { this.props.namespaceCallBack && this.props.namespaceCallBack(needclean); } @@ -166,7 +173,29 @@ class NameSpaceList extends React.Component { } rendernamespace(namespaceList) { - const { nownamespace } = this.state; // 获得当前namespace + const { nownamespace, nameShow } = this.state; // 获得当前namespace + if (nameShow && nameShow === 'select') { + let de = { + value: nownamespace, + }; + namespaceList.forEach(obj => { + obj.label = obj.namespaceShowName + ' ' + (obj.namespaceDesc ? obj.namespaceDesc : ''); + obj.value = obj.namespace; + if (obj.value !== undefined && obj.value === de.value) { + de = obj; + } + }); + return ( + - + { @@ -259,6 +261,8 @@ class ConfigEditor extends React.Component { if (configTags.length > 0) { payload.config_tags = configTags.join(','); } + // #12046 console-ui should not offer encryptedDataKey field to API + payload.encryptedDataKey = ''; const stringify = require('qs/lib/stringify'); this.setState({ loading: true }); return request({ diff --git a/console-ui/src/pages/ConfigurationManagement/ConfigRollback/ConfigRollback.js b/console-ui/src/pages/ConfigurationManagement/ConfigRollback/ConfigRollback.js index 4860ee1bb9d..9d058df05e5 100644 --- a/console-ui/src/pages/ConfigurationManagement/ConfigRollback/ConfigRollback.js +++ b/console-ui/src/pages/ConfigurationManagement/ConfigRollback/ConfigRollback.js @@ -173,7 +173,7 @@ class ConfigRollback extends React.Component { const typeMap = { U: locale.update, I: locale.insert, - D: locale.deleteAction, + D: locale.rollbackDelete, }; return typeMap[type]; } diff --git a/console-ui/src/pages/ConfigurationManagement/ConfigurationManagement/ConfigurationManagement.js b/console-ui/src/pages/ConfigurationManagement/ConfigurationManagement/ConfigurationManagement.js index 9db70c8481a..9b1dc2bbdd3 100644 --- a/console-ui/src/pages/ConfigurationManagement/ConfigurationManagement/ConfigurationManagement.js +++ b/console-ui/src/pages/ConfigurationManagement/ConfigurationManagement/ConfigurationManagement.js @@ -28,38 +28,52 @@ import { Icon, Input, Menu, + MenuButton, + Message, Pagination, Select, + Switch, Table, Upload, - Message, - MenuButton, - Box, - Switch, } from '@alifd/next'; import BatchHandle from 'components/BatchHandle'; import RegionGroup from 'components/RegionGroup'; import ShowCodeing from 'components/ShowCodeing'; import DeleteDialog from 'components/DeleteDialog'; import DashboardCard from './DashboardCard'; -import { getParams, setParams, request } from '@/globalLib'; -import { goLogin } from '../../../globalLib'; -import { connect } from 'react-redux'; -import { getConfigs, getConfigsV2 } from '../../../reducers/configuration'; +import {getParams, request, setParams} from '@/globalLib'; +import {goLogin} from '../../../globalLib'; +import {connect} from 'react-redux'; +import {getConfigs, getConfigsV2} from '../../../reducers/configuration'; import PageTitle from '../../../components/PageTitle'; import QueryResult from '../../../components/QueryResult'; import './index.scss'; -import { LANGUAGE_KEY, GLOBAL_PAGE_SIZE_LIST, LOGINPAGE_ENABLED } from '../../../constants'; +import { + GLOBAL_PAGE_SIZE_LIST, + LANGUAGE_KEY, + LOGINPAGE_ENABLED +} from '../../../constants'; +import TotalRender from '../../../components/Page/TotalRender'; -const { Item } = MenuButton; -const { Panel } = Collapse; +const {Item} = MenuButton; +const {Panel} = Collapse; const configsTableSelected = new Map(); +const typeMapping = [ + {value: 'text', label: 'TEXT'}, + {value: 'json', label: 'JSON'}, + {value: 'xml', label: 'XML'}, + {value: 'yaml', label: 'YAML'}, + {value: 'html', label: 'HTML'}, + {value: 'properties', label: 'Properties'}, + {value: 'toml', label: 'TOML'}, +]; + @connect( - state => ({ - configurations: state.configuration.configurations, - }), - { getConfigs, getConfigsV2 } + state => ({ + configurations: state.configuration.configurations, + }), + {getConfigs, getConfigsV2} ) @ConfigProvider.config class ConfigurationManagement extends React.Component { @@ -100,7 +114,10 @@ class ConfigurationManagement extends React.Component { group: this.group, appName: this.appName, config_detail: getParams('configDetail') || '', - config_tags: getParams('configTags') ? getParams('configTags').split(',') : [], + config_tags: getParams('configTags') ? getParams('configTags').split(',') + : [], + types: getParams('types') ? getParams('types').split( + ',') : [], tagLst: getParams('tagList') ? getParams('tagList').split(',') : [], selectValue: [], loading: false, @@ -135,7 +152,7 @@ class ConfigurationManagement extends React.Component { } componentDidMount() { - const { locale = {} } = this.props; + const {locale = {}} = this.props; // this.getGroup(); this.setIsCn(); if (window._getLink && window._getLink('isCn') === 'true') { @@ -147,19 +164,20 @@ class ConfigurationManagement extends React.Component { width: '60%', }, content: ( -
    -
    - {locale.ad} - {/* eslint-disable */} - - {locale.questionnaire2} - -
    -
    - {locale.noLongerDisplay4} - +
    +
    + {locale.ad} + {/* eslint-disable */} + + {locale.questionnaire2} + +
    +
    + {locale.noLongerDisplay4} + +
    -
    ), }); } @@ -168,7 +186,7 @@ class ConfigurationManagement extends React.Component { } setIsCn() { - this.setState({ isCn: localStorage.getItem(LANGUAGE_KEY) === 'zh-CN' }); + this.setState({isCn: localStorage.getItem(LANGUAGE_KEY) === 'zh-CN'}); } toggleShowQuestionnaire(value) { @@ -194,17 +212,19 @@ class ConfigurationManagement extends React.Component { switch (url) { case '/historyRollback': url = `${url}?historyServerId=${this.serverId || ''}&historyDataId=${ - record.dataId + record.dataId }&historyGroup=${record.group}&namespace=${this.tenant}`; break; case '/listeningToQuery': - url = `${url}?listeningServerId=${this.serverId || ''}&listeningDataId=${ - record.dataId + url = `${url}?listeningServerId=${this.serverId + || ''}&listeningDataId=${ + record.dataId }&listeningGroup=${record.group}&namespace=${this.tenant}`; break; case '/pushTrajectory': - url = `${url}?serverId=${this.serverId || ''}&dataId=${record.dataId}&group=${ - record.group + url = `${url}?serverId=${this.serverId + || ''}&dataId=${record.dataId}&group=${ + record.group }&namespace=${this.tenant}`; break; default: @@ -239,9 +259,9 @@ class ConfigurationManagement extends React.Component { } this.getData(); configsTableSelected.clear(); - const { rowSelection } = this.state; + const {rowSelection} = this.state; rowSelection.selectedRowKeys = []; - this.setState({ rowSelection }); + this.setState({rowSelection}); } changeParamsBySearchType(params) { @@ -264,7 +284,7 @@ class ConfigurationManagement extends React.Component { if (this.state.loading) { return; } - const { locale = {}, configurations = {} } = this.props; + const {locale = {}, configurations = {}} = this.props; this.tenant = getParams('namespace') || ''; // 为当前实例保存tenant参数 this.serverId = getParams('serverId') || ''; const prePageNo = getParams('pageNo'); @@ -279,11 +299,12 @@ class ConfigurationManagement extends React.Component { pageNo: prePageNo ? prePageNo : pageNo, pageSize: prePageSize ? prePageSize : this.state.pageSize, tenant: this.tenant, + types: this.state.types.join(','), }; setParams('pageSize', null); setParams('pageNo', null); this.changeParamsBySearchType(params); - this.setState({ loading: true }); + this.setState({loading: true}); let props = null; if (this.state.config_detail && this.state.config_detail !== '') { if (this.state.defaultFuzzySearch) { @@ -296,30 +317,30 @@ class ConfigurationManagement extends React.Component { props = this.props.getConfigs(params); } props - .then(() => + .then(() => this.setState({ loading: false, selectedRecord: [], selectedKeys: [], tenant: this.tenant, }) - ) - .catch(res => { - configurations.pageItems = []; - configurations.totalCount = 0; - this.setState({ - loading: false, - }); - if (res && [401, 403].includes(res.status)) { - Dialog.alert({ - title: locale.authFail, - content: locale.getNamespace403.replace( + ) + .catch(res => { + configurations.pageItems = []; + configurations.totalCount = 0; + this.setState({ + loading: false, + }); + if (res && [401, 403].includes(res.status)) { + Dialog.alert({ + title: locale.authFail, + content: locale.getNamespace403.replace( '${namespaceName}', this.state.nownamespace_name - ), - }); - } - }); + ), + }); + } + }); } chooseNav(record, key) { @@ -339,26 +360,29 @@ class ConfigurationManagement extends React.Component { } removeConfig(record) { - const { locale = {} } = this.props; + const {locale = {}} = this.props; const self = this; Dialog.confirm({ title: locale.removeConfiguration, content: ( -
    -

    {locale.sureDelete}

    -

    - Data ID - {record.dataId} -

    -

    - Group - {record.group} -

    -

    - {locale.environment} - {self.serverId || ''} -

    -
    +
    +

    {locale.sureDelete}

    +

    + Data ID + {record.dataId} +

    +

    + Group + {record.group} +

    +

    + {locale.environment} + {self.serverId || ''} +

    +
    ), onOk: () => { const url = `v1/cs/configs?dataId=${record.dataId}&group=${record.group}`; @@ -391,56 +415,61 @@ class ConfigurationManagement extends React.Component { } renderCol(value, index, record) { - const { locale = {} } = this.props; + const {locale = {}} = this.props; return ( -
    - - {locale.details} - - | - - {locale.sampleCode} - - | - - {locale.edit} - - | - - {locale.deleteAction} - - | +
    + + {locale.details} + + | + + {locale.sampleCode} + + | + + {locale.edit} + + | + + {locale.deleteAction} + + | - - - - } - triggerType={'click'} - > - - {locale.version} - {locale.listenerQuery} - - -
    + + + + } + triggerType={'click'} + > + + {locale.version} + {locale.listenerQuery} + + +
    ); } changePage(value, e) { this.setState( - { - isPageEnter: e && e.keyCode && e.keyCode === 13, - currentPage: value, - }, - () => this.getData(value, false) + { + isPageEnter: e && e.keyCode && e.keyCode === 13, + currentPage: value, + }, + () => this.getData(value, false) ); } onChangeSort(dataIndex, order) { - const { configurations = {} } = this.props; - configurations.pageItems.sort(function(a, b) { + const {configurations = {}} = this.props; + configurations.pageItems.sort(function (a, b) { if (order === 'asc') { return (a[dataIndex] + '').localeCompare(b[dataIndex] + ''); } @@ -450,7 +479,7 @@ class ConfigurationManagement extends React.Component { } handlePageSizeChange(pageSize) { - this.setState({ pageSize }, () => this.changePage(1)); + this.setState({pageSize}, () => this.changePage(1)); } setConfigDetail(value) { @@ -507,9 +536,10 @@ class ConfigurationManagement extends React.Component { this.serverId = getParams('serverId') || 'center'; this.tenant = getParams('namespace') || ''; // 为当前实例保存tenant参数 this.props.history.push( - `/newconfig?serverId=${this.serverId || ''}&namespace=${this.tenant}&edasAppName=${ - this.edasAppName - }&edasAppId=${this.edasAppId}&searchDataId=${this.dataId}&searchGroup=${this.group}` + `/newconfig?serverId=${this.serverId + || ''}&namespace=${this.tenant}&edasAppName=${ + this.edasAppName + }&edasAppId=${this.edasAppId}&searchDataId=${this.dataId}&searchGroup=${this.group}` ); } @@ -526,11 +556,12 @@ class ConfigurationManagement extends React.Component { this.tenant = getParams('namespace') || ''; // 为当前实例保存tenant参数 // 点击详情到另一个页面, 返回时候要保留原来的搜索条件 比如: record.dataId为详情的, this.dataId为搜索条件的. this.props.history.push( - `/configdetail?serverId=${this.serverId || ''}&dataId=${record.dataId}&group=${ - record.group - }&namespace=${this.tenant}&edasAppName=${this.edasAppName}&searchDataId=${ - this.dataId - }&searchGroup=${this.group}&pageSize=${this.pageSize}&pageNo=${this.pageNo}` + `/configdetail?serverId=${this.serverId + || ''}&dataId=${record.dataId}&group=${ + record.group + }&namespace=${this.tenant}&edasAppName=${this.edasAppName}&searchDataId=${ + this.dataId + }&searchGroup=${this.group}&pageSize=${this.pageSize}&pageNo=${this.pageNo}` ); } @@ -538,20 +569,38 @@ class ConfigurationManagement extends React.Component { this.serverId = getParams('serverId') || 'center'; this.tenant = getParams('namespace') || ''; // 为当前实例保存tenant参数 this.props.history.push( - `/configeditor?serverId=${this.serverId || ''}&dataId=${record.dataId}&group=${ - record.group - }&namespace=${this.tenant}&edasAppName=${this.edasAppName}&edasAppId=${ - this.edasAppId - }&searchDataId=${this.dataId}&searchGroup=${this.group}&pageSize=${this.pageSize}&pageNo=${ - this.pageNo - }` + `/configeditor?serverId=${this.serverId + || ''}&dataId=${record.dataId}&group=${ + record.group + }&namespace=${this.tenant}&edasAppName=${this.edasAppName}&edasAppId=${ + this.edasAppId + }&searchDataId=${this.dataId}&searchGroup=${this.group}&pageSize=${this.pageSize}&pageNo=${ + this.pageNo + }` ); } + setConfigTypes(value) { + this.setState({ + types: value || [], + }); + if (!value) { + setParams('types', ''); + } else { + setParams('types', value.join(',')); + } + } + + getLabelFromValue(labelMapping, value) { + const mapping = labelMapping.find(item => item.value === value); + return mapping ? mapping.label : value; + } + clear = () => { this.setAppName(''); this.setConfigTags([]); this.setConfigDetail(''); + this.setConfigTypes([]); }; changeAdvancedQuery = () => { @@ -566,18 +615,19 @@ class ConfigurationManagement extends React.Component { openUri(url, params) { window.open( - [ - url, - Object.keys(params) + [ + url, + Object.keys(params) .map(key => `${key}=${params[key]}`) .join('&'), - ].join('?') + ].join('?') ); } exportData() { - const { group, appName, dataId, openUri } = this; - const { accessToken = '', username = '' } = JSON.parse(localStorage.token || '{}'); + const {group, appName, dataId, openUri} = this; + const {accessToken = '', username = ''} = JSON.parse( + localStorage.token || '{}'); openUri('v1/cs/configs', { export: 'true', tenant: getParams('namespace'), @@ -591,8 +641,9 @@ class ConfigurationManagement extends React.Component { } exportDataNew() { - const { group, appName, dataId, openUri } = this; - const { accessToken = '', username = '' } = JSON.parse(localStorage.token || '{}'); + const {group, appName, dataId, openUri} = this; + const {accessToken = '', username = ''} = JSON.parse( + localStorage.token || '{}'); openUri('v1/cs/configs', { exportV2: 'true', tenant: getParams('namespace'), @@ -607,8 +658,9 @@ class ConfigurationManagement extends React.Component { exportSelectedData(newVersion) { const ids = []; - const { locale = {} } = this.props; - const { accessToken = '', username = '' } = JSON.parse(localStorage.token || '{}'); + const {locale = {}} = this.props; + const {accessToken = '', username = ''} = JSON.parse( + localStorage.token || '{}'); if (!configsTableSelected.size) { Dialog.alert({ title: locale.exportSelectedAlertTitle, @@ -641,7 +693,7 @@ class ConfigurationManagement extends React.Component { } multipleSelectionDeletion() { - const { locale = {} } = this.props; + const {locale = {}} = this.props; const self = this; if (configsTableSelected.size === 0) { Dialog.alert({ @@ -659,19 +711,20 @@ class ConfigurationManagement extends React.Component { Dialog.confirm({ title: locale.removeConfiguration, content: ( -
    -

    {locale.sureDelete}

    - - - -
    -
    +
    +

    {locale.sureDelete}

    + + + +
    +
    ), onOk: () => { const url = - `v1/cs/configs?delType=ids&ids=${Array.from(configsTableSelected.keys()).join( - ',' - )}&tenant=` + self.state.nownamespace_id; + `v1/cs/configs?delType=ids&ids=${Array.from( + configsTableSelected.keys()).join( + ',' + )}&tenant=` + self.state.nownamespace_id; request({ url, type: 'delete', @@ -686,7 +739,7 @@ class ConfigurationManagement extends React.Component { } cloneSelectedDataConfirm() { - const { locale = {} } = this.props; + const {locale = {}} = this.props; const self = this; self.field.setValue('sameConfigPolicy', 'ABORT'); self.field.setValue('cloneTargetSpace', undefined); @@ -714,7 +767,10 @@ class ConfigurationManagement extends React.Component { let namespaceSelectData = []; let namespaceSelecItemRender = item => { if (item.isCurrent) { - return {item.label}; + return {item.label}; } else { return {item.label}; } @@ -743,160 +799,192 @@ class ConfigurationManagement extends React.Component { dataItem.dataId = value.dataId; dataItem.group = value.group; editableTableData.push(dataItem); - configsTableSelectedDeepCopyed.set(key, JSON.parse(JSON.stringify(value))); + configsTableSelectedDeepCopyed.set(key, + JSON.parse(JSON.stringify(value))); }); let editableTableOnBlur = (record, type, e) => { if (type === 1) { - configsTableSelectedDeepCopyed.get(record.id).dataId = e.target.value; + configsTableSelectedDeepCopyed.get( + record.id).dataId = e.target.value; } else { - configsTableSelectedDeepCopyed.get(record.id).group = e.target.value; + configsTableSelectedDeepCopyed.get( + record.id).group = e.target.value; } }; let renderEditableTableCellDataId = (value, index, record) => ( - + ); let renderEditableTableCellGroup = (value, index, record) => ( - + ); const cloneConfirm = Dialog.confirm({ title: locale.cloningConfiguration, footer: false, content: ( - <> -
    - {locale.source} - {self.state.nownamespace_name} |{' '} - {self.state.nownamespace_id} -
    -
    - {locale.configurationNumber} - {configsTableSelected.size} - {locale.selectedEntry} -
    -
    - {'*'} - {locale.target} - { + if (value) { + document.getElementById( + 'cloneTargetSpaceSelectErr').style.display = 'none'; + self.field.setValue('cloneTargetSpace', value); + } + }} + /> +
    + {locale.selectNamespace} -
    -
    - {locale.samePreparation}: - { + if (value) { + self.field.setValue('sameConfigPolicy', value); + } + }} + /> +
    +
    + -
    -
    - + }} + data-spm-click={'gostr=/aliyun;locaid=doClone'} + > + {locale.startCloning} + +
    +
    + {locale.cloneEditableTitle} -
    - - - -
    - +
    + + + +
    + ), }); }, @@ -920,76 +1008,79 @@ class ConfigurationManagement extends React.Component { confirm.hide(); let failCount = ret.data.failData ? ret.data.failData.length : 0; let skipCount = ret.data.skipData ? ret.data.skipData.length : 0; - let unrecognizedCount = ret.data.unrecognizedCount ? ret.data.unrecognizedCount : 0; + let unrecognizedCount = ret.data.unrecognizedCount + ? ret.data.unrecognizedCount : 0; if (failCount > 0) { Dialog.alert({ title: isImport ? locale.importAbort : locale.cloneAbort, content: ( -
    -

    - {locale.conflictConfig}:{ret.data.failData[0].group}/{ret.data.failData[0].dataId} -

    -
    -
    - {locale.failureEntries}: {failCount} -
    - - - -
    -
    -
    -
    - {locale.unprocessedEntries}: {skipCount} -
    - - - -
    -
    -
    -
    - {locale.unrecognizedEntries}: {unrecognizedCount} -
    - - -
    +
    +

    + {locale.conflictConfig}:{ret.data.failData[0].group}/{ret.data.failData[0].dataId} +

    +
    +
    + {locale.failureEntries}: {failCount} +
    + + + +
    +
    +
    +
    + {locale.unprocessedEntries}: {skipCount} +
    + + + +
    +
    +
    +
    + {locale.unrecognizedEntries}: {unrecognizedCount} +
    + + +
    +
    -
    ), }); } else if (skipCount > 0 || unrecognizedCount > 0) { - let message = `${isImport ? locale.importSuccEntries : locale.cloneSuccEntries}${ - ret.data.succCount + let message = `${isImport ? locale.importSuccEntries + : locale.cloneSuccEntries}${ + ret.data.succCount }`; Dialog.alert({ title: isImport ? locale.importSucc : locale.cloneSucc, content: ( -
    -
    {message}
    -
    -
    - {locale.skippedEntries}: {skipCount} -
    - - - -
    -
    -
    -
    - {locale.unrecognizedEntries}: {unrecognizedCount} -
    - - -
    +
    +
    {message}
    +
    +
    + {locale.skippedEntries}: {skipCount} +
    + + + +
    +
    +
    +
    + {locale.unrecognizedEntries}: {unrecognizedCount} +
    + + +
    +
    -
    ), }); } else { - let message = `${isImport ? locale.importSuccBegin : locale.cloneSuccBegin}${ - ret.data.succCount + let message = `${isImport ? locale.importSuccBegin + : locale.cloneSuccBegin}${ + ret.data.succCount }${isImport ? locale.importSuccEnd : locale.cloneSuccEnd}`; Message.success(message); } @@ -1002,7 +1093,8 @@ class ConfigurationManagement extends React.Component { if (resultCode === 100002) { alertContent = locale.metadataIllegal; } - if (resultCode === 100003 || resultCode === 100004 || resultCode === 100005) { + if (resultCode === 100003 || resultCode === 100004 || resultCode + === 100005) { alertContent = locale.importDataValidationError; } Dialog.alert({ @@ -1013,7 +1105,7 @@ class ConfigurationManagement extends React.Component { } importData() { - const { locale = {} } = this.props; + const {locale = {}} = this.props; const self = this; self.field.setValue('sameConfigPolicy', 'ABORT'); @@ -1033,13 +1125,14 @@ class ConfigurationManagement extends React.Component { return; } } - const { accessToken = '', username = '' } = token; + const {accessToken = '', username = ''} = token; const uploadProps = { accept: 'application/zip', action: `v1/cs/configs?import=true&namespace=${getParams( - 'namespace' - )}&accessToken=${accessToken}&username=${username}&tenant=${getParams('namespace')}`, - headers: Object.assign({}, {}, { accessToken }), + 'namespace' + )}&accessToken=${accessToken}&username=${username}&tenant=${getParams( + 'namespace')}`, + headers: Object.assign({}, {}, {accessToken}), data: { policy: self.field.getValue('sameConfigPolicy'), }, @@ -1050,10 +1143,11 @@ class ConfigurationManagement extends React.Component { return options; }, onSuccess(ret) { - self.processImportAndCloneResult(ret.response, locale, importConfirm, true); + self.processImportAndCloneResult(ret.response, locale, importConfirm, + true); }, onError(err) { - const { data = {}, status } = err.response; + const {data = {}, status} = err.response; if ([401, 403].includes(status)) { Dialog.alert({ title: locale.importFail, @@ -1071,64 +1165,72 @@ class ConfigurationManagement extends React.Component { title: locale.import, footer: false, content: ( -
    -
    - {locale.targetNamespace}: - {this.state.nownamespace_name} |{' '} - {this.state.nownamespace_id} -
    -
    - {locale.samePreparation}: - +
    +
    + + {locale.importRemind} +
    +
    + + + +
    -
    ), }); } configDataTableOnChange(ids, records) { - const { rowSelection } = this.state; + const {rowSelection} = this.state; rowSelection.selectedRowKeys = ids; - this.setState({ rowSelection }); + this.setState({rowSelection}); configsTableSelected.clear(); records.forEach((record, i) => { configsTableSelected.set(record.id, record); @@ -1136,292 +1238,330 @@ class ConfigurationManagement extends React.Component { } render() { - const { locale = {}, configurations = {} } = this.props; + const {locale = {}, configurations = {}} = this.props; return ( - <> - (this.batchHandle = ref)} /> -
    -
    -
    - - -
    - + <> + (this.batchHandle = ref)}/> +
    -
    - - - - - { - this.dataId = dataId; - this.setState({ dataId }); - setParams('dataId', this.dataId); - }} - onPressEnter={() => this.selectAll()} - /> - +
    + + +
    - - this.selectAll()} - hasClear - /> - +
    + + + + + + { + this.dataId = dataId; + this.setState({dataId}); + setParams('dataId', this.dataId); + }} + onPressEnter={() => this.selectAll()} + /> + - - - + + this.selectAll()} + hasClear + /> + - - - - - - + + + - - - -
    - - this.getData()} - /> - - - - - -
    - - - - - - {!this.inApp && ( - - )} - -
    - {configurations.totalCount > 0 && ( - <> -
    - {[ - { - warning: true, - text: locale.deleteAction, - locaid: 'configsDelete', - onClick: () => this.multipleSelectionDeletion(), - }, + > + + - { - text: locale.clone, - locaid: 'configsDelete', - onClick: () => this.cloneSelectedDataConfirm(), - }, - ].map((item, index) => ( + - ))} - +
    + + this.getData()} + /> + + + + + + + + +
    + + + + + + + {!this.inApp && ( + + )} + +
    + {configurations.totalCount > 0 && ( + <> +
    + {[ + { + warning: true, + text: locale.deleteAction, + locaid: 'configsDelete', + onClick: () => this.multipleSelectionDeletion(), + }, + + { + text: locale.clone, + locaid: 'configsDelete', + onClick: () => this.cloneSelectedDataConfirm(), + }, + ].map((item, index) => ( + + ))} + + {[ + { + text: locale.export, + locaid: 'exportData', + onClick: () => this.exportData(this), + }, + { + text: locale.newExport, + locaid: 'exportDataNew', + onClick: () => this.exportDataNew(this), + }, + { + text: locale.exportSelected, + locaid: 'configsExport', + onClick: () => this.exportSelectedData(false), + }, + { + text: locale.newExportSelected, + locaid: 'configsExport', + onClick: () => this.exportSelectedData(true), + }, + ].map((item, index) => ( + + {item.text} + + ))} + +
    + this.handlePageSizeChange(val)} + current={configurations.pageNumber} + total={configurations.totalCount} + totalRender={total => } + pageSize={this.state.pageSize} + onChange={this.changePage.bind(this)} + /> + + )} + + +
    + {this.state.hasdash && ( +
    + {this.state.contentList.map((v, i) => ( + + ))}
    - this.handlePageSizeChange(val)} - current={configurations.pageNumber} - total={configurations.totalCount} - pageSize={this.state.pageSize} - onChange={this.changePage.bind(this)} - /> - )} - -
    - {this.state.hasdash && ( -
    - {this.state.contentList.map((v, i) => ( - - ))} -
    - )} -
    - + ); } } diff --git a/console-ui/src/pages/Register/Register.jsx b/console-ui/src/pages/Register/Register.jsx new file mode 100644 index 00000000000..27ba151185f --- /dev/null +++ b/console-ui/src/pages/Register/Register.jsx @@ -0,0 +1,181 @@ +import React from 'react'; +import { Card, Form, Input, Message, ConfigProvider, Field, Dialog } from '@alifd/next'; +import { withRouter } from 'react-router-dom'; + +import './index.scss'; +import Header from '../../layouts/Header'; +import PropTypes from 'prop-types'; +import { admin, guide, state } from '../../reducers/base'; +import { connect } from 'react-redux'; +import { generateRandomPassword, goLogin } from '../../globalLib'; +import { LOGINPAGE_ENABLED } from '../../constants'; + +const FormItem = Form.Item; + +@withRouter +@ConfigProvider.config +@connect(state => ({ ...state.locale })) +class Register extends React.Component { + static displayName = 'Register'; + + static propTypes = { + locale: PropTypes.object, + history: PropTypes.object, + }; + + constructor(props) { + super(props); + this.state = { + consoleUiEnable: true, + guideMsg: '', + }; + this.field = new Field(this); + } + + componentDidMount() { + if (localStorage.getItem('token')) { + const [baseUrl] = location.href.split('#'); + location.href = `${baseUrl}#/`; + } + this.handleSearch(); + } + + handleSearch = () => { + state().then(res => { + if (res?.console_ui_enabled === 'false') { + this.setState({ consoleUiEnable: true }); + guide().then(res => { + this.setState({ guideMsg: res?.data }); + }); + } else { + this.setState({ consoleUiEnable: false }); + } + }); + }; + + handleSubmit = () => { + const { locale = {} } = this.props; + this.field.validate((errors, values) => { + if (errors) { + return; + } + + const data = { + password: generateRandomPassword(10), + ...values + }; + + admin(data) + .then(res => { + if (res.username && res.password) { + localStorage.setItem('token', JSON.stringify(res)); + Dialog.alert({ + title: locale.Login.initPassword + locale.ListeningToQuery.success, + content: locale.Password.newPassword + ':' + res.password, + onOk: () => { + this.props.history.push('/'); + } + }); + } else { + Dialog.alert({ + title: locale.Login.initPassword + locale.ListeningToQuery.failure, + content: res.data, + onOk: () => { + const _LOGINPAGE_ENABLED = localStorage.getItem(LOGINPAGE_ENABLED); + + if (_LOGINPAGE_ENABLED !== 'false') { + let token = {}; + try { + token = JSON.parse(localStorage.token); + } catch (e) { + console.log('Token Error', localStorage.token, e); + goLogin(); + } + } else { + this.props.history.push('/'); + } + } + }); + } + }) + .catch(() => { + Message.error({ + content: locale.Login.invalidUsernameOrPassword, + }); + }); + }); + }; + + onKeyDown = event => { + // 'keypress' event misbehaves on mobile so we track 'Enter' key via 'keydown' event + if (event.key === 'Enter') { + event.preventDefault(); + event.stopPropagation(); + this.handleSubmit(); + } + }; + + render() { + const { locale = {} } = this.props; + const { consoleUiEnable, guideMsg } = this.state; + + return ( +
    +
    +
    +
    + +

    {locale.Login.productDesc}

    +
    +
    +
    +
    +
    +
    + +
    {locale.Login.initPassword}
    +
    +
    {locale.Login.internalSysTip1}
    +
    {locale.Login.internalSysTip2}
    +
    + {!consoleUiEnable && ( +
    + + + + + + + + {locale.Login.submit} + +
    + )} + {consoleUiEnable && ( + +
    + + )} + +
    +
    + ); + } +} + +export default Register; diff --git a/console-ui/src/pages/Register/index.jsx b/console-ui/src/pages/Register/index.jsx new file mode 100644 index 00000000000..17cef2d4b96 --- /dev/null +++ b/console-ui/src/pages/Register/index.jsx @@ -0,0 +1,4 @@ + +import Register from './Register'; + +export default Register; diff --git a/console-ui/src/pages/Register/index.scss b/console-ui/src/pages/Register/index.scss new file mode 100644 index 00000000000..2a16a44a154 --- /dev/null +++ b/console-ui/src/pages/Register/index.scss @@ -0,0 +1,142 @@ +/*! + * Copyright 1999-2018 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +$animationDuration: 2s; + +// 品牌色 +$brandColor: #2e3034; +$mobileWidth: 640px; +// 页面主体最大宽度 +$contentWidth: 1280px; + +@keyframes slashStar { + 0% { + opacity: 1; + } + + 100% { + opacity: 0; + } +} + +.home-page { + .top-section { + position: relative; + height: 100vh; + .login-panel { + position: absolute; + right: 40px; + width: 480px; + height: 540px; + top: 90px; + border: 0px; + input, + input::-webkit-input-placeholder { + font-size: 16px; + } + .login-header { + width: 100%; + line-height: 45px; + font-size: 32px; + margin-top: 58px; + text-align: center; + } + .internal-sys-tip { + width: 100%; + line-height: 25px; + font-size: 20px; + margin-top: 25px; + text-align: center; + font-weight: 800; + color: #ff0000cc; + } + .login-form { + width: 360px; + margin: 40px auto auto auto; + input { + height: 60px; + } + button { + width: 100%; + height: 60px; + font-size: 16px; + background: #4190ff 100%; + color: white; + border: 0px; + } + } + } + .animation { + position: absolute; + width: 6px; + height: 6px; + border-radius: 50%; + background-color: #1be1f6; + &1 { + left: 15%; + top: 70%; + animation: slashStar $animationDuration ease-in-out 0.3s infinite; + } + &2 { + left: 34%; + top: 35%; + animation: slashStar $animationDuration ease-in-out 1.2s infinite; + } + &3 { + left: 53%; + top: 20%; + animation: slashStar $animationDuration ease-in-out 0.5s infinite; + } + &4 { + left: 72%; + top: 64%; + animation: slashStar $animationDuration ease-in-out 0.8s infinite; + } + &5 { + left: 87%; + top: 30%; + animation: slashStar $animationDuration ease-in-out 1.5s infinite; + } + } + .vertical-middle { + position: absolute; + left: 0; + top: 50%; + margin-top: -47px; + transform: translateY(-50%); + } + .product-area { + width: 600px; + margin-left: 40px; + } + .product-logo { + display: block; + width: 257px; + height: 50px; + margin: 0; + } + .product-desc { + opacity: 0.8; + font-family: Avenir-Medium; + font-size: 24px; + color: #fff; + max-width: 780px; + margin: 12px auto 30px; + text-align: left; + line-height: 30px; + } + } +} diff --git a/console-ui/src/pages/ServiceManagement/ServiceList/ServiceList.js b/console-ui/src/pages/ServiceManagement/ServiceList/ServiceList.js index 4d161ab0eaa..f30ceac8d3e 100644 --- a/console-ui/src/pages/ServiceManagement/ServiceList/ServiceList.js +++ b/console-ui/src/pages/ServiceManagement/ServiceList/ServiceList.js @@ -36,6 +36,7 @@ import RegionGroup from '../../../components/RegionGroup'; import EditServiceDialog from '../ServiceDetail/EditServiceDialog'; import ShowServiceCodeing from 'components/ShowCodeing/ShowServiceCodeing'; import PageTitle from '../../../components/PageTitle'; +import TotalRender from '../../../components/Page/TotalRender'; import './ServiceList.scss'; import { GLOBAL_PAGE_SIZE_LIST } from '../../../constants'; @@ -343,6 +344,7 @@ class ServiceList extends React.Component { popupProps={{ align: 'bl tl' }} total={this.state.total} pageSize={this.state.pageSize} + totalRender={total => } onPageSizeChange={pageSize => this.handlePageSizeChange(pageSize)} onChange={currentPage => this.setState({ currentPage }, () => this.queryServiceList())} /> diff --git a/console-ui/src/pages/SettingCenter/SettingCenter.js b/console-ui/src/pages/SettingCenter/SettingCenter.js index a85e3256d14..47654bd4811 100644 --- a/console-ui/src/pages/SettingCenter/SettingCenter.js +++ b/console-ui/src/pages/SettingCenter/SettingCenter.js @@ -21,12 +21,13 @@ import { Button, ConfigProvider, Radio } from '@alifd/next'; import PageTitle from '../../components/PageTitle'; import { changeLanguage } from '@/reducers/locale'; import changeTheme from '../../theme'; +import changeNameShow from '../../components/NameSpaceList/show'; import { connect } from 'react-redux'; -import { LANGUAGE_KEY, THEME } from '../../constants'; +import { LANGUAGE_KEY, NAME_SHOW, THEME } from '../../constants'; const { Group: RadioGroup } = Radio; -@connect(state => ({ ...state.locale }), { changeLanguage, changeTheme }) +@connect(state => ({ ...state.locale }), { changeLanguage, changeTheme, changeNameShow }) @ConfigProvider.config class SettingCenter extends React.Component { static displayName = 'SettingCenter'; @@ -35,14 +36,18 @@ class SettingCenter extends React.Component { locale: PropTypes.object, changeLanguage: PropTypes.func, changeTheme: PropTypes.func, + changeNameShow: PropTypes.func, }; constructor(props) { super(props); const defaultTheme = localStorage.getItem(THEME); + const defaultShow = localStorage.getItem(NAME_SHOW); + const defaultLanguage = localStorage.getItem(LANGUAGE_KEY); this.state = { theme: defaultTheme === 'dark' ? 'dark' : 'light', - language: localStorage.getItem(LANGUAGE_KEY), + language: defaultLanguage === 'en-US' ? 'en-US' : 'zh-CN', + nameShow: defaultShow === 'select' ? 'select' : 'label', }; } @@ -58,12 +63,20 @@ class SettingCenter extends React.Component { }); } + newNameShow(value) { + this.setState({ + nameShow: value, + }); + } + submit() { - const { changeLanguage, changeTheme } = this.props; + const { changeLanguage, changeTheme, changeNameShow } = this.props; const currentLanguage = this.state.language; const currentTheme = this.state.theme; + const currentNameShow = this.state.nameShow; changeLanguage(currentLanguage); changeTheme(currentTheme); + changeNameShow(currentNameShow); } render() { @@ -76,6 +89,10 @@ class SettingCenter extends React.Component { { value: 'en-US', label: 'English' }, { value: 'zh-CN', label: '中文' }, ]; + const nameShowList = [ + { value: 'select', label: locale.settingShowSelect }, + { value: 'label', label: locale.settingShowLabel }, + ]; return ( <> @@ -97,6 +114,14 @@ class SettingCenter extends React.Component { onChange={this.newLanguage.bind(this)} />
    +
    +
    {locale.settingShow}
    + +
    ), use instead of.'),S.default.cloneElement(e,{className:t,size:c||C(r)})):(0,k.isValidElement)(e)?e:S.default.createElement("span",{className:a+"btn-helper"},e)}),t=d,_=(0,b.default)({},x.obj.pickOthers(Object.keys(T.propTypes),e),{type:o,disabled:p,onClick:h,className:(0,E.default)(n)});return"button"!==t&&(delete _.type,_.disabled)&&(delete _.onClick,_.href)&&delete _.href,S.default.createElement(t,(0,b.default)({},_,{dir:g?"rtl":void 0,onMouseUp:this.onMouseUp,ref:this.buttonRefHandler}),s,u)},a=n=T,n.propTypes=(0,b.default)({},s.default.propTypes,{prefix:r.default.string,rtl:r.default.bool,type:r.default.oneOf(["primary","secondary","normal"]),size:r.default.oneOf(["small","medium","large"]),icons:r.default.shape({loading:r.default.node}),iconSize:r.default.oneOfType([r.default.oneOf(["xxs","xs","small","medium","large","xl","xxl","xxxl","inherit"]),r.default.number]),htmlType:r.default.oneOf(["submit","reset","button"]),component:r.default.oneOf(["button","a","div","span"]),loading:r.default.bool,ghost:r.default.oneOf([!0,!1,"light","dark"]),text:r.default.bool,warning:r.default.bool,disabled:r.default.bool,onClick:r.default.func,className:r.default.string,onMouseUp:r.default.func,children:r.default.node}),n.defaultProps={prefix:"next-",type:"normal",size:"medium",icons:{},htmlType:"button",component:"button",loading:!1,ghost:!1,text:!1,warning:!1,disabled:!1,onClick:function(){}};var u,s=a;function T(){var e,t;(0,o.default)(this,T);for(var n=arguments.length,a=Array(n),r=0;ra[r])return!0;if(n[r] 0, or `null`');if(U(i,"numericSeparator")&&"boolean"!=typeof i.numericSeparator)throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var t=i.numericSeparator;if(void 0===n)return"undefined";if(null===n)return"null";if("boolean"==typeof n)return n?"true":"false";if("string"==typeof n)return function e(t,n){if(t.length>n.maxStringLength)return a=t.length-n.maxStringLength,a="... "+a+" more character"+(1"}if(z(n))return 0===n.length?"[]":(l=$(n,m),h&&!function(e){for(var t=0;t "+m(e,n))}),ne("Map",_.call(n),u,h)):function(e){if(w&&e&&"object"==typeof e)try{w.call(e);try{_.call(e)}catch(e){return 1}return e instanceof Set}catch(e){}return}(n)?(d=[],M&&M.call(n,function(e){d.push(m(e,n))}),ne("Set",w.call(n),d,h)):function(e){if(k&&e&&"object"==typeof e)try{k.call(e,k);try{S.call(e,S)}catch(e){return 1}return e instanceof WeakMap}catch(e){}return}(n)?q("WeakMap"):function(e){if(S&&e&&"object"==typeof e)try{S.call(e,S);try{k.call(e,k)}catch(e){return 1}return e instanceof WeakSet}catch(e){}return}(n)?q("WeakSet"):function(e){if(E&&e&&"object"==typeof e)try{return E.call(e),1}catch(e){}return}(n)?q("WeakRef"):"[object Number]"!==V(c=n)||j&&"object"==typeof c&&j in c?function(e){if(e&&"object"==typeof e&&D)try{return D.call(e),1}catch(e){}return}(n)?K(m(D.call(n))):"[object Boolean]"!==V(t=n)||j&&"object"==typeof t&&j in t?"[object String]"!==V(e=n)||j&&"object"==typeof e&&j in e?("[object Date]"!==V(t=n)||j&&"object"==typeof t&&j in t)&&!W(n)?(e=$(n,m),t=I?I(n)===Object.prototype:n instanceof Object||n.constructor===Object,f=n instanceof Object?"":"null prototype",p=!t&&j&&Object(n)===n&&j in n?x.call(V(n),8,-1):f?"Object":"",t=(!t&&"function"==typeof n.constructor&&n.constructor.name?n.constructor.name+" ":"")+(p||f?"["+O.call(L.call([],p||[],f||[]),": ")+"] ":""),0===e.length?t+"{}":h?t+"{"+G(e,h)+"}":t+"{ "+O.call(e,", ")+" }"):String(n):K(m(String(n))):K(J.call(n)):K(m(Number(n)))};var l=Object.prototype.hasOwnProperty||function(e){return e in this};function U(e,t){return l.call(e,t)}function V(e){return i.call(e)}function ee(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0,a=e.length;n, as child."),a.push(t),e.props.children)&&(t.children=n(e.props.children))}),a}(e.children):t},N.prototype.fetchInfoFromBinaryChildren=function(e){function r(e,t){return t=t||0,e.forEach(function(e){e.children?t=r(e.children,t):t+=1}),t}var a=!1,o=[],i=[],e=(function t(){var e=0r.tRight&&(e=r.tRight,r.changedPageX=r.tRight-r.startLeft),e-r.cellLefto.clientHeight,o.scrollWidth,o.clientWidth,o={},e||(o[r]=0,o[a]=0),+i&&(o.marginBottom=-i,o.paddingBottom=i,e)&&(o[a]=i),h.dom.setStyle(this.headerNode,o)),n&&!this.props.lockType&&this.headerNode&&(r=this.headerNode.querySelector("."+t+"table-header-fixer"),e=h.dom.getStyle(this.headerNode,"height"),a=h.dom.getStyle(this.headerNode,"paddingBottom"),h.dom.setStyle(r,{width:i,height:e-a}))},o.prototype.render=function(){var e=this.props,t=e.components,n=e.className,a=e.prefix,r=e.fixedHeader,o=e.lockType,i=e.dataSource,e=(e.maxBodyHeight,(0,u.default)(e,["components","className","prefix","fixedHeader","lockType","dataSource","maxBodyHeight"]));return r&&((t=(0,l.default)({},t)).Header||(t.Header=m.default),t.Body||(t.Body=g.default),t.Wrapper||(t.Wrapper=y.default),n=(0,p.default)(((r={})[a+"table-fixed"]=!0,r[a+"table-wrap-empty"]=!i.length,r[n]=n,r))),c.default.createElement(s,(0,l.default)({},e,{dataSource:i,lockType:o,components:t,className:n,prefix:a}))},o}(c.default.Component),n.FixedHeader=m.default,n.FixedBody=g.default,n.FixedWrapper=y.default,n.propTypes=(0,l.default)({hasHeader:r.default.bool,fixedHeader:r.default.bool,maxBodyHeight:r.default.oneOfType([r.default.number,r.default.string])},s.propTypes),n.defaultProps=(0,l.default)({},s.defaultProps,{hasHeader:!0,fixedHeader:!1,maxBodyHeight:200,components:{},refs:{},prefix:"next-"}),n.childContextTypes={fixedHeader:r.default.bool,getNode:r.default.func,onFixedScrollSync:r.default.func,getTableInstanceForFixed:r.default.func,maxBodyHeight:r.default.oneOfType([r.default.number,r.default.string])};var t,n=t;return n.displayName="FixedTable",(0,o.statics)(n,s),n};var c=s(n(0)),r=s(n(5)),f=n(24),p=s(n(17)),h=n(11),m=s(n(134)),g=s(n(402)),y=s(n(135)),o=n(70);function s(e){return e&&e.__esModule?e:{default:e}}e.exports=t.default},function(e,t,n){"use strict";t.__esModule=!0;var i=o(n(12)),f=o(n(2)),r=o(n(4)),s=o(n(6)),l=o(n(7)),u=(t.default=function(o){e=t=function(n){function a(e,t){(0,r.default)(this,a);var c=(0,s.default)(this,n.call(this,e,t));return c.addSelection=function(e){var t=c.props,n=t.prefix,a=t.rowSelection,t=t.size,a=a.columnProps&&a.columnProps()||{};e.find(function(e){return"selection"===e.key})||e.unshift((0,f.default)({key:"selection",title:c.renderSelectionHeader.bind(c),cell:c.renderSelectionBody.bind(c),width:"small"===t?34:50,className:n+"table-selection "+n+"table-prerow",__normalized:!0},a))},c.renderSelectionHeader=function(){var e=c.selectAllRow,t={},n=c.props,a=n.rowSelection,r=n.primaryKey,o=n.dataSource,i=n.entireDataSource,n=n.locale,s=c.state.selectedRowKeys,l=a.mode||"multiple",u=!!s.length,d=!1,i=(c.flatDataSource(i||o).filter(function(e,t){return!a.getProps||!(a.getProps(e,t)||{}).disabled}).map(function(e){return e[r]}).forEach(function(e){-1===s.indexOf(e)?u=!1:d=!0}),t.onClick=b(function(e){e.stopPropagation()},t.onClick),a.titleProps&&a.titleProps()||{});return u&&(d=!1),["multiple"===l?p.default.createElement(h.default,(0,f.default)({key:"_total",indeterminate:d,"aria-label":n.selectAll,checked:u,onChange:e},t,i)):null,a.titleAddons&&a.titleAddons()]},c.renderSelectionBody=function(e,t,n){var a=c.props,r=a.rowSelection,a=a.primaryKey,o=c.state.selectedRowKeys,i=r.mode||"multiple",o=-1l.length&&(u=o),w(u.filter(function(e){return-1=Math.max(a-y,0)&&oc.clientHeight;this.isLock()?(e=this.bodyLeftNode,t=this.bodyRightNode,n=this.getWrapperNode("right"),a=f?d:0,c=c.offsetHeight-d,f||(r[l]=0,r[u]=0),+d?(r.marginBottom=-d,r.paddingBottom=d):(r.marginBottom=-20,r.paddingBottom=20),c={"max-height":c},o||+d||(c[u]=0),+d&&(c[u]=-d),e&&g.dom.setStyle(e,c),t&&g.dom.setStyle(t,c),n&&+d&&g.dom.setStyle(n,i?"left":"right",a+"px")):(r.marginBottom=-d,r.paddingBottom=d,r[u]=0,f||(r[l]=0)),s&&g.dom.setStyle(s,r)},a.prototype.adjustHeaderSize=function(){var o=this;this.isLock()&&this.tableInc.groupChildren.forEach(function(e,t){var n=o.tableInc.groupChildren[t].length-1,n=o.getHeaderCellNode(t,n),a=o.getHeaderCellNode(t,0),r=o.getHeaderCellNode(t,0,"right"),t=o.getHeaderCellNode(t,0,"left");n&&r&&(n=n.offsetHeight,g.dom.setStyle(r,"height",n),setTimeout(function(){var e=o.tableRightInc.affixRef;return e&&e.getInstance()&&e.getInstance().updatePosition()})),a&&t&&(r=a.offsetHeight,g.dom.setStyle(t,"height",r),setTimeout(function(){var e=o.tableLeftInc.affixRef;return e&&e.getInstance()&&e.getInstance().updatePosition()}))})},a.prototype.adjustRowHeight=function(){var n=this;this.isLock()&&this.tableInc.props.dataSource.forEach(function(e,t){t=""+("object"===(void 0===e?"undefined":(0,r.default)(e))&&"__rowIndex"in e?e.__rowIndex:t)+(e.__expanded?"_expanded":"");n.setRowHeight(t,"left"),n.setRowHeight(t,"right")})},a.prototype.setRowHeight=function(e,t){var t=this.getRowNode(e,t),e=this.getRowNode(e),e=(M?e&&e.offsetHeight:e&&parseFloat(getComputedStyle(e).height))||"auto",n=(M?t&&t.offsetHeight:t&&parseFloat(getComputedStyle(t).height))||"auto";t&&e!==n&&g.dom.setStyle(t,"height",e)},a.prototype.getWrapperNode=function(e){e=e?e.charAt(0).toUpperCase()+e.substr(1):"";try{return(0,u.findDOMNode)(this["lock"+e+"El"])}catch(e){return null}},a.prototype.getRowNode=function(e,t){t=this["table"+(t=t?t.charAt(0).toUpperCase()+t.substr(1):"")+"Inc"];try{return(0,u.findDOMNode)(t.getRowRef(e))}catch(e){return null}},a.prototype.getHeaderCellNode=function(e,t,n){n=this["table"+(n=n?n.charAt(0).toUpperCase()+n.substr(1):"")+"Inc"];try{return(0,u.findDOMNode)(n.getHeaderCellRef(e,t))}catch(e){return null}},a.prototype.getCellNode=function(e,t,n){n=this["table"+(n=n?n.charAt(0).toUpperCase()+n.substr(1):"")+"Inc"];try{return(0,u.findDOMNode)(n.getCellRef(e,t))}catch(e){return null}},a.prototype.render=function(){var e,t=this.props,n=(t.children,t.columns,t.prefix),a=t.components,r=t.className,o=t.dataSource,i=t.tableWidth,t=(0,f.default)(t,["children","columns","prefix","components","className","dataSource","tableWidth"]),s=this.normalizeChildrenState(this.props),l=s.lockLeftChildren,u=s.lockRightChildren,s=s.children,d={left:this.getFlatenChildrenLength(l),right:this.getFlatenChildrenLength(u),origin:this.getFlatenChildrenLength(s)};return this._notNeedAdjustLockLeft&&(l=[]),this._notNeedAdjustLockRight&&(u=[]),this.lockLeftChildren=l,this.lockRightChildren=u,this.isOriginLock()?((a=(0,p.default)({},a)).Body=a.Body||v.default,a.Header=a.Header||_.default,a.Wrapper=a.Wrapper||b.default,a.Row=a.Row||y.default,r=(0,m.default)(((e={})[n+"table-lock"]=!0,e[n+"table-wrap-empty"]=!o.length,e[r]=r,e)),e=[h.default.createElement(c,(0,p.default)({},t,{dataSource:o,key:"lock-left",columns:l,className:n+"table-lock-left",lengths:d,prefix:n,lockType:"left",components:a,ref:this.saveLockLeftRef,loading:!1,"aria-hidden":!0})),h.default.createElement(c,(0,p.default)({},t,{dataSource:o,key:"lock-right",columns:u,className:n+"table-lock-right",lengths:d,prefix:n,lockType:"right",components:a,ref:this.saveLockRightRef,loading:!1,"aria-hidden":!0}))],h.default.createElement(c,(0,p.default)({},t,{tableWidth:i,dataSource:o,columns:s,prefix:n,lengths:d,wrapperContent:e,components:a,className:r}))):h.default.createElement(c,this.props)},a}(h.default.Component),t.LockRow=y.default,t.LockBody=v.default,t.LockHeader=_.default,t.propTypes=(0,p.default)({scrollToCol:a.default.number,scrollToRow:a.default.number},c.propTypes),t.defaultProps=(0,p.default)({},c.defaultProps),t.childContextTypes={getTableInstance:a.default.func,getLockNode:a.default.func,onLockBodyScroll:a.default.func,onRowMouseEnter:a.default.func,onRowMouseLeave:a.default.func};var e,t=e;return t.displayName="LockTable",(0,w.statics)(t,c),t},n(0)),h=c(l),u=n(24),a=c(n(5)),m=c(n(17)),d=c(n(177)),g=n(11),y=c(n(179)),v=c(n(403)),_=c(n(404)),b=c(n(135)),w=n(70);function c(e){return e&&e.__esModule?e:{default:e}}var M=g.env.ieVersion;function k(e){return function n(e){return e.map(function(e){var t=(0,p.default)({},e);return e.children&&(e.children=n(e.children)),t})}(e)}e.exports=t.default},function(e,t,n){"use strict";t.__esModule=!0;var l=s(n(12)),u=s(n(2)),r=s(n(4)),o=s(n(6)),i=s(n(7)),d=(t.default=function(s){e=t=function(n){function a(e,t){(0,r.default)(this,a);var d=(0,o.default)(this,n.call(this,e));return d.state={},d.updateOffsetArr=function(){var e=d.splitChildren||{},t=e.lockLeftChildren,n=e.lockRightChildren,e=e.originChildren,a=d.getFlatenChildren(t).length,r=d.getFlatenChildren(n).length,e=a+r+d.getFlatenChildren(e).length,a=0r.top-e.offset?(t?(l.position="absolute",l.top=a-(r.top-e.offset),u="relative"):(l.position="fixed",l.top=e.offset+n.top),d._setAffixStyle(l,!0),d._setContainerStyle(s)):e.bottom&&a{e=new Date(e);if(isNaN(e))throw new TypeError("Invalid Datetime");return e}},function(e,t,n){"use strict";const a=n(182);class r extends Date{constructor(e){super(e+"Z"),this.isFloating=!0}toISOString(){return`${this.getUTCFullYear()}-${a(2,this.getUTCMonth()+1)}-`+a(2,this.getUTCDate())+"T"+(`${a(2,this.getUTCHours())}:${a(2,this.getUTCMinutes())}:${a(2,this.getUTCSeconds())}.`+a(3,this.getUTCMilliseconds()))}}e.exports=e=>{e=new r(e);if(isNaN(e))throw new TypeError("Invalid Datetime");return e}},function(a,e,r){"use strict";!function(e){const t=r(182);class n extends e.Date{constructor(e){super(e),this.isDate=!0}toISOString(){return`${this.getUTCFullYear()}-${t(2,this.getUTCMonth()+1)}-`+t(2,this.getUTCDate())}}a.exports=e=>{e=new n(e);if(isNaN(e))throw new TypeError("Invalid Datetime");return e}}.call(this,r(65))},function(e,t,n){"use strict";const a=n(182);class r extends Date{constructor(e){super(`0000-01-01T${e}Z`),this.isTime=!0}toISOString(){return`${a(2,this.getUTCHours())}:${a(2,this.getUTCMinutes())}:${a(2,this.getUTCSeconds())}.`+a(3,this.getUTCMilliseconds())}}e.exports=e=>{e=new r(e);if(isNaN(e))throw new TypeError("Invalid Datetime");return e}},function(e,t,n){"use strict";!function(s){e.exports=function(r,e){e=e||{};const n=e.blocksize||40960,o=new t;return new Promise((e,t)=>{s(i,0,n,e,t)});function i(e,t,n,a){if(e>=r.length)try{return n(o.finish())}catch(e){return a(l(e,r))}try{o.parse(r.slice(e,e+t)),s(i,e+t,t,n,a)}catch(e){a(l(e,r))}}};const t=n(181),l=n(183)}.call(this,n(408).setImmediate)},function(e,t,n){!function(e,p){!function(n,o){"use strict";var a,i,s,r,l,u,t,e;function d(e){delete i[e]}function c(e){if(s)setTimeout(c,0,e);else{var t=i[e];if(t){s=!0;try{var n=t,a=n.callback,r=n.args;switch(r.length){case 0:a();break;case 1:a(r[0]);break;case 2:a(r[0],r[1]);break;case 3:a(r[0],r[1],r[2]);break;default:a.apply(o,r)}}finally{d(e),s=!1}}}}function f(){function e(e){e.source===n&&"string"==typeof e.data&&0===e.data.indexOf(t)&&c(+e.data.slice(t.length))}var t="setImmediate$"+Math.random()+"$";n.addEventListener?n.addEventListener("message",e,!1):n.attachEvent("onmessage",e),l=function(e){n.postMessage(t+e,"*")}}n.setImmediate||(a=1,s=!(i={}),r=n.document,e=(e=Object.getPrototypeOf&&Object.getPrototypeOf(n))&&e.setTimeout?e:n,"[object process]"==={}.toString.call(n.process)?l=function(e){p.nextTick(function(){c(e)})}:!function(){var e,t;if(n.postMessage&&!n.importScripts)return e=!0,t=n.onmessage,n.onmessage=function(){e=!1},n.postMessage("","*"),n.onmessage=t,e}()?l=n.MessageChannel?((t=new MessageChannel).port1.onmessage=function(e){c(e.data)},function(e){t.port2.postMessage(e)}):r&&"onreadystatechange"in r.createElement("script")?(u=r.documentElement,function(e){var t=r.createElement("script");t.onreadystatechange=function(){c(e),t.onreadystatechange=null,u.removeChild(t),t=null},u.appendChild(t)}):function(e){setTimeout(c,0,e)}:f(),e.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),n=0;n{let n,a=!1,r=!1;function o(){if(a=!0,!n)try{e(l.finish())}catch(e){t(e)}}function i(e){r=!0,t(e)}s.once("end",o),s.once("error",i),function e(){n=!0;let t;for(;null!==(t=s.read());)try{l.parse(t)}catch(e){return i(e)}n=!1;if(a)return o();if(r)return;s.once("readable",e)}()})}(e):function(){const a=new o;return new r.Transform({objectMode:!0,transform(e,t,n){try{a.parse(e.toString(t))}catch(e){this.emit("error",e)}n()},flush(e){try{this.push(a.finish())}catch(e){this.emit("error",e)}e()}})}()};const r=n(691),o=n(181)},function(e,t,n){e.exports=a;var d=n(184).EventEmitter;function a(){d.call(this)}n(104)(a,d),a.Readable=n(185),a.Writable=n(701),a.Duplex=n(702),a.Transform=n(703),a.PassThrough=n(704),(a.Stream=a).prototype.pipe=function(t,e){var n=this;function a(e){t.writable&&!1===t.write(e)&&n.pause&&n.pause()}function r(){n.readable&&n.resume&&n.resume()}n.on("data",a),t.on("drain",r),t._isStdio||e&&!1===e.end||(n.on("end",i),n.on("close",s));var o=!1;function i(){o||(o=!0,t.end())}function s(){o||(o=!0,"function"==typeof t.destroy&&t.destroy())}function l(e){if(u(),0===d.listenerCount(this,"error"))throw e}function u(){n.removeListener("data",a),t.removeListener("drain",r),n.removeListener("end",i),n.removeListener("close",s),n.removeListener("error",l),t.removeListener("error",l),n.removeListener("end",u),n.removeListener("close",u),t.removeListener("close",u)}return n.on("error",l),t.on("error",l),n.on("end",u),n.on("close",u),t.on("close",u),t.emit("pipe",n),t}},function(e,t){var n={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==n.call(e)}},function(e,t,n){"use strict";t.byteLength=function(e){var e=d(e),t=e[0],e=e[1];return 3*(t+e)/4-e},t.toByteArray=function(e){var t,n,a=d(e),r=a[0],a=a[1],o=new u(function(e,t){return 3*(e+t)/4-t}(r,a)),i=0,s=0>16&255,o[i++]=t>>8&255,o[i++]=255&t;2===a&&(t=l[e.charCodeAt(n)]<<2|l[e.charCodeAt(n+1)]>>4,o[i++]=255&t);1===a&&(t=l[e.charCodeAt(n)]<<10|l[e.charCodeAt(n+1)]<<4|l[e.charCodeAt(n+2)]>>2,o[i++]=t>>8&255,o[i++]=255&t);return o},t.fromByteArray=function(e){for(var t,n=e.length,a=n%3,r=[],o=0,i=n-a;o>18&63]+s[e>>12&63]+s[e>>6&63]+s[63&e]}(a));return r.join("")}(e,o,i>2]+s[t<<4&63]+"==")):2==a&&(t=(e[n-2]<<8)+e[n-1],r.push(s[t>>10]+s[t>>4&63]+s[t<<2&63]+"="));return r.join("")};for(var s=[],l=[],u="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r=0,o=a.length;r=e.length?{value:void 0,done:!0}:(e=a(e,t),this._i+=e.length,{value:e,done:!1})})},function(e,t,n){var o=n(153),i=n(152);e.exports=function(r){return function(e,t){var n,e=String(i(e)),t=o(t),a=e.length;return t<0||a<=t?r?"":void 0:(n=e.charCodeAt(t))<55296||56319=e.length?(this._t=void 0,r(1)):r(0,"keys"==t?n:"values"==t?e[n]:[n,e[n]])},"values"),o.Arguments=o.Array,a("keys"),a("values"),a("entries")},function(e,t){e.exports=function(){}},function(e,t){e.exports=function(e,t){return{value:t,done:!!e}}},function(e,t,n){e.exports={default:n(500),__esModule:!0}},function(e,t,n){n(501),n(506),n(507),n(508),e.exports=n(81).Symbol},function(I,A,e){"use strict";function a(e){var t=T[e]=_(M[E]);return t._k=e,t}function n(e,t){m(e);for(var n,a=B(t=g(t)),r=0,o=a.length;rr;)l(T,t=n[r++])||t==x||t==H||a.push(t);return a}function i(e){for(var t,n=e===O,a=X(n?L:g(e)),r=[],o=0;a.length>o;)!l(T,t=a[o++])||n&&!l(O,t)||r.push(T[t]);return r}var s=e(80),l=e(90),u=e(82),c=e(96),R=e(211),H=e(502).KEY,d=e(113),f=e(155),p=e(161),F=e(129),h=e(100),z=e(162),W=e(163),B=e(503),U=e(504),m=e(112),V=e(98),K=e(158),g=e(99),y=e(151),v=e(126),_=e(160),q=e(505),G=e(213),b=e(157),$=e(89),J=e(127),Q=G.f,w=$.f,X=q.f,M=s.Symbol,k=s.JSON,S=k&&k.stringify,E="prototype",x=h("_hidden"),Z=h("toPrimitive"),ee={}.propertyIsEnumerable,C=f("symbol-registry"),T=f("symbols"),L=f("op-symbols"),O=Object[E],f="function"==typeof M&&!!b.f,D=s.QObject,N=!D||!D[E]||!D[E].findChild,P=u&&d(function(){return 7!=_(w({},"a",{get:function(){return w(this,"a",{value:7}).a}})).a})?function(e,t,n){var a=Q(O,t);a&&delete O[t],w(e,t,n),a&&e!==O&&w(O,t,a)}:w,j=f&&"symbol"==typeof M.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof M},Y=function(e,t,n){return e===O&&Y(L,t,n),m(e),t=y(t,!0),m(n),(l(T,t)?(n.enumerable?(l(e,x)&&e[x][t]&&(e[x][t]=!1),n=_(n,{enumerable:v(0,!1)})):(l(e,x)||w(e,x,v(1,{})),e[x][t]=!0),P):w)(e,t,n)};f||(R((M=function(){if(this instanceof M)throw TypeError("Symbol is not a constructor!");var t=F(0ne;)h(te[ne++]);for(var ae=J(h.store),re=0;ae.length>re;)W(ae[re++]);c(c.S+c.F*!f,"Symbol",{for:function(e){return l(C,e+="")?C[e]:C[e]=M(e)},keyFor:function(e){if(!j(e))throw TypeError(e+" is not a symbol!");for(var t in C)if(C[t]===e)return t},useSetter:function(){N=!0},useSimple:function(){N=!1}}),c(c.S+c.F*!f,"Object",{create:function(e,t){return void 0===t?_(e):n(_(e),t)},defineProperty:Y,defineProperties:n,getOwnPropertyDescriptor:r,getOwnPropertyNames:o,getOwnPropertySymbols:i});D=d(function(){b.f(1)});c(c.S+c.F*D,"Object",{getOwnPropertySymbols:function(e){return b.f(K(e))}}),k&&c(c.S+c.F*(!f||d(function(){var e=M();return"[null]"!=S([e])||"{}"!=S({a:e})||"{}"!=S(Object(e))})),"JSON",{stringify:function(e){for(var t,n,a=[e],r=1;ri;)o.call(e,a=r[i++])&&t.push(a);return t}},function(e,t,n){var a=n(209);e.exports=Array.isArray||function(e){return"Array"==a(e)}},function(e,t,n){var a=n(99),r=n(212).f,o={}.toString,i="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];e.exports.f=function(e){if(!i||"[object Window]"!=o.call(e))return r(a(e));try{return r(e)}catch(e){return i.slice()}}},function(e,t){},function(e,t,n){n(163)("asyncIterator")},function(e,t,n){n(163)("observable")},function(e,t,n){e.exports={default:n(510),__esModule:!0}},function(e,t,n){n(511),e.exports=n(81).Object.setPrototypeOf},function(e,t,n){var a=n(96);a(a.S,"Object",{setPrototypeOf:n(512).set})},function(e,t,r){function o(e,t){if(a(e),!n(t)&&null!==t)throw TypeError(t+": can't set as prototype!")}var n=r(98),a=r(112);e.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(e,n,a){try{(a=r(204)(Function.call,r(213).f(Object.prototype,"__proto__").set,2))(e,[]),n=!(e instanceof Array)}catch(e){n=!0}return function(e,t){return o(e,t),n?e.__proto__=t:a(e,t),e}}({},!1):void 0),check:o}},function(e,t,n){e.exports={default:n(514),__esModule:!0}},function(e,t,n){n(515);var a=n(81).Object;e.exports=function(e,t){return a.create(e,t)}},function(e,t,n){var a=n(96);a(a.S,"Object",{create:n(160)})},function(e,t,n){"use strict";var i=n(517);function a(){}function r(){}r.resetWarningCache=a,e.exports=function(){function e(e,t,n,a,r,o){if(o!==i)throw(o=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types")).name="Invariant Violation",o}function t(){return e}var n={array:e.isRequired=e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:r,resetWarningCache:a};return n.PropTypes=n}},function(e,t,n){"use strict";e.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},function(e,t,n){"use strict";function l(e,t,n,a){e.removeEventListener&&e.removeEventListener(t,n,a||!1)}function a(e,t,n,a){return e.addEventListener&&e.addEventListener(t,n,a||!1),{off:function(){return l(e,t,n,a)}}}t.__esModule=!0,t.on=a,t.once=function(r,o,i,s){return a(r,o,function e(){for(var t=arguments.length,n=Array(t),a=0;a68?1900:2e3)},r=function(t){return function(e){this[t]=+e}},o=[/[+-]\d\d:?(\d\d)?|Z/,function(e){(this.zone||(this.zone={})).offset=function(e){if(!e)return 0;if("Z"===e)return 0;var t=e.match(/([+-]|\d\d)/g),n=60*t[1]+(+t[2]||0);return 0===n?0:"+"===t[0]?-n:n}(e)}],i=function(e){var t=h[e];return t&&(t.indexOf?t:t.s.concat(t.f))},s=function(e,t){var n,a=h.meridiem;if(a){for(var r=1;r<=24;r+=1)if(e.indexOf(a(r,0,t))>-1){n=r>12;break}}else n=e===(t?"pm":"PM");return n},f={A:[n,function(e){this.afternoon=s(e,!1)}],a:[n,function(e){this.afternoon=s(e,!0)}],S:[/\d/,function(e){this.milliseconds=100*+e}],SS:[e,function(e){this.milliseconds=10*+e}],SSS:[/\d{3}/,function(e){this.milliseconds=+e}],s:[t,r("seconds")],ss:[t,r("seconds")],m:[t,r("minutes")],mm:[t,r("minutes")],H:[t,r("hours")],h:[t,r("hours")],HH:[t,r("hours")],hh:[t,r("hours")],D:[t,r("day")],DD:[e,r("day")],Do:[n,function(e){var t=h.ordinal,n=e.match(/\d+/);if(this.day=n[0],t)for(var a=1;a<=31;a+=1)t(a).replace(/\[|\]/g,"")===e&&(this.day=a)}],M:[t,r("month")],MM:[e,r("month")],MMM:[n,function(e){var t=i("months"),n=(i("monthsShort")||t.map(function(e){return e.slice(0,3)})).indexOf(e)+1;if(n<1)throw new Error;this.month=n%12||n}],MMMM:[n,function(e){var t=i("months").indexOf(e)+1;if(t<1)throw new Error;this.month=t%12||t}],Y:[/[+-]?\d+/,r("year")],YY:[e,function(e){this.year=a(e)}],YYYY:[/\d{4}/,r("year")],Z:o,ZZ:o};function b(e){var t,r;t=e,r=h&&h.formats;for(var u=(e=t.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,function(e,t,n){var a=n&&n.toUpperCase();return t||r[n]||l[n]||r[a].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,function(e,t,n){return t||n.slice(1)})})).match(d),c=u.length,n=0;n-1)return new Date(("X"===t?1e3:1)*e);var a=b(t)(e),r=a.year,o=a.month,i=a.day,s=a.hours,l=a.minutes,u=a.seconds,c=a.milliseconds,d=a.zone,f=new Date,p=i||(r||o?1:f.getDate()),h=r||f.getFullYear(),m=0;r&&!o||(m=o>0?o-1:f.getMonth());var g=s||0,y=l||0,v=u||0,_=c||0;return d?new Date(Date.UTC(h,m,p,g,y,v,_+60*d.offset*1e3)):n?new Date(Date.UTC(h,m,p,g,y,v,_)):new Date(h,m,p,g,y,v,_)}catch(e){return new Date("")}}(t,r,n),this.init(),l&&!0!==l&&(this.$L=this.locale(l).$L),s&&t!=this.format(r)&&(this.$d=new Date("")),h={}}else if(r instanceof Array)for(var u=r.length,c=1;c<=u;c+=1){a[1]=r[c-1];var d=f.apply(this,a);if(d.isValid()){this.$d=d.$d,this.$L=d.$L,this.init();break}c===u&&(this.$d=new Date(""))}else p.call(this,e)}}}()},function(e,t,n){e.exports=function(){"use strict";return function(e,t,a){a.updateLocale=function(e,t){var n=a.Ls[e];if(n)return(t?Object.keys(t):[]).forEach(function(e){n[e]=t[e]}),n}}}()},function(e,t,n){e.exports=function(e,t,n){function a(e,t,n,a,r){var o,e=e.name?e:e.$locale(),t=s(e[t]),n=s(e[n]),i=t||n.map(function(e){return e.slice(0,a)});return r?(o=e.weekStart,i.map(function(e,t){return i[(t+(o||0))%7]})):i}function r(){return n.Ls[n.locale()]}function o(e,t){return e.formats[t]||e.formats[t.toUpperCase()].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,function(e,t,n){return t||n.slice(1)})}var t=t.prototype,s=function(e){return e&&(e.indexOf?e:e.s)};t.localeData=function(){return function(){var t=this;return{months:function(e){return e?e.format("MMMM"):a(t,"months")},monthsShort:function(e){return e?e.format("MMM"):a(t,"monthsShort","months",3)},firstDayOfWeek:function(){return t.$locale().weekStart||0},weekdays:function(e){return e?e.format("dddd"):a(t,"weekdays")},weekdaysMin:function(e){return e?e.format("dd"):a(t,"weekdaysMin","weekdays",2)},weekdaysShort:function(e){return e?e.format("ddd"):a(t,"weekdaysShort","weekdays",3)},longDateFormat:function(e){return o(t.$locale(),e)},meridiem:this.$locale().meridiem,ordinal:this.$locale().ordinal}}.bind(this)()},n.localeData=function(){var t=r();return{firstDayOfWeek:function(){return t.weekStart||0},weekdays:function(){return n.weekdays()},weekdaysShort:function(){return n.weekdaysShort()},weekdaysMin:function(){return n.weekdaysMin()},months:function(){return n.months()},monthsShort:function(){return n.monthsShort()},longDateFormat:function(e){return o(t,e)},meridiem:t.meridiem,ordinal:t.ordinal}},n.months=function(){return a(r(),"months")},n.monthsShort=function(){return a(r(),"monthsShort","months",3)},n.weekdays=function(e){return a(r(),"weekdays",null,null,e)},n.weekdaysShort=function(e){return a(r(),"weekdaysShort","weekdays",3,e)},n.weekdaysMin=function(e){return a(r(),"weekdaysMin","weekdays",2,e)}}},function(e,t,n){e.exports=function(){"use strict";var i="month",s="quarter";return function(e,t){var n=t.prototype;n.quarter=function(e){return this.$utils().u(e)?Math.ceil((this.month()+1)/3):this.month(this.month()%3+3*(e-1))};var a=n.add;n.add=function(e,t){return e=Number(e),this.$utils().p(t)===s?this.add(3*e,i):a.bind(this)(e,t)};var o=n.startOf;n.startOf=function(e,t){var n=this.$utils(),a=!!n.u(t)||t;if(n.p(e)===s){var r=this.quarter()-1;return a?this.month(3*r).startOf(i).startOf("day"):this.month(3*r+2).endOf(i).endOf("day")}return o.bind(this)(e,t)}}}()},function(e,t,n){e.exports=function(){"use strict";return function(e,t){var n=t.prototype,o=n.format;n.format=function(e){var t=this,n=this.$locale();if(!this.isValid())return o.bind(this)(e);var a=this.$utils(),r=(e||"YYYY-MM-DDTHH:mm:ssZ").replace(/\[([^\]]+)]|Q|wo|ww|w|WW|W|zzz|z|gggg|GGGG|Do|X|x|k{1,2}|S/g,function(e){switch(e){case"Q":return Math.ceil((t.$M+1)/3);case"Do":return n.ordinal(t.$D);case"gggg":return t.weekYear();case"GGGG":return t.isoWeekYear();case"wo":return n.ordinal(t.week(),"W");case"w":case"ww":return a.s(t.week(),"w"===e?1:2,"0");case"W":case"WW":return a.s(t.isoWeek(),"W"===e?1:2,"0");case"k":case"kk":return a.s(String(0===t.$H?24:t.$H),"k"===e?1:2,"0");case"X":return Math.floor(t.$d.getTime()/1e3);case"x":return t.$d.getTime();case"z":return"["+t.offsetName()+"]";case"zzz":return"["+t.offsetName("long")+"]";default:return e}});return o.bind(this)(r)}}}()},function(e,t,n){e.exports=function(){"use strict";var s="week",l="year";return function(e,t,i){var n=t.prototype;n.week=function(e){if(void 0===e&&(e=null),null!==e)return this.add(7*(e-this.week()),"day");var t=this.$locale().yearStart||1;if(11===this.month()&&this.date()>25){var n=i(this).startOf(l).add(1,l).date(t),a=i(this).endOf(s);if(n.isBefore(a))return 1}var r=i(this).startOf(l).date(t).startOf(s).subtract(1,"millisecond"),o=this.diff(r,s,!0);return o<0?i(this).startOf("week").week():Math.ceil(o)},n.weeks=function(e){return void 0===e&&(e=null),this.week(e)}}}()},function(e,t,n){e.exports=function(e){"use strict";function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=t(e),a={name:"zh-cn",weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"周日_周一_周二_周三_周四_周五_周六".split("_"),weekdaysMin:"日_一_二_三_四_五_六".split("_"),months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),ordinal:function(e,t){return"W"===t?e+"周":e+"日"},weekStart:1,yearStart:4,formats:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY/MM/DD",LL:"YYYY年M月D日",LLL:"YYYY年M月D日Ah点mm分",LLLL:"YYYY年M月D日ddddAh点mm分",l:"YYYY/M/D",ll:"YYYY年M月D日",lll:"YYYY年M月D日 HH:mm",llll:"YYYY年M月D日dddd HH:mm"},relativeTime:{future:"%s内",past:"%s前",s:"几秒",m:"1 分钟",mm:"%d 分钟",h:"1 小时",hh:"%d 小时",d:"1 天",dd:"%d 天",M:"1 个月",MM:"%d 个月",y:"1 年",yy:"%d 年"},meridiem:function(e,t){var n=100*e+t;return n<600?"凌晨":n<900?"早上":n<1100?"上午":n<1300?"中午":n<1800?"下午":"晚上"}};return n.default.locale(a,null,!0),a}(n(219))},function(e,t,n){"use strict";t.__esModule=!0,t.flex=t.transition=t.animation=void 0;var r=n(215),o=n(101);function a(e){var n,a;return!!r.hasDOM&&(n=document.createElement("div"),(a=!1,o.each)(e,function(e,t){if(void 0!==n.style[t])return!(a={end:e})}),a)}var i,s;t.animation=a({WebkitAnimation:"webkitAnimationEnd",OAnimation:"oAnimationEnd",animation:"animationend"}),t.transition=a({WebkitTransition:"webkitTransitionEnd",OTransition:"oTransitionEnd",transition:"transitionend"}),t.flex=(n={display:["flex","-webkit-flex","-moz-flex","-ms-flexbox"]},!!r.hasDOM&&(i=document.createElement("div"),(s=!1,o.each)(n,function(e,t){return(0,o.each)(e,function(e){try{i.style[t]=e,s=s||i.style[t]===e}catch(e){}return!s}),!s}),s))},function(e,t,n){"use strict";t.__esModule=!0,t.getFocusNodeList=i,t.saveLastFocusNode=function(){s=document.activeElement},t.clearLastFocusNode=function(){s=null},t.backLastFocusNode=function(){if(s)try{s.focus()}catch(e){}},t.limitTabRange=function(e,t){{var n,a;t.keyCode===r.default.TAB&&(e=i(e),n=e.length-1,-1<(a=e.indexOf(document.activeElement)))&&(a=a+(t.shiftKey?-1:1),e[a=n<(a=a<0?n:a)?0:a].focus(),t.preventDefault())}};var t=n(220),r=(t=t)&&t.__esModule?t:{default:t},a=n(101);function o(e){var t=e.nodeName.toLowerCase(),n=parseInt(e.getAttribute("tabindex"),10),n=!isNaN(n)&&-1a.height)&&(r[1]=-t.top-("t"===e?t.height:0)),r},this._getParentScrollOffset=function(e){var t=0,n=0;return e&&e.offsetParent&&e.offsetParent!==document.body&&(isNaN(e.offsetParent.scrollTop)||(t+=e.offsetParent.scrollTop),isNaN(e.offsetParent.scrollLeft)||(n+=e.offsetParent.scrollLeft)),{top:t,left:n}}};var p=a;function h(e){(0,o.default)(this,h),r.call(this),this.pinElement=e.pinElement,this.baseElement=e.baseElement,this.pinFollowBaseElementWhenFixed=e.pinFollowBaseElementWhenFixed,this.container=function(e){var t=e.container,e=e.baseElement;if("undefined"==typeof document)return t;for(var n=(n=(0,i.default)(t,e))||document.body;"static"===y.dom.getStyle(n,"position");){if(!n||n===document.body)return document.body;n=n.parentNode}return n}(e),this.autoFit=e.autoFit||!1,this.align=e.align||"tl tl",this.offset=e.offset||[0,0],this.needAdjust=e.needAdjust||!1,this.isRtl=e.isRtl||!1}t.default=p,e.exports=t.default},function(e,t,n){"use strict";t.__esModule=!0;var w=a(n(3)),M=a(n(16)),k=n(0),S=a(k),E=a(n(18)),x=a(n(196)),C=a(n(83)),T=n(11);function a(e){return e&&e.__esModule?e:{default:e}}t.default=function(e){var t,n,a,r,o,i,s,l,u,c,d,f,p,h,m,g,y,v,_,b;return k.useState&&k.useRef&&k.useEffect?(t=void 0===(t=e.prefix)?"next-":t,r=e.animation,n=void 0===r?{in:"expandInDown",out:"expandOutUp"}:r,a=e.visible,r=e.hasMask,o=e.align,o=void 0===(s=e.points)?o?o.split(" "):void 0:s,i=e.onPosition,s=e.children,b=e.className,l=e.style,u=e.wrapperClassName,c=e.beforeOpen,d=e.onOpen,f=e.afterOpen,p=e.beforeClose,h=e.onClose,m=e.afterClose,e=(0,M.default)(e,["prefix","animation","visible","hasMask","align","points","onPosition","children","className","style","wrapperClassName","beforeOpen","onOpen","afterOpen","beforeClose","onClose","afterClose"]),g=(_=(0,k.useState)(!0))[0],y=_[1],v=(0,k.useRef)(null),_=S.default.createElement(C.default.OverlayAnimate,{visible:a,animation:n,onEnter:function(){y(!1),"function"==typeof c&&c(v.current)},onEntering:function(){"function"==typeof d&&d(v.current)},onEntered:function(){"function"==typeof f&&f(v.current)},onExit:function(){"function"==typeof p&&p(v.current)},onExiting:function(){"function"==typeof h&&h(v.current)},onExited:function(){y(!0),"function"==typeof m&&m(v.current)},timeout:300,style:l},s?(0,k.cloneElement)(s,{className:(0,E.default)([t+"overlay-inner",b,s&&s.props&&s.props.className])}):S.default.createElement("span",null)),b=(0,E.default)(((l={})[t+"overlay-wrapper v2"]=!0,l[u]=u,l.opened=a,l)),S.default.createElement(x.default,(0,w.default)({},e,{visible:a,isAnimationEnd:g,hasMask:r,wrapperClassName:b,maskClassName:t+"overlay-backdrop",maskRender:function(e){return S.default.createElement(C.default.OverlayAnimate,{visible:a,animation:!!n&&{in:"fadeIn",out:"fadeOut"},timeout:300,unmountOnExit:!0},e)},points:o,onPosition:function(e){(0,w.default)(e,{align:e.config.points}),"function"==typeof i&&i(e)},ref:v}),_)):(T.log.warning("need react version > 16.8.0"),null)},e.exports=t.default},function(n,e){function a(e,t){return n.exports=a=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},n.exports.__esModule=!0,n.exports.default=n.exports,a(e,t)}n.exports=a,n.exports.__esModule=!0,n.exports.default=n.exports},function(e,t,n){"use strict";t.__esModule=!0;var a,c=g(n(16)),d=g(n(3)),r=g(n(4)),o=g(n(7)),i=g(n(8)),l=n(0),f=g(l),p=n(24),s=n(30),u=g(n(5)),h=n(11),m=g(n(362));function g(e){return e&&e.__esModule?e:{default:e}}var y,n=h.func.noop,v=h.func.makeChain,_=h.func.bindCtx,u=(y=l.Component,(0,i.default)(b,y),b.getDerivedStateFromProps=function(e,t){return"visible"in e?(0,d.default)({},t,{visible:e.visible}):null},b.prototype.componentWillUnmount=function(){var t=this;["_timer","_hideTimer","_showTimer"].forEach(function(e){t[e]&&clearTimeout(t[e])})},b.prototype.handleVisibleChange=function(e,t,n){"visible"in this.props||this.setState({visible:e}),this.props.onVisibleChange(e,t,n)},b.prototype.handleTriggerClick=function(e){this.state.visible&&!this.props.canCloseByTrigger||this.handleVisibleChange(!this.state.visible,"fromTrigger",e)},b.prototype.handleTriggerKeyDown=function(e){var t=this.props.triggerClickKeycode;(Array.isArray(t)?t:[t]).includes(e.keyCode)&&(e.preventDefault(),this.handleTriggerClick(e))},b.prototype.handleTriggerMouseEnter=function(e){var t=this;this._mouseNotFirstOnMask=!1,this._hideTimer&&(clearTimeout(this._hideTimer),this._hideTimer=null),this._showTimer&&(clearTimeout(this._showTimer),this._showTimer=null),this.state.visible||(this._showTimer=setTimeout(function(){t.handleVisibleChange(!0,"fromTrigger",e)},this.props.delay))},b.prototype.handleTriggerMouseLeave=function(e,t){var n=this;this._showTimer&&(clearTimeout(this._showTimer),this._showTimer=null),this.state.visible&&(this._hideTimer=setTimeout(function(){n.handleVisibleChange(!1,t||"fromTrigger",e)},this.props.delay))},b.prototype.handleTriggerFocus=function(e){this.handleVisibleChange(!0,"fromTrigger",e)},b.prototype.handleTriggerBlur=function(e){this._isForwardContent||this.handleVisibleChange(!1,"fromTrigger",e),this._isForwardContent=!1},b.prototype.handleContentMouseDown=function(){this._isForwardContent=!0},b.prototype.handleContentMouseEnter=function(){clearTimeout(this._hideTimer)},b.prototype.handleContentMouseLeave=function(e){this.handleTriggerMouseLeave(e,"fromContent")},b.prototype.handleMaskMouseEnter=function(){this._mouseNotFirstOnMask||(clearTimeout(this._hideTimer),this._hideTimer=null,this._mouseNotFirstOnMask=!1)},b.prototype.handleMaskMouseLeave=function(){this._mouseNotFirstOnMask=!0},b.prototype.handleRequestClose=function(e,t){this.handleVisibleChange(!1,e,t)},b.prototype.renderTrigger=function(){var e,t,n,a,r,o,i,s=this,l=this.props,u=l.trigger,l=l.disabled,c={key:"trigger","aria-haspopup":!0,"aria-expanded":this.state.visible};return this.state.visible||(c["aria-describedby"]=void 0),l||(l=this.props.triggerType,l=Array.isArray(l)?l:[l],e=u&&u.props||{},t=e.onClick,n=e.onKeyDown,a=e.onMouseEnter,r=e.onMouseLeave,o=e.onFocus,i=e.onBlur,l.forEach(function(e){switch(e){case"click":c.onClick=v(s.handleTriggerClick,t),c.onKeyDown=v(s.handleTriggerKeyDown,n);break;case"hover":c.onMouseEnter=v(s.handleTriggerMouseEnter,a),c.onMouseLeave=v(s.handleTriggerMouseLeave,r);break;case"focus":c.onFocus=v(s.handleTriggerFocus,o),c.onBlur=v(s.handleTriggerBlur,i)}})),u&&f.default.cloneElement(u,c)},b.prototype.renderContent=function(){var t=this,e=this.props,n=e.children,e=e.triggerType,e=Array.isArray(e)?e:[e],n=l.Children.only(n),a=n.props,r=a.onMouseDown,o=a.onMouseEnter,i=a.onMouseLeave,s={key:"portal"};return e.forEach(function(e){switch(e){case"focus":s.onMouseDown=v(t.handleContentMouseDown,r);break;case"hover":s.onMouseEnter=v(t.handleContentMouseEnter,o),s.onMouseLeave=v(t.handleContentMouseLeave,i)}}),f.default.cloneElement(n,s)},b.prototype.renderPortal=function(){function e(){return(0,p.findDOMNode)(t)}var t=this,n=this.props,a=n.target,r=n.safeNode,o=n.followTrigger,i=n.triggerType,s=n.hasMask,l=n.wrapperStyle,n=(0,c.default)(n,["target","safeNode","followTrigger","triggerType","hasMask","wrapperStyle"]),u=this.props.container,r=Array.isArray(r)?[].concat(r):[r],l=(r.unshift(e),l||{});return o&&(u=function(e){return e&&e.parentNode||e},l.position="relative"),"hover"===i&&s&&(n.onMaskMouseEnter=this.handleMaskMouseEnter,n.onMaskMouseLeave=this.handleMaskMouseLeave),f.default.createElement(m.default,(0,d.default)({},n,{key:"overlay",ref:function(e){return t.overlay=e},visible:this.state.visible,target:a||e,container:u,safeNode:r,wrapperStyle:l,triggerType:i,hasMask:s,onRequestClose:this.handleRequestClose}),this.props.children&&this.renderContent())},b.prototype.render=function(){return[this.renderTrigger(),this.renderPortal()]},a=i=b,i.propTypes={children:u.default.node,trigger:u.default.element,triggerType:u.default.oneOfType([u.default.string,u.default.array]),triggerClickKeycode:u.default.oneOfType([u.default.number,u.default.array]),visible:u.default.bool,defaultVisible:u.default.bool,onVisibleChange:u.default.func,disabled:u.default.bool,autoFit:u.default.bool,delay:u.default.number,canCloseByTrigger:u.default.bool,target:u.default.any,safeNode:u.default.any,followTrigger:u.default.bool,container:u.default.any,hasMask:u.default.bool,wrapperStyle:u.default.object,rtl:u.default.bool,v2:u.default.bool,placement:u.default.string,placementOffset:u.default.number,autoAdjust:u.default.bool},i.defaultProps={triggerType:"hover",triggerClickKeycode:[h.KEYCODE.SPACE,h.KEYCODE.ENTER],defaultVisible:!1,onVisibleChange:n,disabled:!1,autoFit:!1,delay:200,canCloseByTrigger:!0,followTrigger:!1,container:function(){return document.body},rtl:!1},a);function b(e){(0,r.default)(this,b);var t=(0,o.default)(this,y.call(this,e));return t.state={visible:void 0===e.visible?e.defaultVisible:e.visible},_(t,["handleTriggerClick","handleTriggerKeyDown","handleTriggerMouseEnter","handleTriggerMouseLeave","handleTriggerFocus","handleTriggerBlur","handleContentMouseEnter","handleContentMouseLeave","handleContentMouseDown","handleRequestClose","handleMaskMouseEnter","handleMaskMouseLeave"]),t}u.displayName="Popup",t.default=(0,s.polyfill)(u),e.exports=t.default},function(e,t,n){"use strict";t.__esModule=!0;var L=a(n(3)),O=a(n(16)),D=n(0),N=a(D),P=a(n(18)),j=a(n(196)),Y=a(n(83)),I=n(11);function a(e){return e&&e.__esModule?e:{default:e}}t.default=function(r){var e,t,o,n,a,i,s,l,u,c,d,f,p,h,m,g,y,v,_,b,w,M,k,S,E,x,C,T;return D.useState&&D.useRef&&D.useEffect?(e=void 0===(e=r.prefix)?"next-":e,E=r.animation,t=void 0===E?{in:"expandInDown",out:"expandOutUp"}:E,E=r.defaultVisible,x=r.onVisibleChange,o=void 0===x?function(){}:x,x=r.trigger,n=void 0===(n=r.triggerType)?"hover":n,C=r.overlay,a=r.onPosition,T=r.children,i=r.className,s=r.style,l=r.wrapperClassName,u=r.triggerClickKeycode,c=r.align,d=r.beforeOpen,f=r.onOpen,p=r.afterOpen,h=r.beforeClose,m=r.onClose,g=r.afterClose,y=(0,O.default)(r,["prefix","animation","defaultVisible","onVisibleChange","trigger","triggerType","overlay","onPosition","children","className","style","wrapperClassName","triggerClickKeycode","align","beforeOpen","onOpen","afterOpen","beforeClose","onClose","afterClose"]),E=(0,D.useState)(E),v=E[0],_=E[1],E=(0,D.useState)(t),b=E[0],w=E[1],M=(E=(0,D.useState)(!0))[0],k=E[1],S=(0,D.useRef)(null),(0,D.useEffect)(function(){"visible"in r&&_(r.visible)},[r.visible]),(0,D.useEffect)(function(){"animation"in r&&b!==t&&w(t)},[t]),E=C?T:x,x=N.default.createElement(Y.default.OverlayAnimate,{visible:v,animation:b,timeout:200,onEnter:function(){k(!1),"function"==typeof d&&d(S.current)},onEntering:function(){"function"==typeof f&&f(S.current)},onEntered:function(){"function"==typeof p&&p(S.current)},onExit:function(){"function"==typeof h&&h(S.current)},onExiting:function(){"function"==typeof m&&m(S.current)},onExited:function(){k(!0),"function"==typeof g&&g(S.current)},style:s},(x=C||T)?(0,D.cloneElement)(x,{className:(0,P.default)([e+"overlay-inner",i,x&&x.props&&x.props.className])}):N.default.createElement("span",null)),C=(0,P.default)(((s={})[e+"overlay-wrapper v2"]=!0,s[l]=l,s.opened=v,s)),T={},c&&(T.points=c.split(" ")),N.default.createElement(j.default.Popup,(0,L.default)({},y,T,{wrapperClassName:C,overlay:x,visible:v,isAnimationEnd:M,triggerType:n,onVisibleChange:function(e){for(var t=arguments.length,n=Array(1 16.8.0"),null)},e.exports=t.default},function(e,t,n){"use strict";t.__esModule=!0;var l=a(n(3)),u=a(n(16)),o=n(0),c=a(o),i=a(n(24)),s=a(n(6)),d=a(n(83)),f=a(n(165)),p=n(11);function a(e){return e&&e.__esModule?e:{default:e}}var h={top:8,maxCount:0,duration:3e3},m=s.default.config(function(e){var t=e.prefix,s=void 0===t?"next-":t,t=e.dataSource,a=void 0===t?[]:t,r=(0,o.useState)()[1];return a.forEach(function(n){n.timer||(n.timer=setTimeout(function(){var e,t=a.indexOf(n);-1a&&y.shift(),i.default.render(c.default.createElement(s.default,s.default.getContext(),c.default.createElement(m,{dataSource:y})),g),{key:n,close:function(){r.timer&&clearTimeout(r.timer);var e=y.indexOf(r);-1 16.8.0")}},e.exports=t.default},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){"use strict";n(565)},function(e,t,n){},function(e,t,n){},function(e,t,n){"use strict";t.__esModule=!0,t.default=void 0;var p=l(n(3)),r=l(n(4)),o=l(n(7)),a=l(n(8)),h=l(n(42)),m=l(n(0)),i=l(n(5)),g=l(n(18)),y=n(11),s=l(n(28)),v=l(n(368));function l(e){return e&&e.__esModule?e:{default:e}}function _(e,r){var o=r.size,i=r.device,s=r.labelAlign,l=r.labelTextAlign,u=r.labelCol,c=r.wrapperCol,d=r.responsive,f=r.colon;return m.default.Children.map(e,function(e){var t,n,a;return y.obj.isReactFragment(e)?_(e.props.children,r):e&&-1<["function","object"].indexOf((0,h.default)(e.type))&&"form_item"===e.type._typeMark?(t={labelCol:e.props.labelCol||u,wrapperCol:e.props.wrapperCol||c,labelAlign:e.props.labelAlign||("phone"===i?"top":s),labelTextAlign:e.props.labelTextAlign||l,colon:"colon"in e.props?e.props.colon:f,size:e.props.size||o,responsive:d},m.default.cloneElement(e,(n=t,a={},Object.keys(n).forEach(function(e){void 0!==n[e]&&(a[e]=n[e])}),a))):e})}u=m.default.Component,(0,a.default)(b,u),b.prototype.getChildContext=function(){return{_formField:this.props.field||this._formField,_formSize:this.props.size,_formDisabled:this.props.disabled,_formPreview:this.props.isPreview,_formFullWidth:this.props.fullWidth,_formLabelForErrorMessage:this.props.useLabelForErrorMessage}},b.prototype.componentDidUpdate=function(e){var t=this.props;this._formField&&("value"in t&&t.value!==e.value&&this._formField.setValues(t.value),"error"in t)&&t.error!==e.error&&this._formField.setValues(t.error)},b.prototype.render=function(){var e=this.props,t=e.className,n=e.inline,a=e.size,r=(e.device,e.labelAlign,e.labelTextAlign,e.onSubmit),o=e.children,i=(e.labelCol,e.wrapperCol,e.style),s=e.prefix,l=e.rtl,u=e.isPreview,c=e.component,d=e.responsive,f=e.gap,n=(e.colon,(0,g.default)(((e={})[s+"form"]=!0,e[s+"inline"]=n,e[""+s+a]=a,e[s+"form-responsive-grid"]=d,e[s+"form-preview"]=u,e[t]=!!t,e))),a=_(o,this.props);return m.default.createElement(c,(0,p.default)({role:"grid"},y.obj.pickOthers(b.propTypes,this.props),{className:n,style:i,dir:l?"rtl":void 0,onSubmit:r}),d?m.default.createElement(v.default,{gap:f},a):a)},a=n=b,n.propTypes={prefix:i.default.string,inline:i.default.bool,size:i.default.oneOf(["large","medium","small"]),fullWidth:i.default.bool,labelAlign:i.default.oneOf(["top","left","inset"]),labelTextAlign:i.default.oneOf(["left","right"]),field:i.default.any,saveField:i.default.func,labelCol:i.default.object,wrapperCol:i.default.object,onSubmit:i.default.func,children:i.default.any,className:i.default.string,style:i.default.object,value:i.default.object,onChange:i.default.func,component:i.default.oneOfType([i.default.string,i.default.func]),fieldOptions:i.default.object,rtl:i.default.bool,device:i.default.oneOf(["phone","tablet","desktop"]),responsive:i.default.bool,isPreview:i.default.bool,useLabelForErrorMessage:i.default.bool,colon:i.default.bool,disabled:i.default.bool,gap:i.default.oneOfType([i.default.arrayOf(i.default.number),i.default.number])},n.defaultProps={prefix:"next-",onSubmit:function(e){e.preventDefault()},size:"medium",labelAlign:"left",onChange:y.func.noop,component:"form",saveField:y.func.noop,device:"desktop",colon:!1,disabled:!1},n.childContextTypes={_formField:i.default.object,_formSize:i.default.string,_formDisabled:i.default.bool,_formPreview:i.default.bool,_formFullWidth:i.default.bool,_formLabelForErrorMessage:i.default.bool};var u,n=a;function b(e){(0,r.default)(this,b);var t,n,a=(0,o.default)(this,u.call(this,e));return a.onChange=function(e,t){a.props.onChange(a._formField.getValues(),{name:e,value:t,field:a._formField})},a._formField=null,!1!==e.field&&(t=(0,p.default)({},e.fieldOptions,{onChange:a.onChange}),e.field?(a._formField=e.field,n=a._formField.options.onChange,t.onChange=y.func.makeChain(n,a.onChange),a._formField.setOptions&&a._formField.setOptions(t)):("value"in e&&(t.values=e.value),a._formField=new s.default(a,t)),e.locale&&e.locale.Validate&&a._formField.setOptions({messages:e.locale.Validate}),e.saveField(a._formField)),a}n.displayName="Form",t.default=n,e.exports=t.default},function(e,t,n){"use strict";var a=n(91),m=(Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,a(n(169))),i=a(n(570)),r=a(n(170)),o=a(n(116)),b=a(n(171)),w=a(n(77)),s=a(n(366)),l=a(n(367)),g=a(n(577)),M=n(586),u={state:"",valueName:"value",trigger:"onChange",inputValues:[]},a=function(){function a(e){var t=this,n=1e.length)&&(t=e.length);for(var n=0,a=new Array(t);n=a.length?n:(o=a[r],n=e(t&&t[o],n,a,r+1),t?Array.isArray(t)?((a=[].concat(t))[o]=n,a):(0,l.default)({},t,(0,i.default)({},o,n)):((r=isNaN(o)?{}:[])[o]=n,r))};t=function(){};void 0!==e&&e.env,n.warning=t}.call(this,r(103))},function(e,t,n){"use strict";t.__esModule=!0,t.cloneAndAddKey=function(e){{var t;if(e&&(0,a.isValidElement)(e))return t=e.key||"error",(0,a.cloneElement)(e,{key:t})}return e},t.scrollToFirstError=function(e){var t=e.errorsGroup,n=e.options,a=e.instance;if(t&&n.scrollToFirstError){var r,o=void 0,i=void 0;for(r in t)if(t.hasOwnProperty(r)){var s=u.default.findDOMNode(a[r]);if(!s)return;var l=s.offsetTop;(void 0===i||l), use instead of.'),S.default.cloneElement(e,{className:t,size:d||C(r)})):(0,k.isValidElement)(e)?e:S.default.createElement("span",{className:a+"btn-helper"},e)}),t=c,_=(0,b.default)({},x.obj.pickOthers(Object.keys(T.propTypes),e),{type:o,disabled:p,onClick:h,className:(0,E.default)(n)});return"button"!==t&&(delete _.type,_.disabled)&&(delete _.onClick,_.href)&&delete _.href,S.default.createElement(t,(0,b.default)({},_,{dir:g?"rtl":void 0,onMouseUp:this.onMouseUp,ref:this.buttonRefHandler}),s,u)},a=n=T,n.propTypes=(0,b.default)({},s.default.propTypes,{prefix:r.default.string,rtl:r.default.bool,type:r.default.oneOf(["primary","secondary","normal"]),size:r.default.oneOf(["small","medium","large"]),icons:r.default.shape({loading:r.default.node}),iconSize:r.default.oneOfType([r.default.oneOf(["xxs","xs","small","medium","large","xl","xxl","xxxl","inherit"]),r.default.number]),htmlType:r.default.oneOf(["submit","reset","button"]),component:r.default.oneOf(["button","a","div","span"]),loading:r.default.bool,ghost:r.default.oneOf([!0,!1,"light","dark"]),text:r.default.bool,warning:r.default.bool,disabled:r.default.bool,onClick:r.default.func,className:r.default.string,onMouseUp:r.default.func,children:r.default.node}),n.defaultProps={prefix:"next-",type:"normal",size:"medium",icons:{},htmlType:"button",component:"button",loading:!1,ghost:!1,text:!1,warning:!1,disabled:!1,onClick:function(){}};var u,s=a;function T(){var e,t;(0,o.default)(this,T);for(var n=arguments.length,a=Array(n),r=0;ra[r])return!0;if(n[r] 0, or `null`');if(U(i,"numericSeparator")&&"boolean"!=typeof i.numericSeparator)throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var t=i.numericSeparator;if(void 0===n)return"undefined";if(null===n)return"null";if("boolean"==typeof n)return n?"true":"false";if("string"==typeof n)return function e(t,n){if(t.length>n.maxStringLength)return a=t.length-n.maxStringLength,a="... "+a+" more character"+(1"}if(z(n))return 0===n.length?"[]":(l=$(n,m),h&&!function(e){for(var t=0;t "+m(e,n))}),ne("Map",_.call(n),u,h)):function(e){if(w&&e&&"object"==typeof e)try{w.call(e);try{_.call(e)}catch(e){return 1}return e instanceof Set}catch(e){}return}(n)?(c=[],M&&M.call(n,function(e){c.push(m(e,n))}),ne("Set",w.call(n),c,h)):function(e){if(k&&e&&"object"==typeof e)try{k.call(e,k);try{S.call(e,S)}catch(e){return 1}return e instanceof WeakMap}catch(e){}return}(n)?q("WeakMap"):function(e){if(S&&e&&"object"==typeof e)try{S.call(e,S);try{k.call(e,k)}catch(e){return 1}return e instanceof WeakSet}catch(e){}return}(n)?q("WeakSet"):function(e){if(E&&e&&"object"==typeof e)try{return E.call(e),1}catch(e){}return}(n)?q("WeakRef"):"[object Number]"!==V(d=n)||j&&"object"==typeof d&&j in d?function(e){if(e&&"object"==typeof e&&D)try{return D.call(e),1}catch(e){}return}(n)?K(m(D.call(n))):"[object Boolean]"!==V(t=n)||j&&"object"==typeof t&&j in t?"[object String]"!==V(e=n)||j&&"object"==typeof e&&j in e?("[object Date]"!==V(t=n)||j&&"object"==typeof t&&j in t)&&!W(n)?(e=$(n,m),t=I?I(n)===Object.prototype:n instanceof Object||n.constructor===Object,f=n instanceof Object?"":"null prototype",p=!t&&j&&Object(n)===n&&j in n?x.call(V(n),8,-1):f?"Object":"",t=(!t&&"function"==typeof n.constructor&&n.constructor.name?n.constructor.name+" ":"")+(p||f?"["+O.call(L.call([],p||[],f||[]),": ")+"] ":""),0===e.length?t+"{}":h?t+"{"+G(e,h)+"}":t+"{ "+O.call(e,", ")+" }"):String(n):K(m(String(n))):K(J.call(n)):K(m(Number(n)))};var l=Object.prototype.hasOwnProperty||function(e){return e in this};function U(e,t){return l.call(e,t)}function V(e){return i.call(e)}function ee(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0,a=e.length;nu&&!d&&(o=o.slice(0,u),e=C.default.createElement(m.default,{key:"_count",type:"primary",size:p,animation:!1},c(a,t))),0, as child."),a.push(t),e.props.children)&&(t.children=n(e.props.children))}),a}(e.children):t},N.prototype.fetchInfoFromBinaryChildren=function(e){function r(e,t){return t=t||0,e.forEach(function(e){e.children?t=r(e.children,t):t+=1}),t}var a=!1,o=[],i=[],e=(function t(){var e=0r.tRight&&(e=r.tRight,r.changedPageX=r.tRight-r.startLeft),e-r.cellLefto.clientHeight,o.scrollWidth,o.clientWidth,o={},e||(o[r]=0,o[a]=0),+i&&(o.marginBottom=-i,o.paddingBottom=i,e)&&(o[a]=i),h.dom.setStyle(this.headerNode,o)),n&&!this.props.lockType&&this.headerNode&&(r=this.headerNode.querySelector("."+t+"table-header-fixer"),e=h.dom.getStyle(this.headerNode,"height"),a=h.dom.getStyle(this.headerNode,"paddingBottom"),h.dom.setStyle(r,{width:i,height:e-a}))},o.prototype.render=function(){var e=this.props,t=e.components,n=e.className,a=e.prefix,r=e.fixedHeader,o=e.lockType,i=e.dataSource,e=(e.maxBodyHeight,(0,u.default)(e,["components","className","prefix","fixedHeader","lockType","dataSource","maxBodyHeight"]));return r&&((t=(0,l.default)({},t)).Header||(t.Header=m.default),t.Body||(t.Body=g.default),t.Wrapper||(t.Wrapper=y.default),n=(0,p.default)(((r={})[a+"table-fixed"]=!0,r[a+"table-wrap-empty"]=!i.length,r[n]=n,r))),d.default.createElement(s,(0,l.default)({},e,{dataSource:i,lockType:o,components:t,className:n,prefix:a}))},o}(d.default.Component),n.FixedHeader=m.default,n.FixedBody=g.default,n.FixedWrapper=y.default,n.propTypes=(0,l.default)({hasHeader:r.default.bool,fixedHeader:r.default.bool,maxBodyHeight:r.default.oneOfType([r.default.number,r.default.string])},s.propTypes),n.defaultProps=(0,l.default)({},s.defaultProps,{hasHeader:!0,fixedHeader:!1,maxBodyHeight:200,components:{},refs:{},prefix:"next-"}),n.childContextTypes={fixedHeader:r.default.bool,getNode:r.default.func,onFixedScrollSync:r.default.func,getTableInstanceForFixed:r.default.func,maxBodyHeight:r.default.oneOfType([r.default.number,r.default.string])};var t,n=t;return n.displayName="FixedTable",(0,o.statics)(n,s),n};var d=s(n(0)),r=s(n(5)),f=n(24),p=s(n(18)),h=n(11),m=s(n(136)),g=s(n(406)),y=s(n(137)),o=n(70);function s(e){return e&&e.__esModule?e:{default:e}}e.exports=t.default},function(e,t,n){"use strict";t.__esModule=!0;var i=o(n(16)),f=o(n(3)),r=o(n(4)),s=o(n(7)),l=o(n(8)),u=(t.default=function(o){e=t=function(n){function a(e,t){(0,r.default)(this,a);var d=(0,s.default)(this,n.call(this,e,t));return d.addSelection=function(e){var t=d.props,n=t.prefix,a=t.rowSelection,t=t.size,a=a.columnProps&&a.columnProps()||{};e.find(function(e){return"selection"===e.key})||e.unshift((0,f.default)({key:"selection",title:d.renderSelectionHeader.bind(d),cell:d.renderSelectionBody.bind(d),width:"small"===t?34:50,className:n+"table-selection "+n+"table-prerow",__normalized:!0},a))},d.renderSelectionHeader=function(){var e=d.selectAllRow,t={},n=d.props,a=n.rowSelection,r=n.primaryKey,o=n.dataSource,i=n.entireDataSource,n=n.locale,s=d.state.selectedRowKeys,l=a.mode||"multiple",u=!!s.length,c=!1,i=(d.flatDataSource(i||o).filter(function(e,t){return!a.getProps||!(a.getProps(e,t)||{}).disabled}).map(function(e){return e[r]}).forEach(function(e){-1===s.indexOf(e)?u=!1:c=!0}),t.onClick=b(function(e){e.stopPropagation()},t.onClick),a.titleProps&&a.titleProps()||{});return u&&(c=!1),["multiple"===l?p.default.createElement(h.default,(0,f.default)({key:"_total",indeterminate:c,"aria-label":n.selectAll,checked:u,onChange:e},t,i)):null,a.titleAddons&&a.titleAddons()]},d.renderSelectionBody=function(e,t,n){var a=d.props,r=a.rowSelection,a=a.primaryKey,o=d.state.selectedRowKeys,i=r.mode||"multiple",o=-1l.length&&(u=o),w(u.filter(function(e){return-1=Math.max(a-y,0)&&od.clientHeight;this.isLock()?(e=this.bodyLeftNode,t=this.bodyRightNode,n=this.getWrapperNode("right"),a=f?c:0,d=d.offsetHeight-c,f||(r[l]=0,r[u]=0),+c?(r.marginBottom=-c,r.paddingBottom=c):(r.marginBottom=-20,r.paddingBottom=20),d={"max-height":d},o||+c||(d[u]=0),+c&&(d[u]=-c),e&&g.dom.setStyle(e,d),t&&g.dom.setStyle(t,d),n&&+c&&g.dom.setStyle(n,i?"left":"right",a+"px")):(r.marginBottom=-c,r.paddingBottom=c,r[u]=0,f||(r[l]=0)),s&&g.dom.setStyle(s,r)},a.prototype.adjustHeaderSize=function(){var o=this;this.isLock()&&this.tableInc.groupChildren.forEach(function(e,t){var n=o.tableInc.groupChildren[t].length-1,n=o.getHeaderCellNode(t,n),a=o.getHeaderCellNode(t,0),r=o.getHeaderCellNode(t,0,"right"),t=o.getHeaderCellNode(t,0,"left");n&&r&&(n=n.offsetHeight,g.dom.setStyle(r,"height",n),setTimeout(function(){var e=o.tableRightInc.affixRef;return e&&e.getInstance()&&e.getInstance().updatePosition()})),a&&t&&(r=a.offsetHeight,g.dom.setStyle(t,"height",r),setTimeout(function(){var e=o.tableLeftInc.affixRef;return e&&e.getInstance()&&e.getInstance().updatePosition()}))})},a.prototype.adjustRowHeight=function(){var n=this;this.isLock()&&this.tableInc.props.dataSource.forEach(function(e,t){t=""+("object"===(void 0===e?"undefined":(0,r.default)(e))&&"__rowIndex"in e?e.__rowIndex:t)+(e.__expanded?"_expanded":"");n.setRowHeight(t,"left"),n.setRowHeight(t,"right")})},a.prototype.setRowHeight=function(e,t){var t=this.getRowNode(e,t),e=this.getRowNode(e),e=(M?e&&e.offsetHeight:e&&parseFloat(getComputedStyle(e).height))||"auto",n=(M?t&&t.offsetHeight:t&&parseFloat(getComputedStyle(t).height))||"auto";t&&e!==n&&g.dom.setStyle(t,"height",e)},a.prototype.getWrapperNode=function(e){e=e?e.charAt(0).toUpperCase()+e.substr(1):"";try{return(0,u.findDOMNode)(this["lock"+e+"El"])}catch(e){return null}},a.prototype.getRowNode=function(e,t){t=this["table"+(t=t?t.charAt(0).toUpperCase()+t.substr(1):"")+"Inc"];try{return(0,u.findDOMNode)(t.getRowRef(e))}catch(e){return null}},a.prototype.getHeaderCellNode=function(e,t,n){n=this["table"+(n=n?n.charAt(0).toUpperCase()+n.substr(1):"")+"Inc"];try{return(0,u.findDOMNode)(n.getHeaderCellRef(e,t))}catch(e){return null}},a.prototype.getCellNode=function(e,t,n){n=this["table"+(n=n?n.charAt(0).toUpperCase()+n.substr(1):"")+"Inc"];try{return(0,u.findDOMNode)(n.getCellRef(e,t))}catch(e){return null}},a.prototype.render=function(){var e,t=this.props,n=(t.children,t.columns,t.prefix),a=t.components,r=t.className,o=t.dataSource,i=t.tableWidth,t=(0,f.default)(t,["children","columns","prefix","components","className","dataSource","tableWidth"]),s=this.normalizeChildrenState(this.props),l=s.lockLeftChildren,u=s.lockRightChildren,s=s.children,c={left:this.getFlatenChildrenLength(l),right:this.getFlatenChildrenLength(u),origin:this.getFlatenChildrenLength(s)};return this._notNeedAdjustLockLeft&&(l=[]),this._notNeedAdjustLockRight&&(u=[]),this.lockLeftChildren=l,this.lockRightChildren=u,this.isOriginLock()?((a=(0,p.default)({},a)).Body=a.Body||v.default,a.Header=a.Header||_.default,a.Wrapper=a.Wrapper||b.default,a.Row=a.Row||y.default,r=(0,m.default)(((e={})[n+"table-lock"]=!0,e[n+"table-wrap-empty"]=!o.length,e[r]=r,e)),e=[h.default.createElement(d,(0,p.default)({},t,{dataSource:o,key:"lock-left",columns:l,className:n+"table-lock-left",lengths:c,prefix:n,lockType:"left",components:a,ref:this.saveLockLeftRef,loading:!1,"aria-hidden":!0})),h.default.createElement(d,(0,p.default)({},t,{dataSource:o,key:"lock-right",columns:u,className:n+"table-lock-right",lengths:c,prefix:n,lockType:"right",components:a,ref:this.saveLockRightRef,loading:!1,"aria-hidden":!0}))],h.default.createElement(d,(0,p.default)({},t,{tableWidth:i,dataSource:o,columns:s,prefix:n,lengths:c,wrapperContent:e,components:a,className:r}))):h.default.createElement(d,this.props)},a}(h.default.Component),t.LockRow=y.default,t.LockBody=v.default,t.LockHeader=_.default,t.propTypes=(0,p.default)({scrollToCol:a.default.number,scrollToRow:a.default.number},d.propTypes),t.defaultProps=(0,p.default)({},d.defaultProps),t.childContextTypes={getTableInstance:a.default.func,getLockNode:a.default.func,onLockBodyScroll:a.default.func,onRowMouseEnter:a.default.func,onRowMouseLeave:a.default.func};var e,t=e;return t.displayName="LockTable",(0,w.statics)(t,d),t},n(0)),h=d(l),u=n(24),a=d(n(5)),m=d(n(18)),c=d(n(182)),g=n(11),y=d(n(184)),v=d(n(407)),_=d(n(408)),b=d(n(137)),w=n(70);function d(e){return e&&e.__esModule?e:{default:e}}var M=g.env.ieVersion;function k(e){return function n(e){return e.map(function(e){var t=(0,p.default)({},e);return e.children&&(e.children=n(e.children)),t})}(e)}e.exports=t.default},function(e,t,n){"use strict";t.__esModule=!0;var l=s(n(16)),u=s(n(3)),r=s(n(4)),o=s(n(7)),i=s(n(8)),c=(t.default=function(s){e=t=function(n){function a(e,t){(0,r.default)(this,a);var c=(0,o.default)(this,n.call(this,e));return c.state={},c.updateOffsetArr=function(){var e=c.splitChildren||{},t=e.lockLeftChildren,n=e.lockRightChildren,e=e.originChildren,a=c.getFlatenChildren(t).length,r=c.getFlatenChildren(n).length,e=a+r+c.getFlatenChildren(e).length,a=0r.top-e.offset?(t?(l.position="absolute",l.top=a-(r.top-e.offset),u="relative"):(l.position="fixed",l.top=e.offset+n.top),c._setAffixStyle(l,!0),c._setContainerStyle(s)):e.bottom&&a{e=new Date(e);if(isNaN(e))throw new TypeError("Invalid Datetime");return e}},function(e,t,n){"use strict";const a=n(186);class r extends Date{constructor(e){super(e+"Z"),this.isFloating=!0}toISOString(){return`${this.getUTCFullYear()}-${a(2,this.getUTCMonth()+1)}-`+a(2,this.getUTCDate())+"T"+(`${a(2,this.getUTCHours())}:${a(2,this.getUTCMinutes())}:${a(2,this.getUTCSeconds())}.`+a(3,this.getUTCMilliseconds()))}}e.exports=e=>{e=new r(e);if(isNaN(e))throw new TypeError("Invalid Datetime");return e}},function(a,e,r){"use strict";!function(e){const t=r(186);class n extends e.Date{constructor(e){super(e),this.isDate=!0}toISOString(){return`${this.getUTCFullYear()}-${t(2,this.getUTCMonth()+1)}-`+t(2,this.getUTCDate())}}a.exports=e=>{e=new n(e);if(isNaN(e))throw new TypeError("Invalid Datetime");return e}}.call(this,r(65))},function(e,t,n){"use strict";const a=n(186);class r extends Date{constructor(e){super(`0000-01-01T${e}Z`),this.isTime=!0}toISOString(){return`${a(2,this.getUTCHours())}:${a(2,this.getUTCMinutes())}:${a(2,this.getUTCSeconds())}.`+a(3,this.getUTCMilliseconds())}}e.exports=e=>{e=new r(e);if(isNaN(e))throw new TypeError("Invalid Datetime");return e}},function(e,t,n){"use strict";!function(s){e.exports=function(r,e){e=e||{};const n=e.blocksize||40960,o=new t;return new Promise((e,t)=>{s(i,0,n,e,t)});function i(e,t,n,a){if(e>=r.length)try{return n(o.finish())}catch(e){return a(l(e,r))}try{o.parse(r.slice(e,e+t)),s(i,e+t,t,n,a)}catch(e){a(l(e,r))}}};const t=n(185),l=n(187)}.call(this,n(412).setImmediate)},function(e,t,n){!function(e,p){!function(n,o){"use strict";var a,i,s,r,l,u,t,e;function c(e){delete i[e]}function d(e){if(s)setTimeout(d,0,e);else{var t=i[e];if(t){s=!0;try{var n=t,a=n.callback,r=n.args;switch(r.length){case 0:a();break;case 1:a(r[0]);break;case 2:a(r[0],r[1]);break;case 3:a(r[0],r[1],r[2]);break;default:a.apply(o,r)}}finally{c(e),s=!1}}}}function f(){function e(e){e.source===n&&"string"==typeof e.data&&0===e.data.indexOf(t)&&d(+e.data.slice(t.length))}var t="setImmediate$"+Math.random()+"$";n.addEventListener?n.addEventListener("message",e,!1):n.attachEvent("onmessage",e),l=function(e){n.postMessage(t+e,"*")}}n.setImmediate||(a=1,s=!(i={}),r=n.document,e=(e=Object.getPrototypeOf&&Object.getPrototypeOf(n))&&e.setTimeout?e:n,"[object process]"==={}.toString.call(n.process)?l=function(e){p.nextTick(function(){d(e)})}:!function(){var e,t;if(n.postMessage&&!n.importScripts)return e=!0,t=n.onmessage,n.onmessage=function(){e=!1},n.postMessage("","*"),n.onmessage=t,e}()?l=n.MessageChannel?((t=new MessageChannel).port1.onmessage=function(e){d(e.data)},function(e){t.port2.postMessage(e)}):r&&"onreadystatechange"in r.createElement("script")?(u=r.documentElement,function(e){var t=r.createElement("script");t.onreadystatechange=function(){d(e),t.onreadystatechange=null,u.removeChild(t),t=null},u.appendChild(t)}):function(e){setTimeout(d,0,e)}:f(),e.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),n=0;n{let n,a=!1,r=!1;function o(){if(a=!0,!n)try{e(l.finish())}catch(e){t(e)}}function i(e){r=!0,t(e)}s.once("end",o),s.once("error",i),function e(){n=!0;let t;for(;null!==(t=s.read());)try{l.parse(t)}catch(e){return i(e)}n=!1;if(a)return o();if(r)return;s.once("readable",e)}()})}(e):function(){const a=new o;return new r.Transform({objectMode:!0,transform(e,t,n){try{a.parse(e.toString(t))}catch(e){this.emit("error",e)}n()},flush(e){try{this.push(a.finish())}catch(e){this.emit("error",e)}e()}})}()};const r=n(704),o=n(185)},function(e,t,n){e.exports=a;var c=n(188).EventEmitter;function a(){c.call(this)}n(105)(a,c),a.Readable=n(189),a.Writable=n(714),a.Duplex=n(715),a.Transform=n(716),a.PassThrough=n(717),(a.Stream=a).prototype.pipe=function(t,e){var n=this;function a(e){t.writable&&!1===t.write(e)&&n.pause&&n.pause()}function r(){n.readable&&n.resume&&n.resume()}n.on("data",a),t.on("drain",r),t._isStdio||e&&!1===e.end||(n.on("end",i),n.on("close",s));var o=!1;function i(){o||(o=!0,t.end())}function s(){o||(o=!0,"function"==typeof t.destroy&&t.destroy())}function l(e){if(u(),0===c.listenerCount(this,"error"))throw e}function u(){n.removeListener("data",a),t.removeListener("drain",r),n.removeListener("end",i),n.removeListener("close",s),n.removeListener("error",l),t.removeListener("error",l),n.removeListener("end",u),n.removeListener("close",u),t.removeListener("close",u)}return n.on("error",l),t.on("error",l),n.on("end",u),n.on("close",u),t.on("close",u),t.emit("pipe",n),t}},function(e,t){var n={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==n.call(e)}},function(e,t,n){"use strict";t.byteLength=function(e){var e=c(e),t=e[0],e=e[1];return 3*(t+e)/4-e},t.toByteArray=function(e){var t,n,a=c(e),r=a[0],a=a[1],o=new u(function(e,t){return 3*(e+t)/4-t}(r,a)),i=0,s=0>16&255,o[i++]=t>>8&255,o[i++]=255&t;2===a&&(t=l[e.charCodeAt(n)]<<2|l[e.charCodeAt(n+1)]>>4,o[i++]=255&t);1===a&&(t=l[e.charCodeAt(n)]<<10|l[e.charCodeAt(n+1)]<<4|l[e.charCodeAt(n+2)]>>2,o[i++]=t>>8&255,o[i++]=255&t);return o},t.fromByteArray=function(e){for(var t,n=e.length,a=n%3,r=[],o=0,i=n-a;o>18&63]+s[e>>12&63]+s[e>>6&63]+s[63&e]}(a));return r.join("")}(e,o,i>2]+s[t<<4&63]+"==")):2==a&&(t=(e[n-2]<<8)+e[n-1],r.push(s[t>>10]+s[t>>4&63]+s[t<<2&63]+"="));return r.join("")};for(var s=[],l=[],u="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r=0,o=a.length;r */ -t.read=function(e,t,n,a,r){var o,i,s=8*r-a-1,l=(1<>1,d=-7,c=n?r-1:0,f=n?-1:1,r=e[t+c];for(c+=f,o=r&(1<<-d)-1,r>>=-d,d+=s;0>=-d,d+=a;0>1,c=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,f=a?0:o-1,p=a?1:-1,o=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,i=u):(i=Math.floor(Math.log(t)/Math.LN2),t*(a=Math.pow(2,-i))<1&&(i--,a*=2),2<=(t+=1<=i+d?c/a:c*Math.pow(2,1-d))*a&&(i++,a/=2),u<=i+d?(s=0,i=u):1<=i+d?(s=(t*a-1)*Math.pow(2,r),i+=d):(s=t*Math.pow(2,d-1)*Math.pow(2,r),i=0));8<=r;e[n+f]=255&s,f+=p,s/=256,r-=8);for(i=i<>>0),r=this.head,o=0;r;)t=r.data,n=o,t.copy(a,n),o+=r.data.length,r=r.next;return a},r),a&&a.inspect&&a.inspect.custom&&(e.exports.prototype[a.inspect.custom]=function(){var e=a.inspect({length:this.length});return this.constructor.name+" "+e})},function(e,t){},function(e,t,n){!function(t){function a(e){try{if(!t.localStorage)return}catch(e){return}e=t.localStorage[e];return null!=e&&"true"===String(e).toLowerCase()}e.exports=function(e,t){if(a("noDeprecation"))return e;var n=!1;return function(){if(!n){if(a("throwDeprecation"))throw new Error(t);a("traceDeprecation")?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}}}.call(this,n(65))},function(e,t,n){"use strict";e.exports=r;var a=n(414),e=Object.create(n(117));function r(e){if(!(this instanceof r))return new r(e);a.call(this,e)}e.inherits=n(104),e.inherits(r,a),r.prototype._transform=function(e,t,n){n(null,e)}},function(e,t,n){e.exports=n(186)},function(e,t,n){e.exports=n(91)},function(e,t,n){e.exports=n(185).Transform},function(e,t,n){e.exports=n(185).PassThrough},function(e,t,n){"use strict";function u(e){return new Error("Can only stringify objects, not "+e)}function d(t){return Object.keys(t).filter(e=>p(t[e]))}function c(e){var t,n=Array.isArray(e)?[]:Object.prototype.hasOwnProperty.call(e,"__proto__")?{["__proto__"]:void 0}:{};for(t of Object.keys(e))!e[t]||"function"!=typeof e[t].toJSON||"toISOString"in e[t]?n[t]=e[t]:n[t]=e[t].toJSON();return n}function f(t,e,n){var a,r,o=d(n=c(n));r=n,a=Object.keys(r).filter(e=>!p(r[e]));const i=[],s=e||"",l=(o.forEach(e=>{var t=h(n[e]);"undefined"!==t&&"null"!==t&&i.push(s+m(e)+" = "+g(n[e],!0))}),0{i.push(function(e,t,n,a){var r=h(a);{if("array"===r)return function(e,t,n,a){var r=h((a=c(a))[0]);if("table"!==r)throw u(r);const o=e+m(n);let i="";return a.forEach(e=>{0"\\u"+function(e,t){for(;t.lengths(e).replace(/"(?="")/g,'\\"')).join("\n");return'"'===e.slice(-1)&&(e+="\\\n"),'"""\n'+e+'"""';return}case"string":return i(t);case"string-literal":return"'"+t+"'";case"integer":return y(t);case"float":n=t;return n===1/0?"inf":n===-1/0?"-inf":Object.is(n,NaN)?"nan":Object.is(n,-0)?"-0.0":([n,a]=String(n).split("."),y(n)+"."+a);case"boolean":return String(t);case"datetime":return t.toISOString();case"array":{var a=t.filter(e=>"null"!==h(e)&&"undefined"!==h(e)&&"nan"!==h(e));a=c(a);let e="[";a=a.map(e=>l(e));60{o.push(m(e)+" = "+g(r[e],!1))}),"{ "+o.join(", ")+(0u&&!c&&(o=o.slice(0,u),e=C.default.createElement(m.default,{key:"_count",type:"primary",size:p,animation:!1},d(a,t))),0=P.KEYCODE.LEFT&&t<=P.KEYCODE.DOWN&&e.preventDefault(),e=void 0,t===P.KEYCODE.RIGHT||t===P.KEYCODE.DOWN?(e=o.getNextActiveKey(!0),o.handleTriggerEvent(o.props.triggerType,e)):t!==P.KEYCODE.LEFT&&t!==P.KEYCODE.UP||(e=o.getNextActiveKey(!1),o.handleTriggerEvent(o.props.triggerType,e)))},o.state={activeKey:o.getDefaultActiveKey(e)},o}s.displayName="Tab",t.default=(0,l.polyfill)(s),e.exports=t.default},function(e,t,n){"use strict";t.__esModule=!0;var _=c(n(2)),a=c(n(4)),r=c(n(6)),o=c(n(7)),b=c(n(0)),i=n(24),s=c(n(5)),w=c(n(17)),M=c(n(26)),l=c(n(64)),u=c(n(50)),k=(c(n(19)),c(n(82))),h=n(11),d=n(418);function c(e){return e&&e.__esModule?e:{default:e}}var f,S={float:"right",zIndex:1},E={float:"left",zIndex:1},p={dropdown:"arrow-down",prev:"arrow-left",next:"arrow-right"},m=l.default.Popup,l=(f=b.default.Component,(0,o.default)(g,f),g.prototype.componentDidMount=function(){this.props.animation||this.initialSettings(),h.events.on(window,"resize",this.onWindowResized)},g.prototype.componentDidUpdate=function(e){var t=this;clearTimeout(this.scrollTimer),this.scrollTimer=setTimeout(function(){t.scrollToActiveTab()},410),clearTimeout(this.slideTimer),this.slideTimer=setTimeout(function(){t.setSlideBtn()},410),"dropdown"!==this.props.excessMode||(0,d.tabsArrayShallowEqual)(this.props.tabs,e.tabs)||this.getDropdownItems(this.props)},g.prototype.componentWillUnmount=function(){h.events.off(window,"resize",this.onWindowResized)},g.prototype.initialSettings=function(){this.setSlideBtn(),this.getDropdownItems(this.props)},g.prototype.setOffset=function(e){var t=!(1n&&(t.current=n),this.setState(t),this.props.onPageSizeChange(e)},I.prototype.renderPageTotal=function(){var e=this.props,t=e.prefix,n=e.total,e=e.totalRender,a=this.state,r=a.currentPageSize,a=a.current;return N.default.createElement("div",{className:t+"pagination-total"},e(n,[(a-1)*r+1,a*r]))},I.prototype.renderPageItem=function(e){var t=this.props,n=t.prefix,a=t.size,r=t.link,o=t.pageNumberRender,i=t.total,s=t.pageSize,t=t.locale,l=this.state.current,i=Y(i,s),s=parseInt(e,10)===l,a={size:a,className:(0,P.default)(((l={})[n+"pagination-item"]=!0,l[n+"current"]=s,l)),onClick:s?m:this.onPageItemClick.bind(this,e)};return r&&(a.component="a",a.href=r.replace("{page}",e)),N.default.createElement(c.default,(0,D.default)({"aria-label":j.str.template(t.total,{current:e,total:i})},a,{key:e}),o(e))},I.prototype.renderPageFirst=function(e){var t=this.props,n=t.prefix,a=t.size,r=t.shape,t=t.locale,a={disabled:e<=1,size:a,className:(0,P.default)(((a={})[n+"pagination-item"]=!0,a[n+"prev"]=!0,a)),onClick:this.onPageItemClick.bind(this,e-1)},n=N.default.createElement(d.default,{type:"arrow-left",className:n+"pagination-icon-prev"});return N.default.createElement(c.default,(0,D.default)({},a,{"aria-label":j.str.template(t.labelPrev,{current:e})}),n,"arrow-only"===r||"arrow-prev-only"===r||"no-border"===r?"":t.prev)},I.prototype.renderPageLast=function(e,t){var n=this.props,a=n.prefix,r=n.size,o=n.shape,n=n.locale,r={disabled:t<=e,size:r,className:(0,P.default)(((t={})[a+"pagination-item"]=!0,t[a+"next"]=!0,t)),onClick:this.onPageItemClick.bind(this,e+1)},t=N.default.createElement(d.default,{type:"arrow-right",className:a+"pagination-icon-next"});return N.default.createElement(c.default,(0,D.default)({},r,{"aria-label":j.str.template(n.labelNext,{current:e})}),"arrow-only"===o||"no-border"===o?"":n.next,t)},I.prototype.renderPageEllipsis=function(e){var t=this.props.prefix;return N.default.createElement(d.default,{className:t+"pagination-ellipsis "+t+"pagination-icon-ellipsis",type:"ellipsis",key:"ellipsis-"+e})},I.prototype.renderPageJump=function(){var t=this,e=this.props,n=e.prefix,a=e.size,e=e.locale,r=this.state.inputValue;return[N.default.createElement("span",{className:n+"pagination-jump-text"},e.goTo),N.default.createElement(f.default,{className:n+"pagination-jump-input",type:"text","aria-label":e.inputAriaLabel,size:a,value:r,onChange:this.onInputChange.bind(this),onKeyDown:function(e){e.keyCode===j.KEYCODE.ENTER&&t.handleJump(e)}}),N.default.createElement("span",{className:n+"pagination-jump-text"},e.page),N.default.createElement(c.default,{className:n+"pagination-jump-go",size:a,onClick:this.handleJump},e.go)]},I.prototype.renderPageDisplay=function(e,t){var n=this.props,a=n.prefix,n=n.pageNumberRender;return N.default.createElement("span",{className:a+"pagination-display"},N.default.createElement("em",null,n(e)),"/",n(t))},I.prototype.renderPageList=function(e,t){var n=this.props,a=n.prefix,n=n.pageShowCount,r=[];if(t<=n)for(var o=1;o<=t;o++)r.push(this.renderPageItem(o));else{var n=n-3,i=parseInt(n/2,10),s=void 0,l=void 0;r.push(this.renderPageItem(1)),l=e+i,(s=e-i)<=1&&(l=(s=2)+n),2=e.length&&-1=this.props.children.length?(this.update(this.props),this.changeSlide({message:"index",index:this.props.children.length-this.props.slidesToShow,currentSlide:this.state.currentSlide})):(n=[],Object.keys(t).forEach(function(e){e in a.props&&t[e]!==a.props[e]&&n.push(e)}),1===n.length&&"children"===n[0]||l.obj.shallowEqual(t,this.props)||this.update(this.props)),this.adaptHeight()},p.prototype.componentWillUnmount=function(){this.animationEndCallback&&clearTimeout(this.animationEndCallback),l.events.off(window,"resize",this.onWindowResized),this.state.autoPlayTimer&&clearInterval(this.state.autoPlayTimer)},p.prototype.onWindowResized=function(){this.update(this.props),this.setState({animating:!1}),clearTimeout(this.animationEndCallback),delete this.animationEndCallback},p.prototype.slickGoTo=function(e){"number"==typeof e&&this.changeSlide({message:"index",index:e,currentSlide:this.state.currentSlide})},p.prototype.onEnterArrow=function(e){this.arrowHoverHandler(e)},p.prototype.onLeaveArrow=function(){this.arrowHoverHandler()},p.prototype._instanceRefHandler=function(e,t){this[e]=t},p.prototype.render=function(){var e=this.props,t=e.prefix,n=e.animation,a=e.arrows,r=e.arrowSize,o=e.arrowPosition,i=e.arrowDirection,s=e.dots,l=e.dotsClass,u=e.cssEase,d=e.speed,c=e.infinite,f=e.centerMode,p=e.centerPadding,h=e.lazyLoad,m=e.dotsDirection,g=e.rtl,y=e.slidesToShow,v=e.slidesToScroll,_=e.variableWidth,b=e.vertical,w=e.verticalSwiping,M=e.focusOnSelect,k=e.children,S=e.dotsRender,e=e.triggerType,E=this.state,x=E.currentSlide,C=E.lazyLoadedList,T=E.slideCount,L=E.slideWidth,O=E.slideHeight,D=E.trackStyle,N=E.listHeight,E=E.dragging,u={prefix:t,animation:n,cssEase:u,speed:d,infinite:c,centerMode:f,focusOnSelect:M?this.selectHandler:null,currentSlide:x,lazyLoad:h,lazyLoadedList:C,rtl:g,slideWidth:L,slideHeight:O,slidesToShow:y,slidesToScroll:v,slideCount:T,trackStyle:D,variableWidth:_,vertical:b,verticalSwiping:w,triggerType:e},d=void 0,h=(!0===s&&yt.startX?1:-1),!0===this.props.verticalSwiping&&(t.swipeLength=Math.round(Math.sqrt(Math.pow(t.curY-t.startY,2))),a=t.curY>t.startY?1:-1),r=this.state.currentSlide,s=Math.ceil(this.state.slideCount/this.props.slidesToScroll),o=this.swipeDirection(this.state.touchObject),i=t.swipeLength,!1===this.props.infinite&&(0===r&&"right"===o||s<=r+1&&"left"===o)&&(i=t.swipeLength*this.props.edgeFriction,!1===this.state.edgeDragged)&&this.props.edgeEvent&&(this.props.edgeEvent(o),this.setState({edgeDragged:!0})),!1===this.state.swiped&&this.props.swipeEvent&&(this.props.swipeEvent(o),this.setState({swiped:!0})),this.setState({touchObject:t,swipeLeft:s=n+i*a,trackStyle:(0,u.getTrackCSS)((0,l.default)({left:s},this.props,this.state))}),Math.abs(t.curX-t.startX)<.8*Math.abs(t.curY-t.startY))||4t[t.length-1])e=t[t.length-1];else for(var a in t){if(e-1*n.state.swipeLeft)return t=e,!1}else if(e.offsetLeft-a+(n.getWidth(e)||0)/2>-1*n.state.swipeLeft)return t=e,!1;return!0}),Math.abs(t.dataset.index-this.state.currentSlide)||1):this.props.slidesToScroll},swipeEnd:function(e){if(this.state.dragging){var t=this.state.touchObject,n=this.state.listWidth/this.props.touchThreshold,a=this.swipeDirection(t);if(this.props.verticalSwiping&&(n=this.state.listHeight/this.props.touchThreshold),this.setState({dragging:!1,edgeDragged:!1,swiped:!1,swipeLeft:null,touchObject:{}}),t.swipeLength)if(t.swipeLength>n){e.preventDefault();var r=void 0,o=void 0;switch(a){case"left":case"down":o=this.state.currentSlide+this.getSlideCount(),r=this.props.swipeToSlide?this.checkNavigable(o):o,this.setState({currentDirection:0});break;case"right":case"up":o=this.state.currentSlide-this.getSlideCount(),r=this.props.swipeToSlide?this.checkNavigable(o):o,this.setState({currentDirection:1});break;default:r=this.state.currentSlide}this.slideHandler(r)}else{t=(0,u.getTrackLeft)((0,l.default)({slideIndex:this.state.currentSlide,trackRef:this.track},this.props,this.state));this.setState({trackStyle:(0,u.getTrackAnimateCSS)((0,l.default)({left:t},this.props,this.state))})}}else this.props.swipe&&e.preventDefault()},onInnerSliderEnter:function(){this.props.autoplay&&this.props.pauseOnHover&&this.pause()},onInnerSliderLeave:function(){this.props.autoplay&&this.props.pauseOnHover&&this.autoPlay()}},e.exports=t.default},function(e,t,n){"use strict";t.__esModule=!0;var g=a(n(2)),d=a(n(0)),c=a(n(24)),y=n(421);function a(e){return e&&e.__esModule?e:{default:e}}t.default={initialize:function(t){var n=this,e=c.default.findDOMNode(this.list),a=d.default.Children.count(t.children),r=this.getWidth(e)||0,o=this.getWidth(c.default.findDOMNode(this.track))||0,i=void 0,e=(i=t.vertical?r:(r-(t.centerMode&&2*parseInt(t.centerPadding)))/t.slidesToShow,this.getHeight(e.querySelector('[data-index="0"]'))||0),s=e*t.slidesToShow,l=t.slidesToShow||1,u="activeIndex"in t?t.activeIndex:t.defaultActiveIndex,l=t.rtl?a-1-(l-1)-u:u;this.setState({slideCount:a,slideWidth:i,listWidth:r,trackWidth:o,currentSlide:l,slideHeight:e,listHeight:s},function(){var e=(0,y.getTrackLeft)((0,g.default)({slideIndex:n.state.currentSlide,trackRef:n.track},t,n.state)),e=(0,y.getTrackCSS)((0,g.default)({left:e},t,n.state));n.setState({trackStyle:e}),n.autoPlay()})},update:function(e){this.initialize(e)},getWidth:function(e){return"clientWidth"in e?e.clientWidth:e&&e.getBoundingClientRect().width},getHeight:function(e){return"clientHeight"in e?e.clientHeight:e&&e.getBoundingClientRect().height},adaptHeight:function(){var e,t;this.props.adaptiveHeight&&(t='[data-index="'+this.state.currentSlide+'"]',this.list)&&(t=(e=c.default.findDOMNode(this.list)).querySelector(t).offsetHeight,e.style.height=t+"px")},canGoNext:function(e){var t=!0;return e.infinite||(e.centerMode?e.currentSlide>=e.slideCount-1&&(t=!1):(e.slideCount<=e.slidesToShow||e.currentSlide>=e.slideCount-e.slidesToShow)&&(t=!1)),t},slideHandler:function(e){var t=this,n=this.props.rtl,a=void 0,r=void 0,o=void 0;if(!this.props.waitForAnimate||!this.state.animating){if("fade"===this.props.animation)return r=this.state.currentSlide,!1===this.props.infinite&&(e<0||e>=this.state.slideCount)?void 0:(a=e<0?e+this.state.slideCount:e>=this.state.slideCount?e-this.state.slideCount:e,this.props.lazyLoad&&this.state.lazyLoadedList.indexOf(a)<0&&this.setState({lazyLoadedList:this.state.lazyLoadedList.concat(a)}),o=function(){t.setState({animating:!1}),t.props.onChange(a),delete t.animationEndCallback},this.props.onBeforeChange(this.state.currentSlide,a),this.setState({animating:!0,currentSlide:a},function(){this.animationEndCallback=setTimeout(o,this.props.speed+20)}),void this.autoPlay());a=e,n?a<0?!1===this.props.infinite?r=0:this.state.slideCount%this.props.slidesToScroll!=0?a+this.props.slidesToScroll<=0?(r=this.state.slideCount+a,a=this.state.slideCount-this.props.slidesToScroll):r=a=0:r=this.state.slideCount+a:r=a>=this.state.slideCount?!1===this.props.infinite?this.state.slideCount-this.props.slidesToShow:this.state.slideCount%this.props.slidesToScroll!=0?0:a-this.state.slideCount:a:r=a<0?!1===this.props.infinite?0:this.state.slideCount%this.props.slidesToScroll!=0?this.state.slideCount-this.state.slideCount%this.props.slidesToScroll:this.state.slideCount+a:a>=this.state.slideCount?!1===this.props.infinite?this.state.slideCount-this.props.slidesToShow:this.state.slideCount%this.props.slidesToScroll!=0?0:a-this.state.slideCount:a;var i,e=(0,y.getTrackLeft)((0,g.default)({slideIndex:a,trackRef:this.track},this.props,this.state)),s=(0,y.getTrackLeft)((0,g.default)({slideIndex:r,trackRef:this.track},this.props,this.state));if(!1===this.props.infinite&&(e=s),this.props.lazyLoad){for(var l=!0,u=[],d=this.state.slideCount,c=a<0?d+a:r,f=c;f=l.activeIndex?"visible":"hidden",d.transition="opacity "+l.speed+"ms "+l.cssEase,d.WebkitTransition="opacity "+l.speed+"ms "+l.cssEase,l.vertical?d.top=-l.activeIndex*l.slideHeight:d.left=-l.activeIndex*l.slideWidth),l.vertical&&(d.width="100%"),d),u=(d=(0,v.default)({activeIndex:e},c),a=d.prefix,u=r=i=void 0,o=(u=d.rtl?d.slideCount-1-d.activeIndex:d.activeIndex)<0||u>=d.slideCount,d.centerMode?(n=Math.floor(d.slidesToShow/2),r=(u-d.currentSlide)%d.slideCount==0,u>d.currentSlide-n-1&&u<=d.currentSlide+n&&(i=!0)):i=d.currentSlide<=u&&u=u,u=(0,k.default)(((v={})[o+"upload-list-item"]=!0,v[o+"hidden"]=u,v)),v=this.props.children||i.card.addPhoto,c=r?S.func.prevent:c,_=S.obj.pickOthers(C.propTypes,this.props),b=S.obj.pickOthers(E.default.propTypes,_);if(h&&"function"==typeof m)return e=(0,k.default)(((e={})[o+"form-preview"]=!0,e[s]=!!s,e)),M.default.createElement("div",{style:l,className:e},m(this.state.value,this.props));return M.default.createElement(E.default,(0,w.default)({className:s,style:l,listType:"card",closable:!0,locale:i,value:this.state.value,onRemove:c,onCancel:f,onPreview:d,itemRender:g,isPreview:h,uploader:this.uploaderRef,reUpload:y,showDownload:n},_),M.default.createElement(x.default,(0,w.default)({},b,{shape:"card",prefix:o,disabled:r,action:a,timeout:p,isPreview:h,value:this.state.value,onProgress:this.onProgress,onChange:this.onChange,ref:function(e){return t.saveRef(e)},className:u}),v))},d=n=C,n.displayName="Card",n.propTypes={prefix:s.default.string,locale:s.default.object,children:s.default.object,value:s.default.oneOfType([s.default.array,s.default.object]),defaultValue:s.default.oneOfType([s.default.array,s.default.object]),onPreview:s.default.func,onChange:s.default.func,onRemove:s.default.func,onCancel:s.default.func,itemRender:s.default.func,reUpload:s.default.bool,showDownload:s.default.bool,onProgress:s.default.func,isPreview:s.default.bool,renderPreview:s.default.func},n.defaultProps={prefix:"next-",locale:u.default.Upload,showDownload:!0,onChange:S.func.noop,onPreview:S.func.noop,onProgress:S.func.noop},a=function(){var n=this;this.onProgress=function(e,t){n.setState({value:e}),n.props.onProgress(e,t)},this.onChange=function(e,t){"value"in n.props||n.setState({value:e}),n.props.onChange(e,t)}};var f,i=d;function C(e){(0,r.default)(this,C);var t=(0,o.default)(this,f.call(this,e)),n=(a.call(t),void 0),n="value"in e?e.value:e.defaultValue;return t.state={value:Array.isArray(n)?n:[],uploaderRef:t.uploaderRef},t}t.default=(0,l.polyfill)(i),e.exports=t.default},function(e,t,n){"use strict";t.__esModule=!0;var u=m(n(2)),d=m(n(12)),o=m(n(4)),i=m(n(6)),a=m(n(7)),c=m(n(0)),r=m(n(5)),f=m(n(17)),p=m(n(26)),s=n(11),l=m(n(44)),h=m(n(191));function m(e){return e&&e.__esModule?e:{default:e}}g=c.default.Component,(0,a.default)(y,g),y.prototype.abort=function(e){this.uploaderRef.abort(e)},y.prototype.startUpload=function(){this.uploaderRef.startUpload()},y.prototype.render=function(){var e=this.props,t=e.className,n=e.style,a=e.shape,r=e.locale,o=e.prefix,i=e.listType,e=(0,d.default)(e,["className","style","shape","locale","prefix","listType"]),s=o+"upload-drag",t=(0,f.default)(((l={})[s]=!0,l[s+"-over"]=this.state.dragOver,l[t]=!!t,l)),l=this.props.children||c.default.createElement("div",{className:t},c.default.createElement("p",{className:s+"-icon"},c.default.createElement(p.default,{size:"large",className:s+"-upload-icon"})),c.default.createElement("p",{className:s+"-text"},r.drag.text),c.default.createElement("p",{className:s+"-hint"},r.drag.hint));return c.default.createElement(h.default,(0,u.default)({},e,{prefix:o,shape:a,listType:i,dragable:!0,style:n,onDragOver:this.onDragOver,onDragLeave:this.onDragLeave,onDrop:this.onDrop,ref:this.saveUploaderRef}),l)},a=n=y,n.propTypes={prefix:r.default.string,locale:r.default.object,shape:r.default.string,onDragOver:r.default.func,onDragLeave:r.default.func,onDrop:r.default.func,limit:r.default.number,className:r.default.string,style:r.default.object,defaultValue:r.default.array,children:r.default.node,listType:r.default.string,timeout:r.default.number},n.defaultProps={prefix:"next-",onDragOver:s.func.noop,onDragLeave:s.func.noop,onDrop:s.func.noop,locale:l.default.Upload};var g,r=a;function y(){var e,t;(0,o.default)(this,y);for(var n=arguments.length,a=Array(n),r=0;r>1,c=-7,d=n?r-1:0,f=n?-1:1,r=e[t+d];for(d+=f,o=r&(1<<-c)-1,r>>=-c,c+=s;0>=-c,c+=a;0>1,d=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,f=a?0:o-1,p=a?1:-1,o=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,i=u):(i=Math.floor(Math.log(t)/Math.LN2),t*(a=Math.pow(2,-i))<1&&(i--,a*=2),2<=(t+=1<=i+c?d/a:d*Math.pow(2,1-c))*a&&(i++,a/=2),u<=i+c?(s=0,i=u):1<=i+c?(s=(t*a-1)*Math.pow(2,r),i+=c):(s=t*Math.pow(2,c-1)*Math.pow(2,r),i=0));8<=r;e[n+f]=255&s,f+=p,s/=256,r-=8);for(i=i<>>0),r=this.head,o=0;r;)t=r.data,n=o,t.copy(a,n),o+=r.data.length,r=r.next;return a},r),a&&a.inspect&&a.inspect.custom&&(e.exports.prototype[a.inspect.custom]=function(){var e=a.inspect({length:this.length});return this.constructor.name+" "+e})},function(e,t){},function(e,t,n){!function(t){function a(e){try{if(!t.localStorage)return}catch(e){return}e=t.localStorage[e];return null!=e&&"true"===String(e).toLowerCase()}e.exports=function(e,t){if(a("noDeprecation"))return e;var n=!1;return function(){if(!n){if(a("throwDeprecation"))throw new Error(t);a("traceDeprecation")?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}}}.call(this,n(65))},function(e,t,n){"use strict";e.exports=r;var a=n(418),e=Object.create(n(118));function r(e){if(!(this instanceof r))return new r(e);a.call(this,e)}e.inherits=n(105),e.inherits(r,a),r.prototype._transform=function(e,t,n){n(null,e)}},function(e,t,n){e.exports=n(190)},function(e,t,n){e.exports=n(92)},function(e,t,n){e.exports=n(189).Transform},function(e,t,n){e.exports=n(189).PassThrough},function(e,t,n){"use strict";function u(e){return new Error("Can only stringify objects, not "+e)}function c(t){return Object.keys(t).filter(e=>p(t[e]))}function d(e){var t,n=Array.isArray(e)?[]:Object.prototype.hasOwnProperty.call(e,"__proto__")?{["__proto__"]:void 0}:{};for(t of Object.keys(e))!e[t]||"function"!=typeof e[t].toJSON||"toISOString"in e[t]?n[t]=e[t]:n[t]=e[t].toJSON();return n}function f(t,e,n){var a,r,o=c(n=d(n));r=n,a=Object.keys(r).filter(e=>!p(r[e]));const i=[],s=e||"",l=(o.forEach(e=>{var t=h(n[e]);"undefined"!==t&&"null"!==t&&i.push(s+m(e)+" = "+g(n[e],!0))}),0{i.push(function(e,t,n,a){var r=h(a);{if("array"===r)return function(e,t,n,a){var r=h((a=d(a))[0]);if("table"!==r)throw u(r);const o=e+m(n);let i="";return a.forEach(e=>{0"\\u"+function(e,t){for(;t.lengths(e).replace(/"(?="")/g,'\\"')).join("\n");return'"'===e.slice(-1)&&(e+="\\\n"),'"""\n'+e+'"""';return}case"string":return i(t);case"string-literal":return"'"+t+"'";case"integer":return y(t);case"float":n=t;return n===1/0?"inf":n===-1/0?"-inf":Object.is(n,NaN)?"nan":Object.is(n,-0)?"-0.0":([n,a]=String(n).split("."),y(n)+"."+a);case"boolean":return String(t);case"datetime":return t.toISOString();case"array":{var a=t.filter(e=>"null"!==h(e)&&"undefined"!==h(e)&&"nan"!==h(e));a=d(a);let e="[";a=a.map(e=>l(e));60{o.push(m(e)+" = "+g(r[e],!1))}),"{ "+o.join(", ")+(0=P.KEYCODE.LEFT&&t<=P.KEYCODE.DOWN&&e.preventDefault(),e=void 0,t===P.KEYCODE.RIGHT||t===P.KEYCODE.DOWN?(e=o.getNextActiveKey(!0),o.handleTriggerEvent(o.props.triggerType,e)):t!==P.KEYCODE.LEFT&&t!==P.KEYCODE.UP||(e=o.getNextActiveKey(!1),o.handleTriggerEvent(o.props.triggerType,e)))},o.state={activeKey:o.getDefaultActiveKey(e)},o}s.displayName="Tab",t.default=(0,l.polyfill)(s),e.exports=t.default},function(e,t,n){"use strict";t.__esModule=!0;var _=d(n(3)),a=d(n(4)),r=d(n(7)),o=d(n(8)),b=d(n(0)),i=n(24),s=d(n(5)),w=d(n(18)),M=d(n(26)),l=d(n(64)),u=d(n(50)),k=(d(n(19)),d(n(83))),h=n(11),c=n(420);function d(e){return e&&e.__esModule?e:{default:e}}var f,S={float:"right",zIndex:1},E={float:"left",zIndex:1},p={dropdown:"arrow-down",prev:"arrow-left",next:"arrow-right"},m=l.default.Popup,l=(f=b.default.Component,(0,o.default)(g,f),g.prototype.componentDidMount=function(){this.props.animation||this.initialSettings(),h.events.on(window,"resize",this.onWindowResized)},g.prototype.componentDidUpdate=function(e){var t=this;clearTimeout(this.scrollTimer),this.scrollTimer=setTimeout(function(){t.scrollToActiveTab()},410),clearTimeout(this.slideTimer),this.slideTimer=setTimeout(function(){t.setSlideBtn()},410),"dropdown"!==this.props.excessMode||(0,c.tabsArrayShallowEqual)(this.props.tabs,e.tabs)||this.getDropdownItems(this.props)},g.prototype.componentWillUnmount=function(){h.events.off(window,"resize",this.onWindowResized)},g.prototype.initialSettings=function(){this.setSlideBtn(),this.getDropdownItems(this.props)},g.prototype.setOffset=function(e){var t=!(1n&&(t.current=n),this.setState(t),this.props.onPageSizeChange(e)},I.prototype.renderPageTotal=function(){var e=this.props,t=e.prefix,n=e.total,e=e.totalRender,a=this.state,r=a.currentPageSize,a=a.current;return N.default.createElement("div",{className:t+"pagination-total"},e(n,[(a-1)*r+1,a*r]))},I.prototype.renderPageItem=function(e){var t=this.props,n=t.prefix,a=t.size,r=t.link,o=t.pageNumberRender,i=t.total,s=t.pageSize,t=t.locale,l=this.state.current,i=Y(i,s),s=parseInt(e,10)===l,a={size:a,className:(0,P.default)(((l={})[n+"pagination-item"]=!0,l[n+"current"]=s,l)),onClick:s?m:this.onPageItemClick.bind(this,e)};return r&&(a.component="a",a.href=r.replace("{page}",e)),N.default.createElement(d.default,(0,D.default)({"aria-label":j.str.template(t.total,{current:e,total:i})},a,{key:e}),o(e))},I.prototype.renderPageFirst=function(e){var t=this.props,n=t.prefix,a=t.size,r=t.shape,t=t.locale,a={disabled:e<=1,size:a,className:(0,P.default)(((a={})[n+"pagination-item"]=!0,a[n+"prev"]=!0,a)),onClick:this.onPageItemClick.bind(this,e-1)},n=N.default.createElement(c.default,{type:"arrow-left",className:n+"pagination-icon-prev"});return N.default.createElement(d.default,(0,D.default)({},a,{"aria-label":j.str.template(t.labelPrev,{current:e})}),n,"arrow-only"===r||"arrow-prev-only"===r||"no-border"===r?"":t.prev)},I.prototype.renderPageLast=function(e,t){var n=this.props,a=n.prefix,r=n.size,o=n.shape,n=n.locale,r={disabled:t<=e,size:r,className:(0,P.default)(((t={})[a+"pagination-item"]=!0,t[a+"next"]=!0,t)),onClick:this.onPageItemClick.bind(this,e+1)},t=N.default.createElement(c.default,{type:"arrow-right",className:a+"pagination-icon-next"});return N.default.createElement(d.default,(0,D.default)({},r,{"aria-label":j.str.template(n.labelNext,{current:e})}),"arrow-only"===o||"no-border"===o?"":n.next,t)},I.prototype.renderPageEllipsis=function(e){var t=this.props.prefix;return N.default.createElement(c.default,{className:t+"pagination-ellipsis "+t+"pagination-icon-ellipsis",type:"ellipsis",key:"ellipsis-"+e})},I.prototype.renderPageJump=function(){var t=this,e=this.props,n=e.prefix,a=e.size,e=e.locale,r=this.state.inputValue;return[N.default.createElement("span",{className:n+"pagination-jump-text"},e.goTo),N.default.createElement(f.default,{className:n+"pagination-jump-input",type:"text","aria-label":e.inputAriaLabel,size:a,value:r,onChange:this.onInputChange.bind(this),onKeyDown:function(e){e.keyCode===j.KEYCODE.ENTER&&t.handleJump(e)}}),N.default.createElement("span",{className:n+"pagination-jump-text"},e.page),N.default.createElement(d.default,{className:n+"pagination-jump-go",size:a,onClick:this.handleJump},e.go)]},I.prototype.renderPageDisplay=function(e,t){var n=this.props,a=n.prefix,n=n.pageNumberRender;return N.default.createElement("span",{className:a+"pagination-display"},N.default.createElement("em",null,n(e)),"/",n(t))},I.prototype.renderPageList=function(e,t){var n=this.props,a=n.prefix,n=n.pageShowCount,r=[];if(t<=n)for(var o=1;o<=t;o++)r.push(this.renderPageItem(o));else{var n=n-3,i=parseInt(n/2,10),s=void 0,l=void 0;r.push(this.renderPageItem(1)),l=e+i,(s=e-i)<=1&&(l=(s=2)+n),2=e.length&&-1=this.props.children.length?(this.update(this.props),this.changeSlide({message:"index",index:this.props.children.length-this.props.slidesToShow,currentSlide:this.state.currentSlide})):(n=[],Object.keys(t).forEach(function(e){e in a.props&&t[e]!==a.props[e]&&n.push(e)}),1===n.length&&"children"===n[0]||l.obj.shallowEqual(t,this.props)||this.update(this.props)),this.adaptHeight()},p.prototype.componentWillUnmount=function(){this.animationEndCallback&&clearTimeout(this.animationEndCallback),l.events.off(window,"resize",this.onWindowResized),this.state.autoPlayTimer&&clearInterval(this.state.autoPlayTimer)},p.prototype.onWindowResized=function(){this.update(this.props),this.setState({animating:!1}),clearTimeout(this.animationEndCallback),delete this.animationEndCallback},p.prototype.slickGoTo=function(e){"number"==typeof e&&this.changeSlide({message:"index",index:e,currentSlide:this.state.currentSlide})},p.prototype.onEnterArrow=function(e){this.arrowHoverHandler(e)},p.prototype.onLeaveArrow=function(){this.arrowHoverHandler()},p.prototype._instanceRefHandler=function(e,t){this[e]=t},p.prototype.render=function(){var e=this.props,t=e.prefix,n=e.animation,a=e.arrows,r=e.arrowSize,o=e.arrowPosition,i=e.arrowDirection,s=e.dots,l=e.dotsClass,u=e.cssEase,c=e.speed,d=e.infinite,f=e.centerMode,p=e.centerPadding,h=e.lazyLoad,m=e.dotsDirection,g=e.rtl,y=e.slidesToShow,v=e.slidesToScroll,_=e.variableWidth,b=e.vertical,w=e.verticalSwiping,M=e.focusOnSelect,k=e.children,S=e.dotsRender,e=e.triggerType,E=this.state,x=E.currentSlide,C=E.lazyLoadedList,T=E.slideCount,L=E.slideWidth,O=E.slideHeight,D=E.trackStyle,N=E.listHeight,E=E.dragging,u={prefix:t,animation:n,cssEase:u,speed:c,infinite:d,centerMode:f,focusOnSelect:M?this.selectHandler:null,currentSlide:x,lazyLoad:h,lazyLoadedList:C,rtl:g,slideWidth:L,slideHeight:O,slidesToShow:y,slidesToScroll:v,slideCount:T,trackStyle:D,variableWidth:_,vertical:b,verticalSwiping:w,triggerType:e},c=void 0,h=(!0===s&&yt.startX?1:-1),!0===this.props.verticalSwiping&&(t.swipeLength=Math.round(Math.sqrt(Math.pow(t.curY-t.startY,2))),a=t.curY>t.startY?1:-1),r=this.state.currentSlide,s=Math.ceil(this.state.slideCount/this.props.slidesToScroll),o=this.swipeDirection(this.state.touchObject),i=t.swipeLength,!1===this.props.infinite&&(0===r&&"right"===o||s<=r+1&&"left"===o)&&(i=t.swipeLength*this.props.edgeFriction,!1===this.state.edgeDragged)&&this.props.edgeEvent&&(this.props.edgeEvent(o),this.setState({edgeDragged:!0})),!1===this.state.swiped&&this.props.swipeEvent&&(this.props.swipeEvent(o),this.setState({swiped:!0})),this.setState({touchObject:t,swipeLeft:s=n+i*a,trackStyle:(0,u.getTrackCSS)((0,l.default)({left:s},this.props,this.state))}),Math.abs(t.curX-t.startX)<.8*Math.abs(t.curY-t.startY))||4t[t.length-1])e=t[t.length-1];else for(var a in t){if(e-1*n.state.swipeLeft)return t=e,!1}else if(e.offsetLeft-a+(n.getWidth(e)||0)/2>-1*n.state.swipeLeft)return t=e,!1;return!0}),Math.abs(t.dataset.index-this.state.currentSlide)||1):this.props.slidesToScroll},swipeEnd:function(e){if(this.state.dragging){var t=this.state.touchObject,n=this.state.listWidth/this.props.touchThreshold,a=this.swipeDirection(t);if(this.props.verticalSwiping&&(n=this.state.listHeight/this.props.touchThreshold),this.setState({dragging:!1,edgeDragged:!1,swiped:!1,swipeLeft:null,touchObject:{}}),t.swipeLength)if(t.swipeLength>n){e.preventDefault();var r=void 0,o=void 0;switch(a){case"left":case"down":o=this.state.currentSlide+this.getSlideCount(),r=this.props.swipeToSlide?this.checkNavigable(o):o,this.setState({currentDirection:0});break;case"right":case"up":o=this.state.currentSlide-this.getSlideCount(),r=this.props.swipeToSlide?this.checkNavigable(o):o,this.setState({currentDirection:1});break;default:r=this.state.currentSlide}this.slideHandler(r)}else{t=(0,u.getTrackLeft)((0,l.default)({slideIndex:this.state.currentSlide,trackRef:this.track},this.props,this.state));this.setState({trackStyle:(0,u.getTrackAnimateCSS)((0,l.default)({left:t},this.props,this.state))})}}else this.props.swipe&&e.preventDefault()},onInnerSliderEnter:function(){this.props.autoplay&&this.props.pauseOnHover&&this.pause()},onInnerSliderLeave:function(){this.props.autoplay&&this.props.pauseOnHover&&this.autoPlay()}},e.exports=t.default},function(e,t,n){"use strict";t.__esModule=!0;var g=a(n(3)),c=a(n(0)),d=a(n(24)),y=n(423);function a(e){return e&&e.__esModule?e:{default:e}}t.default={initialize:function(t){var n=this,e=d.default.findDOMNode(this.list),a=c.default.Children.count(t.children),r=this.getWidth(e)||0,o=this.getWidth(d.default.findDOMNode(this.track))||0,i=void 0,e=(i=t.vertical?r:(r-(t.centerMode&&2*parseInt(t.centerPadding)))/t.slidesToShow,this.getHeight(e.querySelector('[data-index="0"]'))||0),s=e*t.slidesToShow,l=t.slidesToShow||1,u="activeIndex"in t?t.activeIndex:t.defaultActiveIndex,l=t.rtl?a-1-(l-1)-u:u;this.setState({slideCount:a,slideWidth:i,listWidth:r,trackWidth:o,currentSlide:l,slideHeight:e,listHeight:s},function(){var e=(0,y.getTrackLeft)((0,g.default)({slideIndex:n.state.currentSlide,trackRef:n.track},t,n.state)),e=(0,y.getTrackCSS)((0,g.default)({left:e},t,n.state));n.setState({trackStyle:e}),n.autoPlay()})},update:function(e){this.initialize(e)},getWidth:function(e){return"clientWidth"in e?e.clientWidth:e&&e.getBoundingClientRect().width},getHeight:function(e){return"clientHeight"in e?e.clientHeight:e&&e.getBoundingClientRect().height},adaptHeight:function(){var e,t;this.props.adaptiveHeight&&(t='[data-index="'+this.state.currentSlide+'"]',this.list)&&(t=(e=d.default.findDOMNode(this.list)).querySelector(t).offsetHeight,e.style.height=t+"px")},canGoNext:function(e){var t=!0;return e.infinite||(e.centerMode?e.currentSlide>=e.slideCount-1&&(t=!1):(e.slideCount<=e.slidesToShow||e.currentSlide>=e.slideCount-e.slidesToShow)&&(t=!1)),t},slideHandler:function(e){var t=this,n=this.props.rtl,a=void 0,r=void 0,o=void 0;if(!this.props.waitForAnimate||!this.state.animating){if("fade"===this.props.animation)return r=this.state.currentSlide,!1===this.props.infinite&&(e<0||e>=this.state.slideCount)?void 0:(a=e<0?e+this.state.slideCount:e>=this.state.slideCount?e-this.state.slideCount:e,this.props.lazyLoad&&this.state.lazyLoadedList.indexOf(a)<0&&this.setState({lazyLoadedList:this.state.lazyLoadedList.concat(a)}),o=function(){t.setState({animating:!1}),t.props.onChange(a),delete t.animationEndCallback},this.props.onBeforeChange(this.state.currentSlide,a),this.setState({animating:!0,currentSlide:a},function(){this.animationEndCallback=setTimeout(o,this.props.speed+20)}),void this.autoPlay());a=e,n?a<0?!1===this.props.infinite?r=0:this.state.slideCount%this.props.slidesToScroll!=0?a+this.props.slidesToScroll<=0?(r=this.state.slideCount+a,a=this.state.slideCount-this.props.slidesToScroll):r=a=0:r=this.state.slideCount+a:r=a>=this.state.slideCount?!1===this.props.infinite?this.state.slideCount-this.props.slidesToShow:this.state.slideCount%this.props.slidesToScroll!=0?0:a-this.state.slideCount:a:r=a<0?!1===this.props.infinite?0:this.state.slideCount%this.props.slidesToScroll!=0?this.state.slideCount-this.state.slideCount%this.props.slidesToScroll:this.state.slideCount+a:a>=this.state.slideCount?!1===this.props.infinite?this.state.slideCount-this.props.slidesToShow:this.state.slideCount%this.props.slidesToScroll!=0?0:a-this.state.slideCount:a;var i,e=(0,y.getTrackLeft)((0,g.default)({slideIndex:a,trackRef:this.track},this.props,this.state)),s=(0,y.getTrackLeft)((0,g.default)({slideIndex:r,trackRef:this.track},this.props,this.state));if(!1===this.props.infinite&&(e=s),this.props.lazyLoad){for(var l=!0,u=[],c=this.state.slideCount,d=a<0?c+a:r,f=d;f=l.activeIndex?"visible":"hidden",c.transition="opacity "+l.speed+"ms "+l.cssEase,c.WebkitTransition="opacity "+l.speed+"ms "+l.cssEase,l.vertical?c.top=-l.activeIndex*l.slideHeight:c.left=-l.activeIndex*l.slideWidth),l.vertical&&(c.width="100%"),c),u=(c=(0,v.default)({activeIndex:e},d),a=c.prefix,u=r=i=void 0,o=(u=c.rtl?c.slideCount-1-c.activeIndex:c.activeIndex)<0||u>=c.slideCount,c.centerMode?(n=Math.floor(c.slidesToShow/2),r=(u-c.currentSlide)%c.slideCount==0,u>c.currentSlide-n-1&&u<=c.currentSlide+n&&(i=!0)):i=c.currentSlide<=u&&u=u,u=(0,k.default)(((v={})[o+"upload-list-item"]=!0,v[o+"hidden"]=u,v)),v=this.props.children||i.card.addPhoto,d=r?S.func.prevent:d,_=S.obj.pickOthers(C.propTypes,this.props),b=S.obj.pickOthers(E.default.propTypes,_);if(h&&"function"==typeof m)return e=(0,k.default)(((e={})[o+"form-preview"]=!0,e[s]=!!s,e)),M.default.createElement("div",{style:l,className:e},m(this.state.value,this.props));return M.default.createElement(E.default,(0,w.default)({className:s,style:l,listType:"card",closable:!0,locale:i,value:this.state.value,onRemove:d,onCancel:f,onPreview:c,itemRender:g,isPreview:h,uploader:this.uploaderRef,reUpload:y,showDownload:n},_),M.default.createElement(x.default,(0,w.default)({},b,{shape:"card",prefix:o,disabled:r,action:a,timeout:p,isPreview:h,value:this.state.value,onProgress:this.onProgress,onChange:this.onChange,ref:function(e){return t.saveRef(e)},className:u}),v))},c=n=C,n.displayName="Card",n.propTypes={prefix:s.default.string,locale:s.default.object,children:s.default.object,value:s.default.oneOfType([s.default.array,s.default.object]),defaultValue:s.default.oneOfType([s.default.array,s.default.object]),onPreview:s.default.func,onChange:s.default.func,onRemove:s.default.func,onCancel:s.default.func,itemRender:s.default.func,reUpload:s.default.bool,showDownload:s.default.bool,onProgress:s.default.func,isPreview:s.default.bool,renderPreview:s.default.func},n.defaultProps={prefix:"next-",locale:u.default.Upload,showDownload:!0,onChange:S.func.noop,onPreview:S.func.noop,onProgress:S.func.noop},a=function(){var n=this;this.onProgress=function(e,t){n.setState({value:e}),n.props.onProgress(e,t)},this.onChange=function(e,t){"value"in n.props||n.setState({value:e}),n.props.onChange(e,t)}};var f,i=c;function C(e){(0,r.default)(this,C);var t=(0,o.default)(this,f.call(this,e)),n=(a.call(t),void 0),n="value"in e?e.value:e.defaultValue;return t.state={value:Array.isArray(n)?n:[],uploaderRef:t.uploaderRef},t}t.default=(0,l.polyfill)(i),e.exports=t.default},function(e,t,n){"use strict";t.__esModule=!0;var u=m(n(3)),c=m(n(16)),o=m(n(4)),i=m(n(7)),a=m(n(8)),d=m(n(0)),r=m(n(5)),f=m(n(18)),p=m(n(26)),s=n(11),l=m(n(44)),h=m(n(193));function m(e){return e&&e.__esModule?e:{default:e}}g=d.default.Component,(0,a.default)(y,g),y.prototype.abort=function(e){this.uploaderRef.abort(e)},y.prototype.startUpload=function(){this.uploaderRef.startUpload()},y.prototype.render=function(){var e=this.props,t=e.className,n=e.style,a=e.shape,r=e.locale,o=e.prefix,i=e.listType,e=(0,c.default)(e,["className","style","shape","locale","prefix","listType"]),s=o+"upload-drag",t=(0,f.default)(((l={})[s]=!0,l[s+"-over"]=this.state.dragOver,l[t]=!!t,l)),l=this.props.children||d.default.createElement("div",{className:t},d.default.createElement("p",{className:s+"-icon"},d.default.createElement(p.default,{size:"large",className:s+"-upload-icon"})),d.default.createElement("p",{className:s+"-text"},r.drag.text),d.default.createElement("p",{className:s+"-hint"},r.drag.hint));return d.default.createElement(h.default,(0,u.default)({},e,{prefix:o,shape:a,listType:i,dragable:!0,style:n,onDragOver:this.onDragOver,onDragLeave:this.onDragLeave,onDrop:this.onDrop,ref:this.saveUploaderRef}),l)},a=n=y,n.propTypes={prefix:r.default.string,locale:r.default.object,shape:r.default.string,onDragOver:r.default.func,onDragLeave:r.default.func,onDrop:r.default.func,limit:r.default.number,className:r.default.string,style:r.default.object,defaultValue:r.default.array,children:r.default.node,listType:r.default.string,timeout:r.default.number},n.defaultProps={prefix:"next-",onDragOver:s.func.noop,onDragLeave:s.func.noop,onDrop:s.func.noop,locale:l.default.Upload};var g,r=a;function y(){var e,t;(0,o.default)(this,y);for(var n=arguments.length,a=Array(n),r=0;r response = healthController.liveness(); - Assert.assertEquals(200, response.getStatusCodeValue()); + assertEquals(200, response.getStatusCodeValue()); } @Test - public void testReadinessSuccess() throws Exception { + void testReadinessSuccess() throws Exception { Mockito.when(configInfoPersistService.configInfoCount(any(String.class))).thenReturn(0); Mockito.when(serverStatusManager.getServerStatus()).thenReturn(ServerStatus.UP); ResponseEntity response = healthController.readiness(null); - Assert.assertEquals(200, response.getStatusCodeValue()); - Assert.assertEquals("OK", response.getBody()); + assertEquals(200, response.getStatusCodeValue()); + assertEquals("OK", response.getBody()); } @Test - public void testReadinessBothFailure() { + void testReadinessBothFailure() { // Config and Naming are not in readiness Mockito.when(configInfoPersistService.configInfoCount(any(String.class))) .thenThrow(new RuntimeException("HealthControllerTest.testReadiness")); - Mockito.when(serverStatusManager.getServerStatus()) - .thenThrow(new RuntimeException("HealthControllerTest.testReadiness")); + Mockito.when(serverStatusManager.getServerStatus()).thenThrow(new RuntimeException("HealthControllerTest.testReadiness")); ResponseEntity response = healthController.readiness(null); - Assert.assertEquals(500, response.getStatusCodeValue()); - Assert.assertEquals("naming and config not in readiness", response.getBody()); + assertEquals(500, response.getStatusCodeValue()); + assertEquals("naming and config not in readiness", response.getBody()); } @Test - public void testReadinessConfigFailure() { + void testReadinessConfigFailure() { // Config is not in readiness Mockito.when(configInfoPersistService.configInfoCount(any(String.class))) .thenThrow(new RuntimeException("HealthControllerTest.testReadiness")); Mockito.when(serverStatusManager.getServerStatus()).thenReturn(ServerStatus.UP); ResponseEntity response = healthController.readiness(null); - Assert.assertEquals(500, response.getStatusCodeValue()); - Assert.assertEquals("config not in readiness", response.getBody()); + assertEquals(500, response.getStatusCodeValue()); + assertEquals("config not in readiness", response.getBody()); } @Test - public void testReadinessNamingFailure() { + void testReadinessNamingFailure() { // Naming is not in readiness Mockito.when(configInfoPersistService.configInfoCount(any(String.class))).thenReturn(0); - Mockito.when(serverStatusManager.getServerStatus()) - .thenThrow(new RuntimeException("HealthControllerTest.testReadiness")); + Mockito.when(serverStatusManager.getServerStatus()).thenThrow(new RuntimeException("HealthControllerTest.testReadiness")); ResponseEntity response = healthController.readiness(null); - Assert.assertEquals(500, response.getStatusCodeValue()); - Assert.assertEquals("naming not in readiness", response.getBody()); + assertEquals(500, response.getStatusCodeValue()); + assertEquals("naming not in readiness", response.getBody()); } } diff --git a/console/src/test/java/com/alibaba/nacos/console/controller/NamespaceControllerTest.java b/console/src/test/java/com/alibaba/nacos/console/controller/NamespaceControllerTest.java index c1f4c1e0212..5fc208a687b 100644 --- a/console/src/test/java/com/alibaba/nacos/console/controller/NamespaceControllerTest.java +++ b/console/src/test/java/com/alibaba/nacos/console/controller/NamespaceControllerTest.java @@ -18,22 +18,22 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.common.model.RestResult; -import com.alibaba.nacos.core.namespace.repository.NamespacePersistService; import com.alibaba.nacos.core.namespace.model.Namespace; +import com.alibaba.nacos.core.namespace.repository.NamespacePersistService; import com.alibaba.nacos.core.service.NamespaceOperationService; -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.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; import java.util.List; -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; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.matches; @@ -41,8 +41,8 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class NamespaceControllerTest { +@ExtendWith(MockitoExtension.class) +class NamespaceControllerTest { @InjectMocks private NamespaceController namespaceController; @@ -53,13 +53,13 @@ public class NamespaceControllerTest { @Mock private NamespaceOperationService namespaceOperationService; - @Before - public void setUp() { + @BeforeEach + void setUp() { } @Test - public void testGetNamespaces() throws Exception { + void testGetNamespaces() throws Exception { Namespace namespace = new Namespace("", "public"); when(namespaceOperationService.getNamespaceList()).thenReturn(Collections.singletonList(namespace)); RestResult> actual = namespaceController.getNamespaces(); @@ -69,20 +69,20 @@ public void testGetNamespaces() throws Exception { } @Test - public void testGetNamespaceByNamespaceId() throws Exception { + void testGetNamespaceByNamespaceId() throws Exception { Namespace namespace = new Namespace("", "public", "", 0, 0, 0); when(namespaceOperationService.getNamespace("")).thenReturn(namespace); assertEquals(namespace, namespaceController.getNamespace("")); } @Test - public void testCreateNamespaceWithCustomId() throws Exception { + void testCreateNamespaceWithCustomId() throws Exception { namespaceController.createNamespace("test-Id", "testName", "testDesc"); verify(namespaceOperationService).createNamespace("test-Id", "testName", "testDesc"); } - + @Test - public void testCreateNamespaceWithIllegalName() { + void testCreateNamespaceWithIllegalName() { assertFalse(namespaceController.createNamespace(null, "test@Name", "testDesc")); assertFalse(namespaceController.createNamespace(null, "test#Name", "testDesc")); assertFalse(namespaceController.createNamespace(null, "test$Name", "testDesc")); @@ -91,21 +91,21 @@ public void testCreateNamespaceWithIllegalName() { assertFalse(namespaceController.createNamespace(null, "test&Name", "testDesc")); assertFalse(namespaceController.createNamespace(null, "test*Name", "testDesc")); } - + @Test - public void testCreateNamespaceWithNonUniqueId() throws Exception { + void testCreateNamespaceWithNonUniqueId() throws Exception { when(namespacePersistService.tenantInfoCountByTenantId("test-Id")).thenReturn(1); assertFalse(namespaceController.createNamespace("test-Id", "testNam2", "testDesc")); } @Test - public void testCreateNamespaceWithIllegalCustomId() throws Exception { + void testCreateNamespaceWithIllegalCustomId() throws Exception { assertFalse(namespaceController.createNamespace("test.Id", "testName", "testDesc")); verify(namespaceOperationService, never()).createNamespace("test.Id", "testName", "testDesc"); } @Test - public void testCreateNamespaceWithLongCustomId() throws Exception { + void testCreateNamespaceWithLongCustomId() throws Exception { StringBuilder longId = new StringBuilder(); for (int i = 0; i < 129; i++) { longId.append("a"); @@ -115,22 +115,20 @@ public void testCreateNamespaceWithLongCustomId() throws Exception { } @Test - public void testCreateNamespaceWithAutoId() throws Exception { + void testCreateNamespaceWithAutoId() throws Exception { assertFalse(namespaceController.createNamespace("", "testName", "testDesc")); - verify(namespaceOperationService) - .createNamespace(matches("[A-Za-z\\d]{8}-[A-Za-z\\d]{4}-[A-Za-z\\d]{4}-[A-Za-z\\d]{4}-[A-Za-z\\d]{12}"), - eq("testName"), eq("testDesc")); + verify(namespaceOperationService).createNamespace( + matches("[A-Za-z\\d]{8}-[A-Za-z\\d]{4}-[A-Za-z\\d]{4}-[A-Za-z\\d]{4}-[A-Za-z\\d]{12}"), eq("testName"), eq("testDesc")); } @Test - public void testCreateNamespaceFailure() throws NacosException { - when(namespaceOperationService.createNamespace(anyString(), anyString(), anyString())) - .thenThrow(new NacosException(500, "test")); + void testCreateNamespaceFailure() throws NacosException { + when(namespaceOperationService.createNamespace(anyString(), anyString(), anyString())).thenThrow(new NacosException(500, "test")); assertFalse(namespaceController.createNamespace("", "testName", "testDesc")); } @Test - public void testCheckNamespaceIdExist() throws Exception { + void testCheckNamespaceIdExist() throws Exception { when(namespacePersistService.tenantInfoCountByTenantId("public")).thenReturn(1); when(namespacePersistService.tenantInfoCountByTenantId("123")).thenReturn(0); assertFalse(namespaceController.checkNamespaceIdExist("")); @@ -139,13 +137,13 @@ public void testCheckNamespaceIdExist() throws Exception { } @Test - public void testEditNamespace() { + void testEditNamespace() { namespaceController.editNamespace("test-Id", "testName", "testDesc"); verify(namespaceOperationService).editNamespace("test-Id", "testName", "testDesc"); } - + @Test - public void testEditNamespaceWithIllegalName() { + void testEditNamespaceWithIllegalName() { assertFalse(namespaceController.createNamespace(null, "test@Name", "testDesc")); assertFalse(namespaceController.createNamespace(null, "test#Name", "testDesc")); assertFalse(namespaceController.createNamespace(null, "test$Name", "testDesc")); @@ -156,7 +154,7 @@ public void testEditNamespaceWithIllegalName() { } @Test - public void deleteConfig() throws Exception { + void deleteConfig() throws Exception { namespaceController.deleteNamespace("test-Id"); verify(namespaceOperationService).removeNamespace("test-Id"); } diff --git a/console/src/test/java/com/alibaba/nacos/console/controller/ServerStateControllerTest.java b/console/src/test/java/com/alibaba/nacos/console/controller/ServerStateControllerTest.java index 7a0249690a0..a37082a84ef 100644 --- a/console/src/test/java/com/alibaba/nacos/console/controller/ServerStateControllerTest.java +++ b/console/src/test/java/com/alibaba/nacos/console/controller/ServerStateControllerTest.java @@ -21,12 +21,11 @@ import com.alibaba.nacos.sys.env.Constants; import com.alibaba.nacos.sys.env.EnvUtil; import com.fasterxml.jackson.databind.node.ObjectNode; -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.InjectMocks; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.mock.env.MockEnvironment; import org.springframework.mock.web.MockHttpServletResponse; @@ -35,6 +34,8 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * ServerStateController unit test. * @@ -43,34 +44,33 @@ * @Date: 2022/8/13 10:54 * @Description: TODO */ -@RunWith(MockitoJUnitRunner.class) -public class ServerStateControllerTest { +@ExtendWith(MockitoExtension.class) +class ServerStateControllerTest { + + private static final String CONSOLE_URL = "/v1/console/server/state"; @InjectMocks private ServerStateController serverStateController; private MockMvc mockmvc; - private static final String CONSOLE_URL = "/v1/console/server/state"; - private ConfigurableEnvironment environment; - @Before - public void setUp() { + @BeforeEach + void setUp() { environment = new MockEnvironment(); EnvUtil.setEnvironment(environment); mockmvc = MockMvcBuilders.standaloneSetup(serverStateController).build(); } @Test - public void serverState() throws Exception { + void serverState() throws Exception { MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(CONSOLE_URL); MockHttpServletResponse response = mockmvc.perform(builder).andReturn().getResponse(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); ObjectNode responseContent = JacksonUtils.toObj(response.getContentAsByteArray(), ObjectNode.class); - Assert.assertEquals(EnvUtil.STANDALONE_MODE_CLUSTER, - responseContent.get(Constants.STARTUP_MODE_STATE).asText()); - Assert.assertEquals("null", responseContent.get(Constants.FUNCTION_MODE_STATE).asText()); - Assert.assertEquals(VersionUtils.version, responseContent.get(Constants.NACOS_VERSION).asText()); + assertEquals(EnvUtil.STANDALONE_MODE_CLUSTER, responseContent.get(Constants.STARTUP_MODE_STATE).asText()); + assertEquals("null", responseContent.get(Constants.FUNCTION_MODE_STATE).asText()); + assertEquals(VersionUtils.version, responseContent.get(Constants.NACOS_VERSION).asText()); } } diff --git a/console/src/test/java/com/alibaba/nacos/console/controller/v2/HealthControllerV2Test.java b/console/src/test/java/com/alibaba/nacos/console/controller/v2/HealthControllerV2Test.java index f725339cc5a..e64e08a9213 100644 --- a/console/src/test/java/com/alibaba/nacos/console/controller/v2/HealthControllerV2Test.java +++ b/console/src/test/java/com/alibaba/nacos/console/controller/v2/HealthControllerV2Test.java @@ -23,19 +23,19 @@ import com.alibaba.nacos.naming.cluster.NamingReadinessCheckService; import com.alibaba.nacos.naming.cluster.ServerStatus; import com.alibaba.nacos.naming.cluster.ServerStatusManager; -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.InjectMocks; 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.List; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; /** @@ -43,8 +43,8 @@ * * @author DiligenceLai */ -@RunWith(MockitoJUnitRunner.class) -public class HealthControllerV2Test { +@ExtendWith(MockitoExtension.class) +class HealthControllerV2Test { @InjectMocks private HealthControllerV2 healthControllerV2; @@ -55,68 +55,66 @@ public class HealthControllerV2Test { @Mock private ServerStatusManager serverStatusManager; - @Before - public void setUp() { + @BeforeEach + void setUp() { // auto register to module health checker holder. new NamingReadinessCheckService(serverStatusManager); new ConfigReadinessCheckService(configInfoPersistService); } - @After - public void tearDown() throws IllegalAccessException, NoSuchFieldException { + @AfterEach + void tearDown() throws IllegalAccessException, NoSuchFieldException { Field moduleHealthCheckersField = ModuleHealthCheckerHolder.class.getDeclaredField("moduleHealthCheckers"); moduleHealthCheckersField.setAccessible(true); ((List) moduleHealthCheckersField.get(ModuleHealthCheckerHolder.getInstance())).clear(); } @Test - public void testLiveness() throws Exception { + void testLiveness() throws Exception { Result result = healthControllerV2.liveness(); - Assert.assertEquals(0, result.getCode().intValue()); + assertEquals(0, result.getCode().intValue()); } @Test - public void testReadinessSuccess() throws Exception { + void testReadinessSuccess() throws Exception { Mockito.when(configInfoPersistService.configInfoCount(any(String.class))).thenReturn(0); Mockito.when(serverStatusManager.getServerStatus()).thenReturn(ServerStatus.UP); Result result = healthControllerV2.readiness(null); - Assert.assertEquals(0, result.getCode().intValue()); - Assert.assertEquals("success", result.getMessage()); + assertEquals(0, result.getCode().intValue()); + assertEquals("success", result.getMessage()); } @Test - public void testReadinessBothFailure() { + void testReadinessBothFailure() { // Config and Naming are not in readiness Mockito.when(configInfoPersistService.configInfoCount(any(String.class))) .thenThrow(new RuntimeException("HealthControllerV2Test.testReadiness")); - Mockito.when(serverStatusManager.getServerStatus()) - .thenThrow(new RuntimeException("HealthControllerV2Test.testReadiness")); + Mockito.when(serverStatusManager.getServerStatus()).thenThrow(new RuntimeException("HealthControllerV2Test.testReadiness")); Result result = healthControllerV2.readiness(null); - Assert.assertEquals(30000, result.getCode().intValue()); - Assert.assertEquals("naming and config not in readiness", result.getMessage()); + assertEquals(30000, result.getCode().intValue()); + assertEquals("naming and config not in readiness", result.getMessage()); } @Test - public void testReadinessConfigFailure() { + void testReadinessConfigFailure() { // Config is not in readiness Mockito.when(configInfoPersistService.configInfoCount(any(String.class))) .thenThrow(new RuntimeException("HealthControllerV2Test.testReadiness")); Mockito.when(serverStatusManager.getServerStatus()).thenReturn(ServerStatus.UP); Result result = healthControllerV2.readiness(null); - Assert.assertEquals(30000, result.getCode().intValue()); - Assert.assertEquals("config not in readiness", result.getMessage()); + assertEquals(30000, result.getCode().intValue()); + assertEquals("config not in readiness", result.getMessage()); } @Test - public void testReadinessNamingFailure() { + void testReadinessNamingFailure() { // Naming is not in readiness Mockito.when(configInfoPersistService.configInfoCount(any(String.class))).thenReturn(0); - Mockito.when(serverStatusManager.getServerStatus()) - .thenThrow(new RuntimeException("HealthControllerV2Test.testReadiness")); + Mockito.when(serverStatusManager.getServerStatus()).thenThrow(new RuntimeException("HealthControllerV2Test.testReadiness")); Result result = healthControllerV2.readiness(null); - Assert.assertEquals(30000, result.getCode().intValue()); - Assert.assertEquals("naming not in readiness", result.getMessage()); + assertEquals(30000, result.getCode().intValue()); + assertEquals("naming not in readiness", result.getMessage()); } } diff --git a/console/src/test/java/com/alibaba/nacos/console/controller/v2/NamespaceControllerV2Test.java b/console/src/test/java/com/alibaba/nacos/console/controller/v2/NamespaceControllerV2Test.java index 16fd58aba06..658b0706a6f 100644 --- a/console/src/test/java/com/alibaba/nacos/console/controller/v2/NamespaceControllerV2Test.java +++ b/console/src/test/java/com/alibaba/nacos/console/controller/v2/NamespaceControllerV2Test.java @@ -19,22 +19,23 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.model.v2.ErrorCode; import com.alibaba.nacos.api.model.v2.Result; -import com.alibaba.nacos.core.namespace.model.NamespaceTypeEnum; import com.alibaba.nacos.core.namespace.model.Namespace; +import com.alibaba.nacos.core.namespace.model.NamespaceTypeEnum; import com.alibaba.nacos.core.namespace.model.form.NamespaceForm; import com.alibaba.nacos.core.namespace.repository.NamespacePersistService; import com.alibaba.nacos.core.service.NamespaceOperationService; -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.Collections; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; +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.verify; import static org.mockito.Mockito.when; @@ -44,30 +45,30 @@ * @author dongyafei * @date 2022/8/16 */ -@RunWith(MockitoJUnitRunner.class) -public class NamespaceControllerV2Test { +@ExtendWith(MockitoExtension.class) +class NamespaceControllerV2Test { + + private static final String TEST_NAMESPACE_ID = "testId"; + + private static final String TEST_NAMESPACE_NAME = "testName"; + + private static final String TEST_NAMESPACE_DESC = "testDesc"; private NamespaceControllerV2 namespaceControllerV2; @Mock private NamespaceOperationService namespaceOperationService; - + @Mock private NamespacePersistService namespacePersistService; - private static final String TEST_NAMESPACE_ID = "testId"; - - private static final String TEST_NAMESPACE_NAME = "testName"; - - private static final String TEST_NAMESPACE_DESC = "testDesc"; - - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { namespaceControllerV2 = new NamespaceControllerV2(namespaceOperationService, namespacePersistService); } @Test - public void testGetNamespaceList() { + void testGetNamespaceList() { Namespace namespace = new Namespace(); namespace.setNamespace(TEST_NAMESPACE_ID); namespace.setNamespaceShowName(TEST_NAMESPACE_NAME); @@ -89,7 +90,7 @@ public void testGetNamespaceList() { } @Test - public void testGetNamespace() throws NacosException { + void testGetNamespace() throws NacosException { Namespace namespaceAllInfo = new Namespace(TEST_NAMESPACE_ID, TEST_NAMESPACE_NAME, TEST_NAMESPACE_DESC, 200, 1, NamespaceTypeEnum.GLOBAL.getType()); when(namespaceOperationService.getNamespace(TEST_NAMESPACE_ID)).thenReturn(namespaceAllInfo); @@ -105,49 +106,48 @@ public void testGetNamespace() throws NacosException { } @Test - public void testCreateNamespace() throws NacosException { - when(namespaceOperationService.createNamespace(TEST_NAMESPACE_ID, TEST_NAMESPACE_NAME, TEST_NAMESPACE_DESC)) - .thenReturn(true); - Result result = namespaceControllerV2 - .createNamespace(new NamespaceForm(TEST_NAMESPACE_ID, TEST_NAMESPACE_NAME, TEST_NAMESPACE_DESC)); + void testCreateNamespace() throws NacosException { + when(namespaceOperationService.createNamespace(TEST_NAMESPACE_ID, TEST_NAMESPACE_NAME, TEST_NAMESPACE_DESC)).thenReturn(true); + Result result = namespaceControllerV2.createNamespace( + new NamespaceForm(TEST_NAMESPACE_ID, TEST_NAMESPACE_NAME, TEST_NAMESPACE_DESC)); verify(namespaceOperationService).createNamespace(TEST_NAMESPACE_ID, TEST_NAMESPACE_NAME, TEST_NAMESPACE_DESC); assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode()); - assertEquals(true, result.getData()); + assertTrue(result.getData()); } - + @Test - public void testCreateNamespaceWithIllegalName() { + void testCreateNamespaceWithIllegalName() { NamespaceForm form = new NamespaceForm(); form.setNamespaceDesc("testDesc"); form.setNamespaceName("test@Name"); assertThrows(NacosException.class, () -> namespaceControllerV2.createNamespace(form)); - + form.setNamespaceName("test$Name"); assertThrows(NacosException.class, () -> namespaceControllerV2.createNamespace(form)); - + form.setNamespaceName("test#Name"); assertThrows(NacosException.class, () -> namespaceControllerV2.createNamespace(form)); - + form.setNamespaceName("test%Name"); assertThrows(NacosException.class, () -> namespaceControllerV2.createNamespace(form)); - + form.setNamespaceName("test^Name"); assertThrows(NacosException.class, () -> namespaceControllerV2.createNamespace(form)); - + form.setNamespaceName("test&Name"); assertThrows(NacosException.class, () -> namespaceControllerV2.createNamespace(form)); - + form.setNamespaceName("test*Name"); assertThrows(NacosException.class, () -> namespaceControllerV2.createNamespace(form)); - + form.setNamespaceName(""); assertThrows(NacosException.class, () -> namespaceControllerV2.createNamespace(form)); } - + @Test - public void testCreateNamespaceWithNonUniqueId() { + void testCreateNamespaceWithNonUniqueId() { when(namespacePersistService.tenantInfoCountByTenantId("test-id")).thenReturn(1); NamespaceForm form = new NamespaceForm(); form.setNamespaceId("test-id"); @@ -157,54 +157,53 @@ public void testCreateNamespaceWithNonUniqueId() { } @Test - public void testEditNamespace() throws NacosException { - when(namespaceOperationService.editNamespace(TEST_NAMESPACE_ID, TEST_NAMESPACE_NAME, TEST_NAMESPACE_DESC)) - .thenReturn(true); - Result result = namespaceControllerV2 - .editNamespace(new NamespaceForm(TEST_NAMESPACE_ID, TEST_NAMESPACE_NAME, TEST_NAMESPACE_DESC)); + void testEditNamespace() throws NacosException { + when(namespaceOperationService.editNamespace(TEST_NAMESPACE_ID, TEST_NAMESPACE_NAME, TEST_NAMESPACE_DESC)).thenReturn(true); + Result result = namespaceControllerV2.editNamespace( + new NamespaceForm(TEST_NAMESPACE_ID, TEST_NAMESPACE_NAME, TEST_NAMESPACE_DESC)); verify(namespaceOperationService).editNamespace(TEST_NAMESPACE_ID, TEST_NAMESPACE_NAME, TEST_NAMESPACE_DESC); assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode()); - assertEquals(true, result.getData()); + assertTrue(result.getData()); } - + @Test - public void testEditNamespaceWithIllegalName() { + void testEditNamespaceWithIllegalName() { NamespaceForm form = new NamespaceForm(); form.setNamespaceId("test-id"); form.setNamespaceDesc("testDesc"); - + form.setNamespaceName("test@Name"); assertThrows(NacosException.class, () -> namespaceControllerV2.createNamespace(form)); - + form.setNamespaceName("test#Name"); assertThrows(NacosException.class, () -> namespaceControllerV2.createNamespace(form)); - + form.setNamespaceName("test$Name"); assertThrows(NacosException.class, () -> namespaceControllerV2.createNamespace(form)); - + form.setNamespaceName("test%Name"); assertThrows(NacosException.class, () -> namespaceControllerV2.createNamespace(form)); - + form.setNamespaceName("test^Name"); assertThrows(NacosException.class, () -> namespaceControllerV2.createNamespace(form)); - + form.setNamespaceName("test&Name"); assertThrows(NacosException.class, () -> namespaceControllerV2.createNamespace(form)); - + form.setNamespaceName("test*Name"); assertThrows(NacosException.class, () -> namespaceControllerV2.createNamespace(form)); } @Test - public void testDeleteNamespace() { + void testDeleteNamespace() { when(namespaceOperationService.removeNamespace(TEST_NAMESPACE_ID)).thenReturn(true); Result result = namespaceControllerV2.deleteNamespace(TEST_NAMESPACE_ID); verify(namespaceOperationService).removeNamespace(TEST_NAMESPACE_ID); assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode()); - assertEquals(true, result.getData()); + assertTrue(result.getData()); } } diff --git a/console/src/test/java/com/alibaba/nacos/console/exception/ConsoleExceptionHandlerTest.java b/console/src/test/java/com/alibaba/nacos/console/exception/ConsoleExceptionHandlerTest.java index 6b0e30a307a..c1a0fd24edc 100644 --- a/console/src/test/java/com/alibaba/nacos/console/exception/ConsoleExceptionHandlerTest.java +++ b/console/src/test/java/com/alibaba/nacos/console/exception/ConsoleExceptionHandlerTest.java @@ -19,55 +19,55 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; import com.alibaba.nacos.console.controller.v2.HealthControllerV2; -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.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; + import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @WebMvcTest(ConsoleExceptionHandlerTest.class) -public class ConsoleExceptionHandlerTest { +class ConsoleExceptionHandlerTest { + private MockMvc mockMvc; - + @Autowired private WebApplicationContext context; - + @MockBean private HealthControllerV2 healthControllerV2; - - @Before - public void before() { + + @BeforeEach + void before() { mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); } - + @Test - public void testNacosRunTimeExceptionHandler() throws Exception { + void testNacosRunTimeExceptionHandler() throws Exception { // 设置HealthControllerV2的行为,使其抛出NacosRuntimeException并被ConsoleExceptionHandler捕获处理 - when(healthControllerV2.liveness()) - .thenThrow(new NacosRuntimeException(NacosException.INVALID_PARAM)) - .thenThrow(new NacosRuntimeException(NacosException.SERVER_ERROR)) - .thenThrow(new NacosRuntimeException(503)); - + when(healthControllerV2.liveness()).thenThrow(new NacosRuntimeException(NacosException.INVALID_PARAM)) + .thenThrow(new NacosRuntimeException(NacosException.SERVER_ERROR)).thenThrow(new NacosRuntimeException(503)); + // 执行请求并验证响应码 - ResultActions resultActions = mockMvc.perform(get("/v2/console/health/liveness")); + ResultActions resultActions = mockMvc.perform(get("/v2/console/health/liveness")); resultActions.andExpect(MockMvcResultMatchers.status().is(NacosException.INVALID_PARAM)); - + // 执行请求并验证响应码 - ResultActions resultActions1 = mockMvc.perform(get("/v2/console/health/liveness")); + ResultActions resultActions1 = mockMvc.perform(get("/v2/console/health/liveness")); resultActions1.andExpect(MockMvcResultMatchers.status().is(NacosException.SERVER_ERROR)); - + // 执行请求并验证响应码 - ResultActions resultActions2 = mockMvc.perform(get("/v2/console/health/liveness")); + ResultActions resultActions2 = mockMvc.perform(get("/v2/console/health/liveness")); resultActions2.andExpect(MockMvcResultMatchers.status().is(503)); } } \ No newline at end of file diff --git a/console/src/test/java/com/alibaba/nacos/console/exception/NacosApiExceptionHandlerTest.java b/console/src/test/java/com/alibaba/nacos/console/exception/NacosApiExceptionHandlerTest.java index 41784642f2d..be8b57a0626 100644 --- a/console/src/test/java/com/alibaba/nacos/console/exception/NacosApiExceptionHandlerTest.java +++ b/console/src/test/java/com/alibaba/nacos/console/exception/NacosApiExceptionHandlerTest.java @@ -19,56 +19,53 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; import com.alibaba.nacos.console.controller.v2.NamespaceControllerV2; -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.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; + import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -@RunWith(SpringRunner.class) @WebMvcTest(NacosApiExceptionHandler.class) -public class NacosApiExceptionHandlerTest { +class NacosApiExceptionHandlerTest { + private MockMvc mockMvc; - + @Autowired private WebApplicationContext context; - + @MockBean private NamespaceControllerV2 namespaceControllerV2; - - @Before - public void before() { + + @BeforeEach + void before() { mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); } - + @Test - public void testNacosRunTimeExceptionHandler() throws Exception { + void testNacosRunTimeExceptionHandler() throws Exception { // 设置NamespaceControllerV2的行为,使其抛出NacosRuntimeException并被NacosApiExceptionHandler捕获处理 - when(namespaceControllerV2.createNamespace(any())) - .thenThrow(new NacosRuntimeException(NacosException.INVALID_PARAM)) - .thenThrow(new NacosRuntimeException(NacosException.SERVER_ERROR)) - .thenThrow(new NacosRuntimeException(503)); - + when(namespaceControllerV2.createNamespace(any())).thenThrow(new NacosRuntimeException(NacosException.INVALID_PARAM)) + .thenThrow(new NacosRuntimeException(NacosException.SERVER_ERROR)).thenThrow(new NacosRuntimeException(503)); + // 执行请求并验证响应码 - ResultActions resultActions = mockMvc.perform(post("/v2/console/namespace")); + ResultActions resultActions = mockMvc.perform(post("/v2/console/namespace")); resultActions.andExpect(MockMvcResultMatchers.status().is(NacosException.INVALID_PARAM)); - + // 执行请求并验证响应码 - ResultActions resultActions1 = mockMvc.perform(post("/v2/console/namespace")); + ResultActions resultActions1 = mockMvc.perform(post("/v2/console/namespace")); resultActions1.andExpect(MockMvcResultMatchers.status().is(NacosException.SERVER_ERROR)); - + // 执行请求并验证响应码 - ResultActions resultActions2 = mockMvc.perform(post("/v2/console/namespace")); + ResultActions resultActions2 = mockMvc.perform(post("/v2/console/namespace")); resultActions2.andExpect(MockMvcResultMatchers.status().is(503)); } -} \ No newline at end of file +} diff --git a/console/src/test/java/com/alibaba/nacos/console/filter/XssFilterTest.java b/console/src/test/java/com/alibaba/nacos/console/filter/XssFilterTest.java index 45212445625..6598092264c 100644 --- a/console/src/test/java/com/alibaba/nacos/console/filter/XssFilterTest.java +++ b/console/src/test/java/com/alibaba/nacos/console/filter/XssFilterTest.java @@ -16,11 +16,11 @@ package com.alibaba.nacos.console.filter; -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.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import javax.servlet.FilterChain; import javax.servlet.ServletException; @@ -28,8 +28,8 @@ import javax.servlet.http.HttpServletResponse; import java.io.IOException; -@RunWith(MockitoJUnitRunner.class) -public class XssFilterTest { +@ExtendWith(MockitoExtension.class) +class XssFilterTest { private static final String CONTENT_SECURITY_POLICY_HEADER = "Content-Security-Policy"; @@ -45,7 +45,7 @@ public class XssFilterTest { private FilterChain filterChain; @Test - public void testSetResponseHeader() throws ServletException, IOException { + void testSetResponseHeader() throws ServletException, IOException { XssFilter xssFilter = new XssFilter(); xssFilter.doFilterInternal(request, response, filterChain); Mockito.verify(response).setHeader(CONTENT_SECURITY_POLICY_HEADER, CONTENT_SECURITY_POLICY); diff --git a/console/src/test/java/com/alibaba/nacos/console/paramcheck/ParamExtractorTest.java b/console/src/test/java/com/alibaba/nacos/console/paramcheck/ParamExtractorTest.java index f14029bafd5..ba6f68589b1 100644 --- a/console/src/test/java/com/alibaba/nacos/console/paramcheck/ParamExtractorTest.java +++ b/console/src/test/java/com/alibaba/nacos/console/paramcheck/ParamExtractorTest.java @@ -22,19 +22,19 @@ import com.alibaba.nacos.core.paramcheck.ExtractorManager; import com.alibaba.nacos.core.paramcheck.ParamCheckerFilter; import com.alibaba.nacos.sys.env.EnvUtil; -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.MockedStatic; import org.mockito.Mockito; import org.mockito.internal.verification.Times; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import java.lang.reflect.Method; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Param Console ExtractorTest. @@ -42,8 +42,8 @@ * @author 985492783@qq.com * @date 2023/11/9 17:07 */ -@RunWith(MockitoJUnitRunner.class) -public class ParamExtractorTest { +@ExtendWith(MockitoExtension.class) +class ParamExtractorTest { @Mock private ControllerMethodsCache methodsCache; @@ -51,16 +51,14 @@ public class ParamExtractorTest { private ParamCheckerFilter filter; @Test - public void testDefaultFilter() throws Exception { + void testDefaultFilter() throws Exception { MockedStatic mockedStatic = Mockito.mockStatic(EnvUtil.class); final Method check = NamespaceController.class.getMethod("getNamespaces"); - ExtractorManager.Extractor annotation = NamespaceController.class.getAnnotation( - ExtractorManager.Extractor.class); + ExtractorManager.Extractor annotation = NamespaceController.class.getAnnotation(ExtractorManager.Extractor.class); AbstractHttpParamExtractor httpExtractor = Mockito.spy(ExtractorManager.getHttpExtractor(annotation)); MockedStatic managerMockedStatic = Mockito.mockStatic(ExtractorManager.class); - mockedStatic.when(() -> EnvUtil.getProperty(Mockito.any(), Mockito.any(), Mockito.any())) - .thenAnswer((k) -> k.getArgument(2)); + mockedStatic.when(() -> EnvUtil.getProperty(Mockito.any(), Mockito.any(), Mockito.any())).thenAnswer((k) -> k.getArgument(2)); filter = new ParamCheckerFilter(methodsCache); managerMockedStatic.when(() -> ExtractorManager.getHttpExtractor(annotation)).thenReturn(httpExtractor); @@ -71,7 +69,7 @@ public void testDefaultFilter() throws Exception { filter.doFilter(request, response, (servletRequest, servletResponse) -> { }); - assertEquals(httpExtractor.getClass(), ConsoleDefaultHttpParamExtractor.class); + assertEquals(ConsoleDefaultHttpParamExtractor.class, httpExtractor.getClass()); Mockito.verify(httpExtractor, new Times(1)).extractParam(Mockito.any()); managerMockedStatic.close(); mockedStatic.close(); diff --git a/core/pom.xml b/core/pom.xml index bdfb5f762de..4ab09dda594 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -75,17 +75,6 @@ spring-boot-starter-security - - org.springframework.boot - spring-boot-starter-test - test - - - org.junit.vintage - junit-vintage-engine - - - org.springframework.security spring-security-test @@ -95,11 +84,17 @@ org.springframework spring-test + test org.springframework.boot spring-boot-test + test + + + io.grpc + grpc-testing org.apache.tomcat.embed @@ -143,9 +138,20 @@ + - io.grpc - grpc-testing + com.asarkar.grpc + grpc-test + 1.2.2 + + + io.grpc + * + + + test com.alibaba.nacos diff --git a/core/src/main/java/com/alibaba/nacos/core/auth/AuthFilter.java b/core/src/main/java/com/alibaba/nacos/core/auth/AuthFilter.java index 55c00f9852e..5bf98b5f1e6 100644 --- a/core/src/main/java/com/alibaba/nacos/core/auth/AuthFilter.java +++ b/core/src/main/java/com/alibaba/nacos/core/auth/AuthFilter.java @@ -22,6 +22,8 @@ import com.alibaba.nacos.common.utils.ExceptionUtil; import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.core.code.ControllerMethodsCache; +import com.alibaba.nacos.core.context.RequestContext; +import com.alibaba.nacos.core.context.RequestContextHolder; import com.alibaba.nacos.core.utils.Loggers; import com.alibaba.nacos.core.utils.WebUtils; import com.alibaba.nacos.plugin.auth.api.IdentityContext; @@ -120,11 +122,16 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha Resource resource = protocolAuthService.parseResource(req, secured); IdentityContext identityContext = protocolAuthService.parseIdentity(req); boolean result = protocolAuthService.validateIdentity(identityContext, resource); + RequestContext requestContext = RequestContextHolder.getContext(); + requestContext.getAuthContext().setIdentityContext(identityContext); + requestContext.getAuthContext().setResource(resource); + if (null == requestContext.getAuthContext().getAuthResult()) { + requestContext.getAuthContext().setAuthResult(result); + } if (!result) { // TODO Get reason of failure throw new AccessException("Validate Identity failed."); } - injectIdentityId(req, identityContext); String action = secured.action().toString(); result = protocolAuthService.validateAuthority(identityContext, new Permission(resource, action)); if (!result) { @@ -146,21 +153,4 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server failed, " + e.getMessage()); } } - - /** - * Set identity id to request session, make sure some actual logic can get identity information. - * - *

    May be replaced with whole identityContext. - * - * @param request http request - * @param identityContext identity context - */ - private void injectIdentityId(HttpServletRequest request, IdentityContext identityContext) { - String identityId = identityContext.getParameter( - com.alibaba.nacos.plugin.auth.constant.Constants.Identity.IDENTITY_ID, StringUtils.EMPTY); - request.getSession() - .setAttribute(com.alibaba.nacos.plugin.auth.constant.Constants.Identity.IDENTITY_ID, identityId); - request.getSession().setAttribute(com.alibaba.nacos.plugin.auth.constant.Constants.Identity.IDENTITY_CONTEXT, - identityContext); - } } diff --git a/core/src/main/java/com/alibaba/nacos/core/auth/RemoteRequestAuthFilter.java b/core/src/main/java/com/alibaba/nacos/core/auth/RemoteRequestAuthFilter.java index ad9a250b01c..21b000cc9e4 100644 --- a/core/src/main/java/com/alibaba/nacos/core/auth/RemoteRequestAuthFilter.java +++ b/core/src/main/java/com/alibaba/nacos/core/auth/RemoteRequestAuthFilter.java @@ -24,6 +24,8 @@ import com.alibaba.nacos.auth.annotation.Secured; import com.alibaba.nacos.auth.config.AuthConfigs; import com.alibaba.nacos.common.utils.ExceptionUtil; +import com.alibaba.nacos.core.context.RequestContext; +import com.alibaba.nacos.core.context.RequestContextHolder; import com.alibaba.nacos.core.remote.AbstractRequestFilter; import com.alibaba.nacos.core.utils.Loggers; import com.alibaba.nacos.plugin.auth.api.IdentityContext; @@ -75,6 +77,12 @@ public Response filter(Request request, RequestMeta meta, Class handlerClazz) th Resource resource = protocolAuthService.parseResource(request, secured); IdentityContext identityContext = protocolAuthService.parseIdentity(request); boolean result = protocolAuthService.validateIdentity(identityContext, resource); + RequestContext requestContext = RequestContextHolder.getContext(); + requestContext.getAuthContext().setIdentityContext(identityContext); + requestContext.getAuthContext().setResource(resource); + if (null == requestContext.getAuthContext().getAuthResult()) { + requestContext.getAuthContext().setAuthResult(result); + } if (!result) { // TODO Get reason of failure throw new AccessException("Validate Identity failed."); diff --git a/core/src/main/java/com/alibaba/nacos/core/cluster/remote/ClusterRpcClientProxy.java b/core/src/main/java/com/alibaba/nacos/core/cluster/remote/ClusterRpcClientProxy.java index ac6f8b9af3d..8294bfd0c9a 100644 --- a/core/src/main/java/com/alibaba/nacos/core/cluster/remote/ClusterRpcClientProxy.java +++ b/core/src/main/java/com/alibaba/nacos/core/cluster/remote/ClusterRpcClientProxy.java @@ -25,7 +25,9 @@ import com.alibaba.nacos.common.remote.ConnectionType; import com.alibaba.nacos.common.remote.client.RpcClient; import com.alibaba.nacos.common.remote.client.RpcClientFactory; +import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig; import com.alibaba.nacos.common.remote.client.ServerListFactory; +import com.alibaba.nacos.common.remote.client.RpcClientTlsConfigFactory; import com.alibaba.nacos.common.utils.CollectionUtils; import com.alibaba.nacos.core.cluster.Member; import com.alibaba.nacos.core.cluster.MemberChangeListener; @@ -41,6 +43,7 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Properties; import java.util.Set; import java.util.stream.Collectors; @@ -152,10 +155,10 @@ public List getServerList() { * Using {@link EnvUtil#getAvailableProcessors(int)} to build cluster clients' grpc thread pool. */ private RpcClient buildRpcClient(ConnectionType type, Map labels, String memberClientKey) { - RpcClient clusterClient = RpcClientFactory - .createClusterClient(memberClientKey, type, EnvUtil.getAvailableProcessors(2), - EnvUtil.getAvailableProcessors(8), labels); - return clusterClient; + Properties properties = EnvUtil.getProperties(); + RpcClientTlsConfig config = RpcClientTlsConfigFactory.getInstance().createClusterConfig(properties); + return RpcClientFactory.createClusterClient(memberClientKey, type, EnvUtil.getAvailableProcessors(2), + EnvUtil.getAvailableProcessors(8), labels, config); } /** diff --git a/core/src/main/java/com/alibaba/nacos/core/context/RequestContext.java b/core/src/main/java/com/alibaba/nacos/core/context/RequestContext.java new file mode 100644 index 00000000000..24b0aea49c3 --- /dev/null +++ b/core/src/main/java/com/alibaba/nacos/core/context/RequestContext.java @@ -0,0 +1,96 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.context; + +import com.alibaba.nacos.core.context.addition.AuthContext; +import com.alibaba.nacos.core.context.addition.BasicContext; +import com.alibaba.nacos.core.context.addition.EngineContext; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +/** + * Nacos request context. + * + * @author xiweng.yy + */ +public class RequestContext { + + /** + * Optional, the request id. + *

      + *
    • For HTTP request, the id not usage, will generate automatically.
    • + *
    • For GRPC, the id is same with real request id.
    • + *
    + */ + private String requestId; + + /** + * Request start timestamp. + */ + private final long requestTimestamp; + + private final BasicContext basicContext; + + private final EngineContext engineContext; + + private final AuthContext authContext; + + private final Map extensionContexts; + + RequestContext(long requestTimestamp) { + this.requestId = UUID.randomUUID().toString(); + this.requestTimestamp = requestTimestamp; + this.basicContext = new BasicContext(); + this.engineContext = new EngineContext(); + this.authContext = new AuthContext(); + this.extensionContexts = new HashMap<>(1); + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + public String getRequestId() { + return requestId; + } + + public long getRequestTimestamp() { + return requestTimestamp; + } + + public BasicContext getBasicContext() { + return basicContext; + } + + public EngineContext getEngineContext() { + return engineContext; + } + + public AuthContext getAuthContext() { + return authContext; + } + + public Object getExtensionContext(String key) { + return extensionContexts.get(key); + } + + public void addExtensionContext(String key, Object value) { + extensionContexts.put(key, value); + } +} diff --git a/core/src/main/java/com/alibaba/nacos/core/context/RequestContextHolder.java b/core/src/main/java/com/alibaba/nacos/core/context/RequestContextHolder.java new file mode 100644 index 00000000000..316d82082d8 --- /dev/null +++ b/core/src/main/java/com/alibaba/nacos/core/context/RequestContextHolder.java @@ -0,0 +1,42 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.context; + +import java.util.function.Supplier; + +/** + * Holder for request context for each worker thread. + * + * @author xiweng.yy + */ +public class RequestContextHolder { + + private static final Supplier REQUEST_CONTEXT_FACTORY = () -> { + long requestTimestamp = System.currentTimeMillis(); + return new RequestContext(requestTimestamp); + }; + + private static final ThreadLocal CONTEXT_HOLDER = ThreadLocal.withInitial(REQUEST_CONTEXT_FACTORY); + + public static RequestContext getContext() { + return CONTEXT_HOLDER.get(); + } + + public static void removeContext() { + CONTEXT_HOLDER.remove(); + } +} diff --git a/core/src/main/java/com/alibaba/nacos/core/context/addition/AddressContext.java b/core/src/main/java/com/alibaba/nacos/core/context/addition/AddressContext.java new file mode 100644 index 00000000000..6120a25e8c3 --- /dev/null +++ b/core/src/main/java/com/alibaba/nacos/core/context/addition/AddressContext.java @@ -0,0 +1,90 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.context.addition; + +/** + * Nacos request address information context. + * + * @author xiweng.yy + */ +public class AddressContext { + + /** + * Request source ip, it's the ip of the client, most situations are same with remoteIp. + */ + private String sourceIp; + + /** + * Request source port, it's the port of the client, most situations are same with remoteIp. + */ + private int sourcePort; + + /** + * Request connection ip, it should be got from the socket, which means the ip seen by nacos server. + */ + private String remoteIp; + + /** + * Request connection port, it should be got from the socket, which means the port seen by nacos server. + */ + private int remotePort; + + /** + * Request host, it's the host of the client, nullable when can't get it from request or connection. + */ + private String host; + + public String getSourceIp() { + return sourceIp; + } + + public void setSourceIp(String sourceIp) { + this.sourceIp = sourceIp; + } + + public int getSourcePort() { + return sourcePort; + } + + public void setSourcePort(int sourcePort) { + this.sourcePort = sourcePort; + } + + public String getRemoteIp() { + return remoteIp; + } + + public void setRemoteIp(String remoteIp) { + this.remoteIp = remoteIp; + } + + public int getRemotePort() { + return remotePort; + } + + public void setRemotePort(int remotePort) { + this.remotePort = remotePort; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } +} diff --git a/core/src/main/java/com/alibaba/nacos/core/context/addition/AuthContext.java b/core/src/main/java/com/alibaba/nacos/core/context/addition/AuthContext.java new file mode 100644 index 00000000000..1f1ed4da70b --- /dev/null +++ b/core/src/main/java/com/alibaba/nacos/core/context/addition/AuthContext.java @@ -0,0 +1,63 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.context.addition; + +import com.alibaba.nacos.plugin.auth.api.IdentityContext; +import com.alibaba.nacos.plugin.auth.api.Resource; + +/** + * Nacos auth context, store and transport some auth plugin information to handler or trace log. + * + * @author xiweng.yy + */ +public class AuthContext { + + private IdentityContext identityContext; + + private Resource resource; + + /** + * Auth result, default is {@code true} or {@code false}. + * + *

    TODO with more auth result by auth plugin. + */ + private Object authResult; + + public IdentityContext getIdentityContext() { + return identityContext; + } + + public void setIdentityContext(IdentityContext identityContext) { + this.identityContext = identityContext; + } + + public Resource getResource() { + return resource; + } + + public void setResource(Resource resource) { + this.resource = resource; + } + + public Object getAuthResult() { + return authResult; + } + + public void setAuthResult(Object authResult) { + this.authResult = authResult; + } +} diff --git a/core/src/main/java/com/alibaba/nacos/core/context/addition/BasicContext.java b/core/src/main/java/com/alibaba/nacos/core/context/addition/BasicContext.java new file mode 100644 index 00000000000..4c712f83fd9 --- /dev/null +++ b/core/src/main/java/com/alibaba/nacos/core/context/addition/BasicContext.java @@ -0,0 +1,114 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.context.addition; + +import com.alibaba.nacos.api.common.Constants; + +/** + * Nacos request basic information context. + * + * @author xiweng.yy + */ +public class BasicContext { + + private static final String DEFAULT_APP = "unknown"; + + public static final String HTTP_PROTOCOL = "HTTP"; + + public static final String GRPC_PROTOCOL = "GRPC"; + + private final AddressContext addressContext; + + /** + * Request user agent, such as Nacos-Java-client:v2.4.0 + */ + private String userAgent; + + /** + * Request protocol type, HTTP or GRPC and so on. + */ + private String requestProtocol; + + /** + * Request target. + *

      + *
    • For HTTP protocol it should be `${Method} ${URI}`, such as `POST /v2/ns/instance`
    • + *
    • For GRPC protocol, it should be `${requestClass}`, such as `InstanceRequest`
    • + *
    + */ + private String requestTarget; + + /** + * Optional, mark the app name of the request from when client set app name, default `unknown`. + */ + private String app; + + /** + * Optional, mark the encoding of the request from when client set encoding, default `UTF-8`. + */ + private String encoding; + + public BasicContext() { + this.addressContext = new AddressContext(); + this.app = DEFAULT_APP; + this.encoding = Constants.ENCODE; + } + + public AddressContext getAddressContext() { + return addressContext; + } + + public String getUserAgent() { + return userAgent; + } + + public void setUserAgent(String userAgent) { + this.userAgent = userAgent; + } + + public String getRequestProtocol() { + return requestProtocol; + } + + public void setRequestProtocol(String requestProtocol) { + this.requestProtocol = requestProtocol; + } + + public String getRequestTarget() { + return requestTarget; + } + + public void setRequestTarget(String requestTarget) { + this.requestTarget = requestTarget; + } + + public String getApp() { + return app; + } + + public void setApp(String app) { + this.app = app; + } + + public String getEncoding() { + return encoding; + } + + public void setEncoding(String encoding) { + this.encoding = encoding; + } +} diff --git a/core/src/main/java/com/alibaba/nacos/core/context/addition/EngineContext.java b/core/src/main/java/com/alibaba/nacos/core/context/addition/EngineContext.java new file mode 100644 index 00000000000..d46f77938f5 --- /dev/null +++ b/core/src/main/java/com/alibaba/nacos/core/context/addition/EngineContext.java @@ -0,0 +1,62 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.context.addition; + +import com.alibaba.nacos.common.utils.VersionUtils; + +import java.util.HashMap; +import java.util.Map; + +/** + * Nacos engine context, to store some environment and engine information context. Such as version or system information. + * + * @author xiweng.yy + */ +public class EngineContext { + + /** + * Nacos server version, such as v2.4.0. + */ + private String version; + + private final Map contexts; + + public EngineContext() { + version = VersionUtils.version; + contexts = new HashMap<>(1); + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getContext(String key) { + return contexts.get(key); + } + + public String getContext(String key, String defaultValue) { + return contexts.getOrDefault(key, defaultValue); + } + + public void setContext(String key, String value) { + contexts.put(key, value); + } +} diff --git a/core/src/main/java/com/alibaba/nacos/core/context/remote/HttpRequestContextConfig.java b/core/src/main/java/com/alibaba/nacos/core/context/remote/HttpRequestContextConfig.java new file mode 100644 index 00000000000..2ffd05f71f7 --- /dev/null +++ b/core/src/main/java/com/alibaba/nacos/core/context/remote/HttpRequestContextConfig.java @@ -0,0 +1,46 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.context.remote; + +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * Spring Configuration for request context of HTTP. + * + * @author xiweng.yy + */ +@Configuration +public class HttpRequestContextConfig { + + @Bean + public FilterRegistrationBean requestContextFilterRegistration( + HttpRequestContextFilter requestContextFilter) { + FilterRegistrationBean registration = new FilterRegistrationBean<>(); + registration.setFilter(requestContextFilter); + registration.addUrlPatterns("/*"); + registration.setName("nacosRequestContextFilter"); + registration.setOrder(Integer.MIN_VALUE); + return registration; + } + + @Bean + public HttpRequestContextFilter nacosRequestContextFilter() { + return new HttpRequestContextFilter(); + } +} diff --git a/core/src/main/java/com/alibaba/nacos/core/context/remote/HttpRequestContextFilter.java b/core/src/main/java/com/alibaba/nacos/core/context/remote/HttpRequestContextFilter.java new file mode 100644 index 00000000000..c6b325e2b49 --- /dev/null +++ b/core/src/main/java/com/alibaba/nacos/core/context/remote/HttpRequestContextFilter.java @@ -0,0 +1,103 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.context.remote; + +import com.alibaba.nacos.common.constant.HttpHeaderConsts; +import com.alibaba.nacos.common.utils.StringUtils; +import com.alibaba.nacos.core.context.RequestContext; +import com.alibaba.nacos.core.context.RequestContextHolder; +import com.alibaba.nacos.core.context.addition.BasicContext; +import com.alibaba.nacos.core.utils.WebUtils; +import org.apache.http.HttpHeaders; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; + +import static com.alibaba.nacos.api.common.Constants.CLIENT_APPNAME_HEADER; + +/** + * The Filter to add request context for HTTP protocol. + * + * @author xiweng.yy + */ +public class HttpRequestContextFilter implements Filter { + + private static final String PATTERN_REQUEST_TARGET = "%s %s"; + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) + throws IOException, ServletException { + RequestContext requestContext = RequestContextHolder.getContext(); + try { + requestContext.getBasicContext().setRequestProtocol(BasicContext.HTTP_PROTOCOL); + HttpServletRequest request = (HttpServletRequest) servletRequest; + setRequestTarget(request, requestContext); + setEncoding(request, requestContext); + setAddressContext(request, requestContext); + setOtherBasicContext(request, requestContext); + filterChain.doFilter(servletRequest, servletResponse); + } finally { + RequestContextHolder.removeContext(); + } + } + + private void setRequestTarget(HttpServletRequest request, RequestContext requestContext) { + String uri = request.getRequestURI(); + String method = request.getMethod(); + requestContext.getBasicContext().setRequestTarget(String.format(PATTERN_REQUEST_TARGET, method, uri)); + } + + private void setEncoding(HttpServletRequest request, RequestContext requestContext) { + String encoding = request.getCharacterEncoding(); + if (StringUtils.isNotBlank(encoding)) { + requestContext.getBasicContext().setEncoding(encoding); + } + } + + private void setAddressContext(HttpServletRequest request, RequestContext requestContext) { + String remoteAddress = request.getRemoteAddr(); + int remotePort = request.getRemotePort(); + String sourceIp = WebUtils.getRemoteIp(request); + String host = request.getHeader(HttpHeaders.HOST); + requestContext.getBasicContext().getAddressContext().setRemoteIp(remoteAddress); + requestContext.getBasicContext().getAddressContext().setRemotePort(remotePort); + requestContext.getBasicContext().getAddressContext().setSourceIp(sourceIp); + requestContext.getBasicContext().getAddressContext().setHost(host); + } + + private void setOtherBasicContext(HttpServletRequest request, RequestContext requestContext) { + String userAgent = WebUtils.getUserAgent(request); + requestContext.getBasicContext().setUserAgent(userAgent); + String app = getAppName(request); + if (StringUtils.isNotBlank(app)) { + requestContext.getBasicContext().setApp(app); + } + } + + private String getAppName(HttpServletRequest request) { + String app = request.getHeader(HttpHeaderConsts.APP_FILED); + if (StringUtils.isBlank(app)) { + app = request.getHeader(CLIENT_APPNAME_HEADER); + } + return app; + } +} diff --git a/core/src/main/java/com/alibaba/nacos/core/persistence/DistributedDatabaseOperateImpl.java b/core/src/main/java/com/alibaba/nacos/core/persistence/DistributedDatabaseOperateImpl.java index 88d4df56487..f16558f187c 100644 --- a/core/src/main/java/com/alibaba/nacos/core/persistence/DistributedDatabaseOperateImpl.java +++ b/core/src/main/java/com/alibaba/nacos/core/persistence/DistributedDatabaseOperateImpl.java @@ -56,6 +56,8 @@ import com.alibaba.nacos.persistence.repository.embedded.sql.ModifyRequest; import com.alibaba.nacos.persistence.repository.embedded.sql.QueryType; import com.alibaba.nacos.persistence.repository.embedded.sql.SelectRequest; +import com.alibaba.nacos.persistence.repository.embedded.sql.limiter.SqlLimiter; +import com.alibaba.nacos.persistence.repository.embedded.sql.limiter.SqlTypeLimiter; import com.alibaba.nacos.persistence.utils.PersistenceExecutor; import com.alibaba.nacos.sys.utils.DiskUtils; import com.google.protobuf.ByteString; @@ -171,11 +173,14 @@ public class DistributedDatabaseOperateImpl extends RequestProcessor4CP implemen private final ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock(); + private final SqlLimiter sqlLimiter; + public DistributedDatabaseOperateImpl(ServerMemberManager memberManager, ProtocolManager protocolManager) throws Exception { this.memberManager = memberManager; this.protocol = protocolManager.getCpProtocol(); init(); + this.sqlLimiter = new SqlTypeLimiter(); } protected void init() throws Exception { @@ -471,6 +476,7 @@ public Response onRequest(final ReadRequest request) { try { selectRequest = serializer.deserialize(request.getData().toByteArray(), SelectRequest.class); LoggerUtils.printIfDebugEnabled(LOGGER, "getData info : selectRequest : {}", selectRequest); + sqlLimiter.doLimitForSelectRequest(selectRequest); final RowMapper mapper = RowMapperManager.getRowMapper(selectRequest.getClassName()); final byte type = selectRequest.getQueryType(); switch (type) { @@ -518,6 +524,7 @@ public Response onApply(WriteRequest log) { lock.lock(); try { List sqlContext = serializer.deserialize(byteString.toByteArray(), List.class); + sqlLimiter.doLimitForModifyRequest(sqlContext); boolean isOk = false; if (log.containsExtendInfo(DATA_IMPORT_KEY)) { isOk = doDataImport(jdbcTemplate, sqlContext); diff --git a/core/src/main/java/com/alibaba/nacos/core/remote/BaseRpcServer.java b/core/src/main/java/com/alibaba/nacos/core/remote/BaseRpcServer.java index 3b5fe849a8f..3ec0fe28674 100644 --- a/core/src/main/java/com/alibaba/nacos/core/remote/BaseRpcServer.java +++ b/core/src/main/java/com/alibaba/nacos/core/remote/BaseRpcServer.java @@ -47,8 +47,12 @@ public void start() throws Exception { startServer(); - if (RpcServerSslContextRefresherHolder.getInstance() != null) { - RpcServerSslContextRefresherHolder.getInstance().refresh(this); + if (RpcServerSslContextRefresherHolder.getSdkInstance() != null) { + RpcServerSslContextRefresherHolder.getSdkInstance().refresh(this); + } + + if (RpcServerSslContextRefresherHolder.getClusterInstance() != null) { + RpcServerSslContextRefresherHolder.getClusterInstance().refresh(this); } Loggers.REMOTE.info("Nacos {} Rpc server started at port {}", serverName, getServicePort()); @@ -75,8 +79,8 @@ public void start() throws Exception { * Reload protocol context if necessary. * *

    - * protocol like: - *

  • Tls
  • + * protocol like: + *
  • Tls
  • *

    */ public abstract void reloadProtocolContext(); diff --git a/core/src/main/java/com/alibaba/nacos/core/remote/ConnectionMeta.java b/core/src/main/java/com/alibaba/nacos/core/remote/ConnectionMeta.java index 51e43f65564..4f29105faa4 100644 --- a/core/src/main/java/com/alibaba/nacos/core/remote/ConnectionMeta.java +++ b/core/src/main/java/com/alibaba/nacos/core/remote/ConnectionMeta.java @@ -197,6 +197,24 @@ public void setClientIp(String clientIp) { this.clientIp = clientIp; } + /** + * Getter method for property remoteIp. + * + * @return property value of remoteIp + */ + public String getRemoteIp() { + return remoteIp; + } + + /** + * Getter method for property remotePort. + * + * @return property value of remotePort + */ + public int getRemotePort() { + return remotePort; + } + /** * Getter method for property connectionId. * diff --git a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/BaseGrpcServer.java b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/BaseGrpcServer.java index 5749a52d8cb..837924191ea 100644 --- a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/BaseGrpcServer.java +++ b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/BaseGrpcServer.java @@ -20,6 +20,7 @@ import com.alibaba.nacos.common.remote.ConnectionType; import com.alibaba.nacos.core.remote.BaseRpcServer; import com.alibaba.nacos.core.remote.ConnectionManager; +import com.alibaba.nacos.core.remote.grpc.negotiator.NacosGrpcProtocolNegotiator; import com.alibaba.nacos.core.utils.Loggers; import com.alibaba.nacos.sys.env.EnvUtil; import io.grpc.CompressorRegistry; @@ -53,6 +54,11 @@ */ public abstract class BaseGrpcServer extends BaseRpcServer { + /** + * The ProtocolNegotiator instance used for communication. + */ + protected NacosGrpcProtocolNegotiator protocolNegotiator; + private Server server; @Autowired @@ -115,6 +121,15 @@ protected Optional newProtocolNeg * reload protocol negotiator If necessary. */ public void reloadProtocolNegotiator() { + if (protocolNegotiator != null) { + try { + protocolNegotiator.reloadNegotiator(); + } catch (Throwable throwable) { + Loggers.REMOTE.info("Nacos {} Rpc server reload negotiator fail at port {}.", + this.getClass().getSimpleName(), getServicePort()); + throw throwable; + } + } } protected long getPermitKeepAliveTime() { @@ -130,8 +145,8 @@ protected long getKeepAliveTimeout() { } protected int getMaxInboundMessageSize() { - Integer property = EnvUtil - .getProperty(GrpcServerConstants.GrpcConfig.MAX_INBOUND_MSG_SIZE_PROPERTY, Integer.class); + Integer property = EnvUtil.getProperty(GrpcServerConstants.GrpcConfig.MAX_INBOUND_MSG_SIZE_PROPERTY, + Integer.class); if (property != null) { return property; } @@ -152,8 +167,8 @@ private void addServices(MutableHandlerRegistry handlerRegistry, ServerIntercept // unary common call register. final MethodDescriptor unaryPayloadMethod = MethodDescriptor.newBuilder() - .setType(MethodDescriptor.MethodType.UNARY).setFullMethodName(MethodDescriptor - .generateFullMethodName(GrpcServerConstants.REQUEST_SERVICE_NAME, + .setType(MethodDescriptor.MethodType.UNARY).setFullMethodName( + MethodDescriptor.generateFullMethodName(GrpcServerConstants.REQUEST_SERVICE_NAME, GrpcServerConstants.REQUEST_METHOD_NAME)) .setRequestMarshaller(ProtoUtils.marshaller(Payload.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Payload.getDefaultInstance())).build(); @@ -161,9 +176,8 @@ private void addServices(MutableHandlerRegistry handlerRegistry, ServerIntercept final ServerCallHandler payloadHandler = ServerCalls.asyncUnaryCall( (request, responseObserver) -> grpcCommonRequestAcceptor.request(request, responseObserver)); - final ServerServiceDefinition serviceDefOfUnaryPayload = ServerServiceDefinition - .builder(GrpcServerConstants.REQUEST_SERVICE_NAME).addMethod(unaryPayloadMethod, payloadHandler) - .build(); + final ServerServiceDefinition serviceDefOfUnaryPayload = ServerServiceDefinition.builder( + GrpcServerConstants.REQUEST_SERVICE_NAME).addMethod(unaryPayloadMethod, payloadHandler).build(); handlerRegistry.addService(ServerInterceptors.intercept(serviceDefOfUnaryPayload, serverInterceptor)); // bi stream register. @@ -171,15 +185,14 @@ private void addServices(MutableHandlerRegistry handlerRegistry, ServerIntercept (responseObserver) -> grpcBiStreamRequestAcceptor.requestBiStream(responseObserver)); final MethodDescriptor biStreamMethod = MethodDescriptor.newBuilder() - .setType(MethodDescriptor.MethodType.BIDI_STREAMING).setFullMethodName(MethodDescriptor - .generateFullMethodName(GrpcServerConstants.REQUEST_BI_STREAM_SERVICE_NAME, + .setType(MethodDescriptor.MethodType.BIDI_STREAMING).setFullMethodName( + MethodDescriptor.generateFullMethodName(GrpcServerConstants.REQUEST_BI_STREAM_SERVICE_NAME, GrpcServerConstants.REQUEST_BI_STREAM_METHOD_NAME)) .setRequestMarshaller(ProtoUtils.marshaller(Payload.newBuilder().build())) .setResponseMarshaller(ProtoUtils.marshaller(Payload.getDefaultInstance())).build(); - final ServerServiceDefinition serviceDefOfBiStream = ServerServiceDefinition - .builder(GrpcServerConstants.REQUEST_BI_STREAM_SERVICE_NAME).addMethod(biStreamMethod, biStreamHandler) - .build(); + final ServerServiceDefinition serviceDefOfBiStream = ServerServiceDefinition.builder( + GrpcServerConstants.REQUEST_BI_STREAM_SERVICE_NAME).addMethod(biStreamMethod, biStreamHandler).build(); handlerRegistry.addService(ServerInterceptors.intercept(serviceDefOfBiStream, serverInterceptor)); } diff --git a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcClusterServer.java b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcClusterServer.java index f37c4c46b37..df50375a61a 100644 --- a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcClusterServer.java +++ b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcClusterServer.java @@ -21,15 +21,18 @@ import com.alibaba.nacos.core.remote.grpc.filter.NacosGrpcServerTransportFilterServiceLoader; import com.alibaba.nacos.core.remote.grpc.interceptor.NacosGrpcServerInterceptor; import com.alibaba.nacos.core.remote.grpc.interceptor.NacosGrpcServerInterceptorServiceLoader; +import com.alibaba.nacos.core.remote.grpc.negotiator.ClusterProtocolNegotiatorBuilderSingleton; import com.alibaba.nacos.core.utils.GlobalExecutor; import com.alibaba.nacos.core.utils.Loggers; import com.alibaba.nacos.sys.env.EnvUtil; import io.grpc.ServerInterceptor; import io.grpc.ServerTransportFilter; +import io.grpc.netty.shaded.io.grpc.netty.InternalProtocolNegotiator; import org.springframework.stereotype.Service; import java.util.LinkedList; import java.util.List; +import java.util.Optional; import java.util.concurrent.ThreadPoolExecutor; /** @@ -56,8 +59,8 @@ public ThreadPoolExecutor getRpcExecutor() { @Override protected long getKeepAliveTime() { - Long property = EnvUtil - .getProperty(GrpcServerConstants.GrpcConfig.CLUSTER_KEEP_ALIVE_TIME_PROPERTY, Long.class); + Long property = EnvUtil.getProperty(GrpcServerConstants.GrpcConfig.CLUSTER_KEEP_ALIVE_TIME_PROPERTY, + Long.class); if (property != null) { return property; } @@ -66,14 +69,20 @@ protected long getKeepAliveTime() { @Override protected long getKeepAliveTimeout() { - Long property = EnvUtil - .getProperty(GrpcServerConstants.GrpcConfig.CLUSTER_KEEP_ALIVE_TIMEOUT_PROPERTY, Long.class); + Long property = EnvUtil.getProperty(GrpcServerConstants.GrpcConfig.CLUSTER_KEEP_ALIVE_TIMEOUT_PROPERTY, + Long.class); if (property != null) { return property; } return super.getKeepAliveTimeout(); } + @Override + protected Optional newProtocolNegotiator() { + protocolNegotiator = ClusterProtocolNegotiatorBuilderSingleton.getSingleton().build(); + return Optional.ofNullable(protocolNegotiator); + } + @Override protected long getPermitKeepAliveTime() { Long property = EnvUtil.getProperty(GrpcServerConstants.GrpcConfig.CLUSTER_PERMIT_KEEP_ALIVE_TIME, Long.class); @@ -85,8 +94,8 @@ protected long getPermitKeepAliveTime() { @Override protected int getMaxInboundMessageSize() { - Integer property = EnvUtil - .getProperty(GrpcServerConstants.GrpcConfig.CLUSTER_MAX_INBOUND_MSG_SIZE_PROPERTY, Integer.class); + Integer property = EnvUtil.getProperty(GrpcServerConstants.GrpcConfig.CLUSTER_MAX_INBOUND_MSG_SIZE_PROPERTY, + Integer.class); if (property != null) { return property; } @@ -104,8 +113,8 @@ protected int getMaxInboundMessageSize() { protected List getSeverInterceptors() { List result = new LinkedList<>(); result.addAll(super.getSeverInterceptors()); - result.addAll(NacosGrpcServerInterceptorServiceLoader - .loadServerInterceptors(NacosGrpcServerInterceptor.CLUSTER_INTERCEPTOR)); + result.addAll(NacosGrpcServerInterceptorServiceLoader.loadServerInterceptors( + NacosGrpcServerInterceptor.CLUSTER_INTERCEPTOR)); return result; } @@ -113,8 +122,8 @@ protected List getSeverInterceptors() { protected List getServerTransportFilters() { List result = new LinkedList<>(); result.addAll(super.getServerTransportFilters()); - result.addAll(NacosGrpcServerTransportFilterServiceLoader - .loadServerTransportFilters(NacosGrpcServerTransportFilter.CLUSTER_FILTER)); + result.addAll(NacosGrpcServerTransportFilterServiceLoader.loadServerTransportFilters( + NacosGrpcServerTransportFilter.CLUSTER_FILTER)); return result; } } diff --git a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcRequestAcceptor.java b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcRequestAcceptor.java index f1283c0a417..626098b967d 100644 --- a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcRequestAcceptor.java +++ b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcRequestAcceptor.java @@ -27,7 +27,12 @@ import com.alibaba.nacos.api.remote.response.Response; import com.alibaba.nacos.api.remote.response.ResponseCode; import com.alibaba.nacos.api.remote.response.ServerCheckResponse; +import com.alibaba.nacos.common.constant.HttpHeaderConsts; import com.alibaba.nacos.common.remote.client.grpc.GrpcUtils; +import com.alibaba.nacos.common.utils.StringUtils; +import com.alibaba.nacos.core.context.RequestContext; +import com.alibaba.nacos.core.context.RequestContextHolder; +import com.alibaba.nacos.core.context.addition.BasicContext; import com.alibaba.nacos.core.monitor.MetricsMonitor; import com.alibaba.nacos.core.remote.Connection; import com.alibaba.nacos.core.remote.ConnectionManager; @@ -186,6 +191,7 @@ public void request(Payload grpcRequest, StreamObserver responseObserve requestMeta.setLabels(connection.getMetaInfo().getLabels()); requestMeta.setAbilityTable(connection.getAbilityTable()); connectionManager.refreshActiveTime(requestMeta.getConnectionId()); + prepareRequestContext(request, requestMeta, connection); Response response = requestHandler.handleRequest(request, requestMeta); Payload payloadResponse = GrpcUtils.convert(response); traceIfNecessary(payloadResponse, false); @@ -212,8 +218,26 @@ public void request(Payload grpcRequest, StreamObserver responseObserve responseObserver.onCompleted(); MetricsMonitor.recordGrpcRequestEvent(type, false, ResponseCode.FAIL.getCode(), e.getClass().getSimpleName(), request.getModule(), System.nanoTime() - startTime); + } finally { + RequestContextHolder.removeContext(); } } + private void prepareRequestContext(Request request, RequestMeta requestMeta, Connection connection) { + RequestContext requestContext = RequestContextHolder.getContext(); + requestContext.setRequestId(request.getRequestId()); + requestContext.getBasicContext().setUserAgent(requestMeta.getClientVersion()); + requestContext.getBasicContext().setRequestProtocol(BasicContext.GRPC_PROTOCOL); + requestContext.getBasicContext().setRequestTarget(request.getClass().getSimpleName()); + String app = connection.getMetaInfo().getAppName(); + if (StringUtils.isBlank(app)) { + app = request.getHeader(HttpHeaderConsts.APP_FILED, "unknown"); + } + requestContext.getBasicContext().setApp(app); + requestContext.getBasicContext().getAddressContext().setRemoteIp(connection.getMetaInfo().getRemoteIp()); + requestContext.getBasicContext().getAddressContext().setRemotePort(connection.getMetaInfo().getRemotePort()); + requestContext.getBasicContext().getAddressContext().setSourceIp(connection.getMetaInfo().getClientIp()); + } + } \ No newline at end of file diff --git a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcSdkServer.java b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcSdkServer.java index 6e9e58fb8ab..b99364e4c87 100644 --- a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcSdkServer.java +++ b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/GrpcSdkServer.java @@ -21,8 +21,7 @@ import com.alibaba.nacos.core.remote.grpc.filter.NacosGrpcServerTransportFilterServiceLoader; import com.alibaba.nacos.core.remote.grpc.interceptor.NacosGrpcServerInterceptor; import com.alibaba.nacos.core.remote.grpc.interceptor.NacosGrpcServerInterceptorServiceLoader; -import com.alibaba.nacos.core.remote.grpc.negotiator.NacosGrpcProtocolNegotiator; -import com.alibaba.nacos.core.remote.grpc.negotiator.ProtocolNegotiatorBuilderSingleton; +import com.alibaba.nacos.core.remote.grpc.negotiator.SdkProtocolNegotiatorBuilderSingleton; import com.alibaba.nacos.core.utils.GlobalExecutor; import com.alibaba.nacos.core.utils.Loggers; import com.alibaba.nacos.sys.env.EnvUtil; @@ -45,8 +44,6 @@ @Service public class GrpcSdkServer extends BaseGrpcServer { - private NacosGrpcProtocolNegotiator protocolNegotiator; - @Override public int rpcPortOffset() { return Constants.SDK_GRPC_PORT_DEFAULT_OFFSET; @@ -78,8 +75,8 @@ protected long getKeepAliveTimeout() { @Override protected int getMaxInboundMessageSize() { - Integer property = EnvUtil - .getProperty(GrpcServerConstants.GrpcConfig.SDK_MAX_INBOUND_MSG_SIZE_PROPERTY, Integer.class); + Integer property = EnvUtil.getProperty(GrpcServerConstants.GrpcConfig.SDK_MAX_INBOUND_MSG_SIZE_PROPERTY, + Integer.class); if (property != null) { return property; } @@ -106,7 +103,7 @@ protected long getPermitKeepAliveTime() { @Override protected Optional newProtocolNegotiator() { - protocolNegotiator = ProtocolNegotiatorBuilderSingleton.getSingleton().build(); + protocolNegotiator = SdkProtocolNegotiatorBuilderSingleton.getSingleton().build(); return Optional.ofNullable(protocolNegotiator); } @@ -114,8 +111,8 @@ protected Optional newProtocolNeg protected List getSeverInterceptors() { List result = new LinkedList<>(); result.addAll(super.getSeverInterceptors()); - result.addAll(NacosGrpcServerInterceptorServiceLoader - .loadServerInterceptors(NacosGrpcServerInterceptor.SDK_INTERCEPTOR)); + result.addAll(NacosGrpcServerInterceptorServiceLoader.loadServerInterceptors( + NacosGrpcServerInterceptor.SDK_INTERCEPTOR)); return result; } @@ -123,24 +120,9 @@ protected List getSeverInterceptors() { protected List getServerTransportFilters() { List result = new LinkedList<>(); result.addAll(super.getServerTransportFilters()); - result.addAll(NacosGrpcServerTransportFilterServiceLoader - .loadServerTransportFilters(NacosGrpcServerTransportFilter.SDK_FILTER)); + result.addAll(NacosGrpcServerTransportFilterServiceLoader.loadServerTransportFilters( + NacosGrpcServerTransportFilter.SDK_FILTER)); return result; } - /** - * reload ssl context. - */ - public void reloadProtocolNegotiator() { - if (protocolNegotiator != null) { - try { - protocolNegotiator.reloadNegotiator(); - } catch (Throwable throwable) { - Loggers.REMOTE - .info("Nacos {} Rpc server reload negotiator fail at port {}.", this.getClass().getSimpleName(), - getServicePort()); - throw throwable; - } - } - } } diff --git a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/AbstractProtocolNegotiatorBuilderSingleton.java b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/AbstractProtocolNegotiatorBuilderSingleton.java new file mode 100644 index 00000000000..d8a5413cb76 --- /dev/null +++ b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/AbstractProtocolNegotiatorBuilderSingleton.java @@ -0,0 +1,96 @@ +/* + * Copyright 1999-2020 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.remote.grpc.negotiator; + +import com.alibaba.nacos.common.spi.NacosServiceLoader; +import com.alibaba.nacos.common.utils.Pair; +import com.alibaba.nacos.core.utils.Loggers; +import com.alibaba.nacos.sys.env.EnvUtil; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Abstract base class for ProtocolNegotiatorBuilder singletons. This class provides a common implementation for + * building ProtocolNegotiator instances based on a given type. Subclasses should provide implementations for loading + * ProtocolNegotiatorBuilder instances via SPI and defining default builders. + * + * @author stone-98 + * @date 2024/2/21 + */ +public abstract class AbstractProtocolNegotiatorBuilderSingleton implements ProtocolNegotiatorBuilder { + + /** + * Map to store ProtocolNegotiatorBuilders based on their types. + */ + protected static final Map BUILDER_MAP = new ConcurrentHashMap<>(); + + static { + try { + for (ProtocolNegotiatorBuilder each : NacosServiceLoader.load(ProtocolNegotiatorBuilder.class)) { + BUILDER_MAP.put(each.type(), each); + Loggers.REMOTE.info("Load ProtocolNegotiatorBuilder {} for type {}", each.getClass().getCanonicalName(), + each.type()); + } + } catch (Exception e) { + Loggers.REMOTE.warn("Load ProtocolNegotiatorBuilder failed.", e); + } + } + + /** + * The property key to retrieve the actual type of ProtocolNegotiatorBuilder. + */ + protected final String typePropertyKey; + + /** + * The actual type of ProtocolNegotiatorBuilder, retrieved from system properties. + */ + protected String actualType; + + /** + * Constructs an instance of AbstractProtocolNegotiatorBuilderSingleton with the specified type property key. + * + * @param typePropertyKey the property key to retrieve the actual type + */ + public AbstractProtocolNegotiatorBuilderSingleton(String typePropertyKey) { + this.typePropertyKey = typePropertyKey; + this.actualType = EnvUtil.getProperty(typePropertyKey, defaultBuilderPair().getFirst()); + } + + /** + * Builds a ProtocolNegotiator instance based on the actual type. + * + * @return a ProtocolNegotiator instance + */ + @Override + public NacosGrpcProtocolNegotiator build() { + ProtocolNegotiatorBuilder actualBuilder = BUILDER_MAP.get(actualType); + if (null == actualBuilder) { + Loggers.REMOTE.warn("Not found ProtocolNegotiatorBuilder for type {}, will use default type {}", actualType, + defaultBuilderPair().getFirst()); + return defaultBuilderPair().getSecond().build(); + } + return actualBuilder.build(); + } + + /** + * Declare default ProtocolNegotiatorBuilders in case loading from SPI fails. + * + * @return a Pair of String and ProtocolNegotiatorBuilder representing the default builder + */ + protected abstract Pair defaultBuilderPair(); +} diff --git a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/ClusterProtocolNegotiatorBuilderSingleton.java b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/ClusterProtocolNegotiatorBuilderSingleton.java new file mode 100644 index 00000000000..d790a84558c --- /dev/null +++ b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/ClusterProtocolNegotiatorBuilderSingleton.java @@ -0,0 +1,81 @@ +/* + * Copyright 1999-2020 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.remote.grpc.negotiator; + +import com.alibaba.nacos.common.utils.Pair; +import com.alibaba.nacos.core.remote.grpc.negotiator.tls.ClusterDefaultTlsProtocolNegotiatorBuilder; + +/** + * Manages ProtocolNegotiatorBuilders for cluster communication. Provides a singleton instance of + * ProtocolNegotiatorBuilder configured for this purpose. Defaults to TLS protocol negotiation but can be overridden via + * system properties. + * + * + *

    Property key for configuring the ProtocolNegotiator type for cluster communication. + * + * @author stone-98 + * @date 2024/2/21 + */ +public class ClusterProtocolNegotiatorBuilderSingleton extends AbstractProtocolNegotiatorBuilderSingleton { + + /** + * Property key for configuring the ProtocolNegotiator type for cluster communication. + */ + public static final String TYPE_PROPERTY_KEY = "nacos.remote.cluster.server.rpc.protocol.negotiator.type"; + + /** + * Singleton instance of ClusterProtocolNegotiatorBuilderSingleton. + */ + private static final ClusterProtocolNegotiatorBuilderSingleton SINGLETON = new ClusterProtocolNegotiatorBuilderSingleton(); + + /** + * Constructs a new instance of ClusterProtocolNegotiatorBuilderSingleton. Sets up the type property key for + * ProtocolNegotiatorBuilder. + */ + public ClusterProtocolNegotiatorBuilderSingleton() { + super(TYPE_PROPERTY_KEY); + } + + /** + * Retrieves the singleton instance of ClusterProtocolNegotiatorBuilderSingleton. + * + * @return the singleton instance + */ + public static AbstractProtocolNegotiatorBuilderSingleton getSingleton() { + return SINGLETON; + } + + /** + * Provides the default ProtocolNegotiatorBuilder pair. + * + * @return a Pair containing the default type and builder instance + */ + @Override + protected Pair defaultBuilderPair() { + return Pair.with(TYPE_PROPERTY_KEY, new ClusterDefaultTlsProtocolNegotiatorBuilder()); + } + + /** + * Retrieves the type of ProtocolNegotiatorBuilder configured for cluster communication. + * + * @return the type of ProtocolNegotiatorBuilder + */ + @Override + public String type() { + return super.actualType; + } +} diff --git a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/ProtocolNegotiatorBuilderSingleton.java b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/ProtocolNegotiatorBuilderSingleton.java deleted file mode 100644 index 9d30d3676ca..00000000000 --- a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/ProtocolNegotiatorBuilderSingleton.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 1999-2023 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.core.remote.grpc.negotiator; - -import com.alibaba.nacos.common.spi.NacosServiceLoader; -import com.alibaba.nacos.core.remote.grpc.negotiator.tls.DefaultTlsProtocolNegotiatorBuilder; -import com.alibaba.nacos.core.utils.Loggers; -import com.alibaba.nacos.sys.env.EnvUtil; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import static com.alibaba.nacos.core.remote.grpc.negotiator.tls.DefaultTlsProtocolNegotiatorBuilder.TYPE_DEFAULT_TLS; - -/** - * Protocol Negotiator Builder Singleton. - * - * @author xiweng.yy - */ -public class ProtocolNegotiatorBuilderSingleton implements ProtocolNegotiatorBuilder { - - private static final String TYPE_PROPERTY_KEY = "nacos.remote.server.rpc.protocol.negotiator.type"; - - private static final ProtocolNegotiatorBuilderSingleton SINGLETON = new ProtocolNegotiatorBuilderSingleton(); - - private final Map builderMap; - - private String actualType; - - private ProtocolNegotiatorBuilderSingleton() { - actualType = EnvUtil.getProperty(TYPE_PROPERTY_KEY, TYPE_DEFAULT_TLS); - builderMap = new ConcurrentHashMap<>(); - loadAllBuilders(); - } - - private void loadAllBuilders() { - try { - for (ProtocolNegotiatorBuilder each : NacosServiceLoader.load(ProtocolNegotiatorBuilder.class)) { - builderMap.put(each.type(), each); - Loggers.REMOTE.info("Load ProtocolNegotiatorBuilder {} for type {}", each.getClass().getCanonicalName(), - each.type()); - } - } catch (Exception e) { - Loggers.REMOTE.warn("Load ProtocolNegotiatorBuilder failed, use default ProtocolNegotiatorBuilder", e); - builderMap.put(TYPE_DEFAULT_TLS, new DefaultTlsProtocolNegotiatorBuilder()); - actualType = TYPE_DEFAULT_TLS; - } - } - - public static ProtocolNegotiatorBuilderSingleton getSingleton() { - return SINGLETON; - } - - @Override - public NacosGrpcProtocolNegotiator build() { - ProtocolNegotiatorBuilder actualBuilder = builderMap.get(actualType); - if (null == actualBuilder) { - Loggers.REMOTE.warn("Not found ProtocolNegotiatorBuilder for type {}, will use default", actualType); - return builderMap.get(TYPE_DEFAULT_TLS).build(); - } - return actualBuilder.build(); - } - - @Override - public String type() { - return actualType; - } -} diff --git a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/SdkProtocolNegotiatorBuilderSingleton.java b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/SdkProtocolNegotiatorBuilderSingleton.java new file mode 100644 index 00000000000..82f150c8c4d --- /dev/null +++ b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/SdkProtocolNegotiatorBuilderSingleton.java @@ -0,0 +1,81 @@ +/* + * Copyright 1999-2020 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.remote.grpc.negotiator; + +import com.alibaba.nacos.common.utils.Pair; +import com.alibaba.nacos.core.remote.grpc.negotiator.tls.SdkDefaultTlsProtocolNegotiatorBuilder; + +/** + * Manages ProtocolNegotiatorBuilders for the interaction between Nacos and SDK. Provides a singleton instance of + * ProtocolNegotiatorBuilder configured for this interaction. Defaults to TLS protocol negotiation but can be overridden + * via system properties. + * + * + *

    Property key for configuring the ProtocolNegotiator type for Nacos and SDK interaction. + * + * @author stone-98 + * @date 2024/2/21 + */ +public class SdkProtocolNegotiatorBuilderSingleton extends AbstractProtocolNegotiatorBuilderSingleton { + + /** + * Property key to retrieve the type of ProtocolNegotiatorBuilder. + */ + public static final String TYPE_PROPERTY_KEY = "nacos.remote.server.rpc.protocol.negotiator.type"; + + /** + * Singleton instance of SdkProtocolNegotiatorBuilderSingleton. + */ + private static final SdkProtocolNegotiatorBuilderSingleton SINGLETON = new SdkProtocolNegotiatorBuilderSingleton(); + + /** + * Constructs a new instance of SdkProtocolNegotiatorBuilderSingleton. Sets up the type property key for + * ProtocolNegotiatorBuilder. + */ + public SdkProtocolNegotiatorBuilderSingleton() { + super(TYPE_PROPERTY_KEY); + } + + /** + * Retrieves the singleton instance of SdkProtocolNegotiatorBuilderSingleton. + * + * @return the singleton instance + */ + public static AbstractProtocolNegotiatorBuilderSingleton getSingleton() { + return SINGLETON; + } + + /** + * Provides the default ProtocolNegotiatorBuilder pair. + * + * @return a Pair containing the default type and builder instance + */ + @Override + protected Pair defaultBuilderPair() { + return Pair.with(TYPE_PROPERTY_KEY, new SdkDefaultTlsProtocolNegotiatorBuilder()); + } + + /** + * Retrieves the type of ProtocolNegotiatorBuilder configured for the SDK. + * + * @return the type of ProtocolNegotiatorBuilder + */ + @Override + public String type() { + return super.actualType; + } +} diff --git a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/ClusterDefaultTlsProtocolNegotiatorBuilder.java b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/ClusterDefaultTlsProtocolNegotiatorBuilder.java new file mode 100644 index 00000000000..d9250f335a5 --- /dev/null +++ b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/ClusterDefaultTlsProtocolNegotiatorBuilder.java @@ -0,0 +1,93 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.remote.grpc.negotiator.tls; + +import com.alibaba.nacos.core.remote.tls.RpcServerTlsConfig; +import com.alibaba.nacos.core.remote.grpc.negotiator.NacosGrpcProtocolNegotiator; +import com.alibaba.nacos.core.remote.grpc.negotiator.ProtocolNegotiatorBuilder; +import com.alibaba.nacos.core.remote.tls.RpcServerTlsConfigFactory; +import com.alibaba.nacos.sys.env.EnvUtil; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContext; + +import java.util.Properties; + +/** + * The {@code ClusterDefaultTlsProtocolNegotiatorBuilder} class is an implementation of the + * {@link ProtocolNegotiatorBuilder} interface for constructing a ProtocolNegotiator specifically for cluster-to-cluster + * communication with TLS encryption. + * + *

    It defines the type as {@code CLUSTER_DEFAULT_TLS} and supports communication types for clusters. + *

    + * + *

    The {@code build()} method constructs and returns a {@link NacosGrpcProtocolNegotiator} instance based on the + * configuration provided by the {@link RpcServerTlsConfig} class. If TLS encryption is enabled, it creates an + * {@link OptionalTlsProtocolNegotiator} with the corresponding SSL context and configuration; otherwise, it returns + * null. + *

    + * + *

    The {@code type()} method returns the unique identifier {@code CLUSTER_TYPE_DEFAULT_TLS} for this negotiator + * builder. + *

    + * + *

    Example Usage: + *

    {@code
    + * ProtocolNegotiatorBuilder builder = new ClusterDefaultTlsProtocolNegotiatorBuilder();
    + * NacosGrpcProtocolNegotiator negotiator = builder.build();
    + * }
    + *

    + * + * @author stone-98 + * @date 2023/12/23 + * @see ProtocolNegotiatorBuilder + * @see NacosGrpcProtocolNegotiator + * @see RpcServerTlsConfig + * @see OptionalTlsProtocolNegotiator + */ +public class ClusterDefaultTlsProtocolNegotiatorBuilder implements ProtocolNegotiatorBuilder { + + /** + * The unique identifier for this negotiator builder. + */ + public static final String CLUSTER_TYPE_DEFAULT_TLS = "CLUSTER_DEFAULT_TLS"; + + /** + * Constructs and returns a ProtocolNegotiator for cluster-to-cluster communication with TLS encryption. + * + * @return ProtocolNegotiator, or null if TLS is not enabled. + */ + @Override + public NacosGrpcProtocolNegotiator build() { + Properties properties = EnvUtil.getProperties(); + RpcServerTlsConfig config = RpcServerTlsConfigFactory.getInstance().createClusterConfig(properties); + if (config.getEnableTls()) { + SslContext sslContext = DefaultTlsContextBuilder.getSslContext(config); + return new OptionalTlsProtocolNegotiator(sslContext, config); + } + return null; + } + + /** + * Returns the unique identifier {@code CLUSTER_TYPE_DEFAULT_TLS} for this negotiator builder. + * + * @return The type identifier. + */ + @Override + public String type() { + return CLUSTER_TYPE_DEFAULT_TLS; + } +} + diff --git a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/DefaultTlsProtocolNegotiatorBuilder.java b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/DefaultTlsProtocolNegotiatorBuilder.java deleted file mode 100644 index aa64cf91d04..00000000000 --- a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/DefaultTlsProtocolNegotiatorBuilder.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 1999-2023 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.core.remote.grpc.negotiator.tls; - -import com.alibaba.nacos.core.remote.grpc.negotiator.NacosGrpcProtocolNegotiator; -import com.alibaba.nacos.core.remote.grpc.negotiator.ProtocolNegotiatorBuilder; -import com.alibaba.nacos.core.remote.tls.RpcServerTlsConfig; -import io.grpc.netty.shaded.io.netty.handler.ssl.SslContext; - -/** - * Default optional tls protocol negotiator builder. - * - * @author xiweng.yy - */ -public class DefaultTlsProtocolNegotiatorBuilder implements ProtocolNegotiatorBuilder { - - public static final String TYPE_DEFAULT_TLS = "DEFAULT_TLS"; - - @Override - public NacosGrpcProtocolNegotiator build() { - RpcServerTlsConfig rpcServerTlsConfig = RpcServerTlsConfig.getInstance(); - if (rpcServerTlsConfig.getEnableTls()) { - SslContext sslContext = DefaultTlsContextBuilder.getSslContext(rpcServerTlsConfig); - return new OptionalTlsProtocolNegotiator(sslContext, rpcServerTlsConfig.getCompatibility()); - } - return null; - } - - @Override - public String type() { - return TYPE_DEFAULT_TLS; - } -} diff --git a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/OptionalTlsProtocolNegotiator.java b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/OptionalTlsProtocolNegotiator.java index c73f51250dc..a41ee4244fb 100644 --- a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/OptionalTlsProtocolNegotiator.java +++ b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/OptionalTlsProtocolNegotiator.java @@ -43,11 +43,14 @@ public class OptionalTlsProtocolNegotiator implements NacosGrpcProtocolNegotiato private final boolean supportPlainText; + private final RpcServerTlsConfig config; + private SslContext sslContext; - public OptionalTlsProtocolNegotiator(SslContext sslContext, boolean supportPlainText) { + public OptionalTlsProtocolNegotiator(SslContext sslContext, RpcServerTlsConfig config) { this.sslContext = sslContext; - this.supportPlainText = supportPlainText; + this.config = config; + this.supportPlainText = config.getCompatibility(); } void setSslContext(SslContext sslContext) { @@ -63,8 +66,7 @@ public AsciiString scheme() { public ChannelHandler newHandler(GrpcHttp2ConnectionHandler grpcHttp2ConnectionHandler) { ChannelHandler plaintext = InternalProtocolNegotiators.serverPlaintext().newHandler(grpcHttp2ConnectionHandler); ChannelHandler ssl = InternalProtocolNegotiators.serverTls(sslContext).newHandler(grpcHttp2ConnectionHandler); - ChannelHandler decoder = new PortUnificationServerHandler(ssl, plaintext); - return decoder; + return new PortUnificationServerHandler(ssl, plaintext); } @Override @@ -74,27 +76,25 @@ public void close() { @Override public void reloadNegotiator() { - RpcServerTlsConfig rpcServerTlsConfig = RpcServerTlsConfig.getInstance(); - if (rpcServerTlsConfig.getEnableTls()) { - sslContext = DefaultTlsContextBuilder.getSslContext(rpcServerTlsConfig); + if (config.getEnableTls()) { + sslContext = DefaultTlsContextBuilder.getSslContext(config); } } private ProtocolNegotiationEvent getDefPne() { - ProtocolNegotiationEvent protocolNegotiationEvent = null; try { Field aDefault = ProtocolNegotiationEvent.class.getDeclaredField("DEFAULT"); aDefault.setAccessible(true); - return (ProtocolNegotiationEvent) aDefault.get(protocolNegotiationEvent); + return (ProtocolNegotiationEvent) aDefault.get(null); } catch (Exception e) { e.printStackTrace(); } - return protocolNegotiationEvent; + return null; } public class PortUnificationServerHandler extends ByteToMessageDecoder { - private ProtocolNegotiationEvent pne; + private final ProtocolNegotiationEvent pne; private final ChannelHandler ssl; @@ -116,14 +116,12 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) t return; } if (isSsl(in) || !supportPlainText) { - ctx.pipeline().addAfter(ctx.name(), (String) null, this.ssl); - ctx.fireUserEventTriggered(pne); - ctx.pipeline().remove(this); + ctx.pipeline().addAfter(ctx.name(), null, this.ssl); } else { - ctx.pipeline().addAfter(ctx.name(), (String) null, this.plaintext); - ctx.fireUserEventTriggered(pne); - ctx.pipeline().remove(this); + ctx.pipeline().addAfter(ctx.name(), null, this.plaintext); } + ctx.fireUserEventTriggered(pne); + ctx.pipeline().remove(this); } } diff --git a/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/SdkDefaultTlsProtocolNegotiatorBuilder.java b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/SdkDefaultTlsProtocolNegotiatorBuilder.java new file mode 100644 index 00000000000..f9bc7303ad5 --- /dev/null +++ b/core/src/main/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/SdkDefaultTlsProtocolNegotiatorBuilder.java @@ -0,0 +1,91 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.remote.grpc.negotiator.tls; + +import com.alibaba.nacos.core.remote.grpc.negotiator.NacosGrpcProtocolNegotiator; +import com.alibaba.nacos.core.remote.grpc.negotiator.ProtocolNegotiatorBuilder; +import com.alibaba.nacos.core.remote.tls.RpcServerTlsConfig; +import com.alibaba.nacos.core.remote.tls.RpcServerTlsConfigFactory; +import com.alibaba.nacos.sys.env.EnvUtil; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContext; + +import java.util.Properties; + +/** + * The {@code SdkDefaultTlsProtocolNegotiatorBuilder} class is an implementation of the + * {@link ProtocolNegotiatorBuilder} interface for constructing a ProtocolNegotiator specifically for SDK-to-Server + * communication with optional TLS encryption. + * + *

    It defines the type as {@code SDK_DEFAULT_TLS} and supports communication types for SDKs. + *

    + * + *

    The {@code build()} method constructs and returns a {@link NacosGrpcProtocolNegotiator} instance based on the + * configuration provided by the {@link RpcServerTlsConfig} class. If TLS encryption is enabled, it creates an + * {@link OptionalTlsProtocolNegotiator} with the corresponding SSL context and configuration; otherwise, it returns + * null. + *

    + * + *

    The {@code type()} method returns the unique identifier {@code SDK_TYPE_DEFAULT_TLS} for this negotiator builder. + *

    + * + *

    Example Usage: + *

    {@code
    + * ProtocolNegotiatorBuilder builder = new SdkDefaultTlsProtocolNegotiatorBuilder();
    + * NacosGrpcProtocolNegotiator negotiator = builder.build();
    + * }
    + *

    + * + * @author xiweng.yy + * @date 2023/12/23 + * @see ProtocolNegotiatorBuilder + * @see NacosGrpcProtocolNegotiator + * @see RpcServerTlsConfig + * @see OptionalTlsProtocolNegotiator + */ +public class SdkDefaultTlsProtocolNegotiatorBuilder implements ProtocolNegotiatorBuilder { + + /** + * The unique identifier for this negotiator builder. + */ + public static final String TYPE_DEFAULT_TLS = "DEFAULT_TLS"; + + /** + * Constructs and returns a ProtocolNegotiator for SDK-to-Server communication with optional TLS encryption. + * + * @return ProtocolNegotiator, or null if TLS is not enabled. + */ + @Override + public NacosGrpcProtocolNegotiator build() { + Properties properties = EnvUtil.getProperties(); + RpcServerTlsConfig config = RpcServerTlsConfigFactory.getInstance().createSdkConfig(properties); + if (config.getEnableTls()) { + SslContext sslContext = DefaultTlsContextBuilder.getSslContext(config); + return new OptionalTlsProtocolNegotiator(sslContext, config); + } + return null; + } + + /** + * Returns the unique identifier {@code SDK_TYPE_DEFAULT_TLS} for this negotiator builder. + * + * @return The type identifier. + */ + @Override + public String type() { + return TYPE_DEFAULT_TLS; + } +} diff --git a/core/src/main/java/com/alibaba/nacos/core/remote/tls/RpcServerSslContextRefresherHolder.java b/core/src/main/java/com/alibaba/nacos/core/remote/tls/RpcServerSslContextRefresherHolder.java index b423442319c..c4b212ac225 100644 --- a/core/src/main/java/com/alibaba/nacos/core/remote/tls/RpcServerSslContextRefresherHolder.java +++ b/core/src/main/java/com/alibaba/nacos/core/remote/tls/RpcServerSslContextRefresherHolder.java @@ -19,56 +19,95 @@ import com.alibaba.nacos.common.spi.NacosServiceLoader; import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.core.utils.Loggers; +import com.alibaba.nacos.sys.env.EnvUtil; import java.util.Collection; +import java.util.Properties; /** - * ssl context refresher spi holder. + * Holder for managing instances of {@link RpcServerSslContextRefresher}. This class is responsible for initializing and + * providing instances of the SSL context refresher based on the communication type (SDK or Cluster). * * @author liuzunfei - * @version $Id: RequestFilters.java, v 0.1 2023年03月17日 12:00 PM liuzunfei Exp $ + * @version $Id: RpcServerSslContextRefresherHolder.java, v 0.1 2023年03月17日 12:00 PM liuzunfei Exp $ */ public class RpcServerSslContextRefresherHolder { - - private static RpcServerSslContextRefresher instance; - - private static volatile boolean init = false; - - public static RpcServerSslContextRefresher getInstance() { - if (init) { - return instance; - } + + /** + * The instance of {@link RpcServerSslContextRefresher} for SDK communication. + */ + private static RpcServerSslContextRefresher sdkInstance; + + /** + * The instance of {@link RpcServerSslContextRefresher} for Cluster communication. + */ + private static RpcServerSslContextRefresher clusterInstance; + + static { + init(); + } + + /** + * Gets the instance of {@link RpcServerSslContextRefresher} for SDK communication. + * + * @return The instance of {@link RpcServerSslContextRefresher} for SDK communication. + */ + public static RpcServerSslContextRefresher getSdkInstance() { + return sdkInstance; + } + + /** + * Gets the instance of {@link RpcServerSslContextRefresher} for Cluster communication. + * + * @return The instance of {@link RpcServerSslContextRefresher} for Cluster communication. + */ + public static RpcServerSslContextRefresher getClusterInstance() { + return clusterInstance; + } + + /** + * Initializes the holder by loading SSL context refreshers and matching them with the configured types (SDK and + * Cluster). + */ + private static void init() { synchronized (RpcServerSslContextRefresherHolder.class) { - if (init) { - return instance; - } - RpcServerTlsConfig rpcServerTlsConfig = RpcServerTlsConfig.getInstance(); - String sslContextRefresher = rpcServerTlsConfig.getSslContextRefresher(); - if (StringUtils.isNotBlank(sslContextRefresher)) { - Collection load = NacosServiceLoader - .load(RpcServerSslContextRefresher.class); - for (RpcServerSslContextRefresher contextRefresher : load) { - if (sslContextRefresher.equals(contextRefresher.getName())) { - instance = contextRefresher; - Loggers.REMOTE.info("RpcServerSslContextRefresher of Name {} Founded->{}", sslContextRefresher, - contextRefresher.getClass().getSimpleName()); - break; - } - } - if (instance == null) { - Loggers.REMOTE.info("RpcServerSslContextRefresher of Name {} not found", sslContextRefresher); + Properties properties = EnvUtil.getProperties(); + RpcServerTlsConfig clusterServerTlsConfig = RpcServerTlsConfigFactory.getInstance().createClusterConfig(properties); + RpcServerTlsConfig sdkServerTlsConfig = RpcServerTlsConfigFactory.getInstance().createSdkConfig(properties); + Collection refreshers = NacosServiceLoader.load( + RpcServerSslContextRefresher.class); + sdkInstance = getSslContextRefresher(refreshers, sdkServerTlsConfig); + clusterInstance = getSslContextRefresher(refreshers, clusterServerTlsConfig); + Loggers.REMOTE.info("RpcServerSslContextRefresher initialization completed."); + } + } + + /** + * Initializes the SSL context refresher instance based on the specified configuration. + * + * @param refreshers Collection of SSL context refreshers to choose from. + * @param serverTlsConfig Configuration instance for the SSL context refresher. + * @return The instance of {@link RpcServerSslContextRefresher}. + */ + private static RpcServerSslContextRefresher getSslContextRefresher( + Collection refreshers, RpcServerTlsConfig serverTlsConfig) { + String refresherName = serverTlsConfig.getSslContextRefresher(); + RpcServerSslContextRefresher instance = null; + if (StringUtils.isNotBlank(refresherName)) { + for (RpcServerSslContextRefresher contextRefresher : refreshers) { + if (refresherName.equals(contextRefresher.getName())) { + instance = contextRefresher; + Loggers.REMOTE.info("RpcServerSslContextRefresher initialized using {}.", + contextRefresher.getClass().getSimpleName()); + break; } - - } else { - Loggers.REMOTE - .info("No RpcServerSslContextRefresher specified,Ssl Context auto refresh not supported."); } - - Loggers.REMOTE.info("RpcServerSslContextRefresher init end"); - init = true; + if (instance == null) { + Loggers.REMOTE.warn("Failed to find RpcServerSslContextRefresher with name {}.", refresherName); + } + } else { + Loggers.REMOTE.info("Ssl Context auto refresh is not supported."); } - return instance; } - } diff --git a/core/src/main/java/com/alibaba/nacos/core/remote/tls/RpcServerTlsConfig.java b/core/src/main/java/com/alibaba/nacos/core/remote/tls/RpcServerTlsConfig.java index e0b0068462e..3cf71ffab41 100644 --- a/core/src/main/java/com/alibaba/nacos/core/remote/tls/RpcServerTlsConfig.java +++ b/core/src/main/java/com/alibaba/nacos/core/remote/tls/RpcServerTlsConfig.java @@ -17,50 +17,57 @@ package com.alibaba.nacos.core.remote.tls; import com.alibaba.nacos.common.remote.TlsConfig; -import com.alibaba.nacos.common.utils.JacksonUtils; -import com.alibaba.nacos.core.utils.Loggers; -import com.alibaba.nacos.sys.env.EnvUtil; -import com.alibaba.nacos.sys.utils.PropertiesUtil; /** - * Grpc config. + * Represents the TLS configuration for an RPC server. + * This class extends TlsConfig to inherit common TLS configuration properties. * * @author githubcheng2978. */ public class RpcServerTlsConfig extends TlsConfig { - - public static final String PREFIX = "nacos.remote.server.rpc.tls"; - - private static RpcServerTlsConfig instance; - + + /** + * The class representing the configuration for SSL context refreshing in the RPC server. + */ private String sslContextRefresher = ""; - + + /** + * Indicates whether compatibility mode is enabled. + */ private Boolean compatibility = true; - - public static synchronized RpcServerTlsConfig getInstance() { - if (null == instance) { - instance = PropertiesUtil.handleSpringBinder(EnvUtil.getEnvironment(), PREFIX, RpcServerTlsConfig.class); - if (instance == null) { - Loggers.REMOTE.debug("TLS configuration is empty, use default value"); - instance = new RpcServerTlsConfig(); - } - } - Loggers.REMOTE.info("Nacos Rpc server tls config:{}", JacksonUtils.toJson(instance)); - return instance; - } - + + /** + * Gets the compatibility mode status. + * + * @return true if compatibility mode is enabled, false otherwise. + */ public Boolean getCompatibility() { return compatibility; } - + + /** + * Sets the compatibility mode status. + * + * @param compatibility true to enable compatibility mode, false otherwise. + */ public void setCompatibility(Boolean compatibility) { this.compatibility = compatibility; } - + + /** + * Gets the SSL context refresher. + * + * @return the SSL context refresher. + */ public String getSslContextRefresher() { return sslContextRefresher; } - + + /** + * Sets the SSL context refresher. + * + * @param sslContextRefresher the SSL context refresher to set. + */ public void setSslContextRefresher(String sslContextRefresher) { this.sslContextRefresher = sslContextRefresher; } diff --git a/core/src/main/java/com/alibaba/nacos/core/remote/tls/RpcServerTlsConfigFactory.java b/core/src/main/java/com/alibaba/nacos/core/remote/tls/RpcServerTlsConfigFactory.java new file mode 100644 index 00000000000..e109d6be27b --- /dev/null +++ b/core/src/main/java/com/alibaba/nacos/core/remote/tls/RpcServerTlsConfigFactory.java @@ -0,0 +1,103 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.remote.tls; + +import com.alibaba.nacos.common.remote.client.RpcTlsConfigFactory; +import com.alibaba.nacos.common.remote.client.RpcConstants; + +import java.util.Properties; + +import static com.alibaba.nacos.common.remote.client.RpcConstants.NACOS_SERVER_RPC; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.COMPATIBILITY; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.MUTUAL_AUTH; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.SSL_CONTEXT_REFRESHER; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.TLS_CERT_CHAIN_PATH; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.TLS_CERT_KEY; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.TLS_CIPHERS; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.TLS_ENABLE; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.TLS_PROTOCOLS; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.TLS_PROVIDER; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.TLS_TRUST_ALL; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.TLS_TRUST_COLLECTION_CHAIN_PATH; +import static com.alibaba.nacos.common.remote.client.RpcConstants.ServerSuffix.TLS_TRUST_PWD; + +/** + * RpcServerTlsConfigFactory. + * + * @author stone-98 + * @date 2024/4/8 + */ +public class RpcServerTlsConfigFactory implements RpcTlsConfigFactory { + + private static RpcServerTlsConfigFactory instance; + + private RpcServerTlsConfigFactory() { + } + + public static synchronized RpcServerTlsConfigFactory getInstance() { + if (instance == null) { + instance = new RpcServerTlsConfigFactory(); + } + return instance; + } + + /** + * Create SDK client TLS config. + * + * @param properties Properties containing TLS configuration + * @return RpcClientTlsConfig object representing the TLS configuration + */ + @Override + public RpcServerTlsConfig createSdkConfig(Properties properties) { + return createServerTlsConfig(properties, NACOS_SERVER_RPC); + } + + /** + * Create cluster client TLS config. + * + * @param properties Properties containing TLS configuration + * @return RpcClientTlsConfig object representing the TLS configuration + */ + @Override + public RpcServerTlsConfig createClusterConfig(Properties properties) { + return createServerTlsConfig(properties, RpcConstants.NACOS_PEER_RPC); + } + + /** + * create sdk server tls config. + * + * @param properties properties + * @param prefix prefix + * @return + */ + public RpcServerTlsConfig createServerTlsConfig(Properties properties, String prefix) { + RpcServerTlsConfig tlsConfig = new RpcServerTlsConfig(); + tlsConfig.setEnableTls(getBooleanProperty(properties, prefix + TLS_ENABLE, false)); + tlsConfig.setMutualAuthEnable(getBooleanProperty(properties, prefix + MUTUAL_AUTH, false)); + tlsConfig.setProtocols(properties.getProperty(prefix + TLS_PROTOCOLS)); + tlsConfig.setCiphers(properties.getProperty(prefix + TLS_CIPHERS)); + tlsConfig.setTrustCollectionCertFile(properties.getProperty(prefix + TLS_TRUST_COLLECTION_CHAIN_PATH)); + tlsConfig.setCertChainFile(properties.getProperty(prefix + TLS_CERT_CHAIN_PATH)); + tlsConfig.setCertPrivateKey(properties.getProperty(prefix + TLS_CERT_KEY)); + tlsConfig.setTrustAll(getBooleanProperty(properties, prefix + TLS_TRUST_ALL, true)); + tlsConfig.setCertPrivateKeyPassword(properties.getProperty(prefix + TLS_TRUST_PWD)); + tlsConfig.setSslProvider(properties.getProperty(prefix + TLS_PROVIDER)); + tlsConfig.setSslContextRefresher(properties.getProperty(prefix + SSL_CONTEXT_REFRESHER)); + tlsConfig.setCompatibility(getBooleanProperty(properties, prefix + COMPATIBILITY, true)); + return tlsConfig; + } +} diff --git a/core/src/main/java/com/alibaba/nacos/core/storage/StorageFactory.java b/core/src/main/java/com/alibaba/nacos/core/storage/StorageFactory.java deleted file mode 100644 index 13fa26a1144..00000000000 --- a/core/src/main/java/com/alibaba/nacos/core/storage/StorageFactory.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.core.storage; - -import com.alibaba.nacos.core.storage.kv.FileKvStorage; -import com.alibaba.nacos.core.storage.kv.KvStorage; -import com.alibaba.nacos.core.storage.kv.MemoryKvStorage; - -/** - * Ket-value Storage factory. - * - * @author liaochuntao - */ -public final class StorageFactory { - - /** - * Create {@link KvStorage} implementation. - * - * @param type type of {@link KvStorage} - * @param label label for {@code RocksStorage} - * @param baseDir base dir of storage file. - * @return implementation of {@link KvStorage} - * @throws Exception exception during creating {@link KvStorage} - */ - public static KvStorage createKvStorage(KvStorage.KvType type, final String label, final String baseDir) - throws Exception { - switch (type) { - case File: - return new FileKvStorage(baseDir); - case Memory: - return new MemoryKvStorage(); - default: - throw new IllegalArgumentException("this kv type : [" + type.name() + "] not support"); - } - } - -} diff --git a/core/src/main/java/com/alibaba/nacos/core/storage/kv/FileKvStorage.java b/core/src/main/java/com/alibaba/nacos/core/storage/kv/FileKvStorage.java deleted file mode 100644 index b730a219d38..00000000000 --- a/core/src/main/java/com/alibaba/nacos/core/storage/kv/FileKvStorage.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.core.storage.kv; - -import com.alibaba.nacos.common.utils.ByteUtils; -import com.alibaba.nacos.core.exception.ErrorCode; -import com.alibaba.nacos.core.exception.KvStorageException; -import com.alibaba.nacos.sys.utils.DiskUtils; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -/** - * Kv storage based on file system. // TODO 写文件的方式需要优化 - * - * @author liaochuntao - */ -public class FileKvStorage implements KvStorage { - - private final String baseDir; - - /** - * Ensure that a consistent view exists when implementing file copies. - */ - private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); - - private final ReentrantReadWriteLock.ReadLock readLock = lock.readLock(); - - private final ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock(); - - public FileKvStorage(String baseDir) throws IOException { - this.baseDir = baseDir; - DiskUtils.forceMkdir(baseDir); - } - - @Override - public byte[] get(byte[] key) throws KvStorageException { - readLock.lock(); - try { - final String fileName = new String(key); - File file = Paths.get(baseDir, fileName).toFile(); - if (file.exists()) { - return DiskUtils.readFileBytes(file); - } - return null; - } finally { - readLock.unlock(); - } - } - - @Override - public Map batchGet(List keys) throws KvStorageException { - readLock.lock(); - try { - Map result = new HashMap<>(keys.size()); - for (byte[] key : keys) { - byte[] val = get(key); - if (val != null) { - result.put(key, val); - } - } - return result; - } finally { - readLock.unlock(); - } - } - - @Override - public void put(byte[] key, byte[] value) throws KvStorageException { - readLock.lock(); - try { - final String fileName = new String(key); - File file = Paths.get(baseDir, fileName).toFile(); - try { - DiskUtils.touch(file); - DiskUtils.writeFile(file, value, false); - } catch (IOException e) { - throw new KvStorageException(ErrorCode.KVStorageWriteError, e); - } - } finally { - readLock.unlock(); - } - } - - @Override - public void batchPut(List keys, List values) throws KvStorageException { - readLock.lock(); - try { - if (keys.size() != values.size()) { - throw new KvStorageException(ErrorCode.KVStorageBatchWriteError, - "key's size must be equal to value's size"); - } - int size = keys.size(); - for (int i = 0; i < size; i++) { - put(keys.get(i), values.get(i)); - } - } finally { - readLock.unlock(); - } - } - - @Override - public void delete(byte[] key) throws KvStorageException { - readLock.lock(); - try { - final String fileName = new String(key); - DiskUtils.deleteFile(baseDir, fileName); - } finally { - readLock.unlock(); - } - } - - @Override - public void batchDelete(List keys) throws KvStorageException { - readLock.lock(); - try { - for (byte[] key : keys) { - delete(key); - } - } finally { - readLock.unlock(); - } - } - - @Override - public void doSnapshot(String backupPath) throws KvStorageException { - writeLock.lock(); - try { - File srcDir = Paths.get(baseDir).toFile(); - File descDir = Paths.get(backupPath).toFile(); - DiskUtils.copyDirectory(srcDir, descDir); - } catch (IOException e) { - throw new KvStorageException(ErrorCode.IOCopyDirError, e); - } finally { - writeLock.unlock(); - } - } - - @Override - public void snapshotLoad(String path) throws KvStorageException { - writeLock.lock(); - try { - File srcDir = Paths.get(path).toFile(); - // If snapshot path is non-exist, means snapshot is empty - if (srcDir.exists()) { - // First clean up the local file information, before the file copy - DiskUtils.deleteDirThenMkdir(baseDir); - File descDir = Paths.get(baseDir).toFile(); - DiskUtils.copyDirectory(srcDir, descDir); - } - } catch (IOException e) { - throw new KvStorageException(ErrorCode.IOCopyDirError, e); - } finally { - writeLock.unlock(); - } - } - - @Override - public List allKeys() throws KvStorageException { - List result = new LinkedList<>(); - File[] files = new File(baseDir).listFiles(); - if (null != files) { - for (File each : files) { - if (each.isFile()) { - result.add(ByteUtils.toBytes(each.getName())); - } - } - } - return result; - } - - @Override - public void shutdown() { - } -} \ No newline at end of file diff --git a/core/src/main/java/com/alibaba/nacos/core/storage/kv/KvStorage.java b/core/src/main/java/com/alibaba/nacos/core/storage/kv/KvStorage.java deleted file mode 100644 index a976daed04b..00000000000 --- a/core/src/main/java/com/alibaba/nacos/core/storage/kv/KvStorage.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.core.storage.kv; - -import com.alibaba.nacos.core.exception.KvStorageException; - -import java.util.List; -import java.util.Map; - -/** - * Universal KV storage interface. - * - * @author liaochuntao - */ -public interface KvStorage { - - enum KvType { - /** - * Local file storage. - */ - File, - - /** - * Local memory storage. - */ - Memory, - - /** - * RocksDB storage. - */ - RocksDB, - } - - - /** - * get data by key. - * - * @param key byte[] - * @return byte[] - * @throws KvStorageException KVStorageException - */ - byte[] get(byte[] key) throws KvStorageException; - - /** - * batch get by List byte[]. - * - * @param keys List byte[] - * @return Map byte[], byte[] - * @throws KvStorageException KvStorageException - */ - Map batchGet(List keys) throws KvStorageException; - - /** - * write data. - * - * @param key byte[] - * @param value byte[] - * @throws KvStorageException KvStorageException - */ - void put(byte[] key, byte[] value) throws KvStorageException; - - /** - * batch write. - * - * @param keys List byte[] - * @param values List byte[] - * @throws KvStorageException KvStorageException - */ - void batchPut(List keys, List values) throws KvStorageException; - - /** - * delete with key. - * - * @param key byte[] - * @throws KvStorageException KvStorageException - */ - void delete(byte[] key) throws KvStorageException; - - /** - * batch delete with keys. - * - * @param keys List byte[] - * @throws KvStorageException KvStorageException - */ - void batchDelete(List keys) throws KvStorageException; - - /** - * do snapshot. - * - * @param backupPath snapshot file save path - * @throws KvStorageException KVStorageException - */ - void doSnapshot(final String backupPath) throws KvStorageException; - - /** - * load snapshot. - * - * @param path The path to the snapshot file - * @throws KvStorageException KVStorageException - */ - void snapshotLoad(String path) throws KvStorageException; - - /** - * Get all keys. - * - * @return all keys - * @throws KvStorageException KVStorageException - */ - List allKeys() throws KvStorageException; - - /** - * shutdown. - */ - void shutdown(); - -} diff --git a/core/src/main/java/com/alibaba/nacos/core/storage/kv/MemoryKvStorage.java b/core/src/main/java/com/alibaba/nacos/core/storage/kv/MemoryKvStorage.java deleted file mode 100644 index 34577f70159..00000000000 --- a/core/src/main/java/com/alibaba/nacos/core/storage/kv/MemoryKvStorage.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.core.storage.kv; - -import com.alibaba.nacos.core.exception.ErrorCode; -import com.alibaba.nacos.core.exception.KvStorageException; -import com.alipay.sofa.jraft.util.BytesUtil; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentSkipListMap; - -/** - * Realization of KV storage based on memory. - * - * @author liaochuntao - */ -public class MemoryKvStorage implements KvStorage { - - private final Map storage = new ConcurrentSkipListMap<>(); - - @Override - public byte[] get(byte[] key) throws KvStorageException { - return storage.get(new Key(key)); - } - - @Override - public Map batchGet(List keys) throws KvStorageException { - Map result = new HashMap<>(keys.size()); - for (byte[] key : keys) { - byte[] val = storage.get(new Key(key)); - if (val != null) { - result.put(key, val); - } - } - return result; - } - - @Override - public void put(byte[] key, byte[] value) throws KvStorageException { - storage.put(new Key(key), value); - } - - @Override - public void batchPut(List keys, List values) throws KvStorageException { - if (keys.size() != values.size()) { - throw new KvStorageException(ErrorCode.KVStorageBatchWriteError.getCode(), - "key's size must be equal to value's size"); - } - int size = keys.size(); - for (int i = 0; i < size; i++) { - storage.put(new Key(keys.get(i)), values.get(i)); - } - } - - @Override - public void delete(byte[] key) throws KvStorageException { - storage.remove(new Key(key)); - } - - @Override - public void batchDelete(List keys) throws KvStorageException { - for (byte[] key : keys) { - storage.remove(new Key(key)); - } - } - - @Override - public void doSnapshot(String backupPath) throws KvStorageException { - throw new UnsupportedOperationException(); - } - - @Override - public void snapshotLoad(String path) throws KvStorageException { - throw new UnsupportedOperationException(); - } - - @Override - public List allKeys() throws KvStorageException { - List result = new LinkedList<>(); - for (Key each : storage.keySet()) { - result.add(each.origin); - } - return result; - } - - @Override - public void shutdown() { - storage.clear(); - } - - private static class Key implements Comparable { - - private final byte[] origin; - - private Key(byte[] origin) { - this.origin = origin; - } - - @Override - public int compareTo(Key o) { - return BytesUtil.compare(origin, o.origin); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Key key = (Key) o; - return Arrays.equals(origin, key.origin); - } - - @Override - public int hashCode() { - return Arrays.hashCode(origin); - } - } - -} diff --git a/core/src/main/java/com/alibaba/nacos/core/utils/WebUtils.java b/core/src/main/java/com/alibaba/nacos/core/utils/WebUtils.java index 1b7a43f75cb..95fa39c9cf5 100644 --- a/core/src/main/java/com/alibaba/nacos/core/utils/WebUtils.java +++ b/core/src/main/java/com/alibaba/nacos/core/utils/WebUtils.java @@ -54,6 +54,12 @@ public class WebUtils { private static final String TMP_SUFFIX = ".tmp"; + private static final String X_REAL_IP = "X-Real-IP"; + + private static final String X_FORWARDED_FOR = "X-Forwarded-For"; + + private static final String X_FORWARDED_FOR_SPLIT_SYMBOL = ","; + /** * get target value from parameterMap, if not found will throw {@link IllegalArgumentException}. * @@ -248,4 +254,22 @@ public static void process(DeferredResult deferredResult, CompletableFutu deferredResult.setResult(t); }); } + + /** + * get real client ip + * + *

    first use X-Forwarded-For header https://zh.wikipedia.org/wiki/X-Forwarded-For next nginx X-Real-IP last + * {@link HttpServletRequest#getRemoteAddr()} + * + * @param request {@link HttpServletRequest} + * @return remote ip address. + */ + public static String getRemoteIp(HttpServletRequest request) { + String xForwardedFor = request.getHeader(X_FORWARDED_FOR); + if (!StringUtils.isBlank(xForwardedFor)) { + return xForwardedFor.split(X_FORWARDED_FOR_SPLIT_SYMBOL)[0].trim(); + } + String nginxHeader = request.getHeader(X_REAL_IP); + return StringUtils.isBlank(nginxHeader) ? request.getRemoteAddr() : nginxHeader; + } } diff --git a/core/src/main/resources/META-INF/services/com.alibaba.nacos.core.remote.grpc.negotiator.ProtocolNegotiatorBuilder b/core/src/main/resources/META-INF/services/com.alibaba.nacos.core.remote.grpc.negotiator.ProtocolNegotiatorBuilder index 1ea83c1f0b2..e0065225026 100644 --- a/core/src/main/resources/META-INF/services/com.alibaba.nacos.core.remote.grpc.negotiator.ProtocolNegotiatorBuilder +++ b/core/src/main/resources/META-INF/services/com.alibaba.nacos.core.remote.grpc.negotiator.ProtocolNegotiatorBuilder @@ -14,4 +14,5 @@ # limitations under the License. # -com.alibaba.nacos.core.remote.grpc.negotiator.tls.DefaultTlsProtocolNegotiatorBuilder \ No newline at end of file +com.alibaba.nacos.core.remote.grpc.negotiator.tls.SdkDefaultTlsProtocolNegotiatorBuilder +com.alibaba.nacos.core.remote.grpc.negotiator.tls.ClusterDefaultTlsProtocolNegotiatorBuilder diff --git a/core/src/test/java/com/alibaba/nacos/core/ability/AbilityControlManagerTest.java b/core/src/test/java/com/alibaba/nacos/core/ability/AbilityControlManagerTest.java index 2ef69de74e7..c57d0e1d393 100644 --- a/core/src/test/java/com/alibaba/nacos/core/ability/AbilityControlManagerTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/ability/AbilityControlManagerTest.java @@ -19,45 +19,43 @@ import com.alibaba.nacos.api.ability.constant.AbilityKey; import com.alibaba.nacos.api.ability.constant.AbilityMode; import com.alibaba.nacos.api.ability.constant.AbilityStatus; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.springframework.boot.test.context.SpringBootTest; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; import java.util.Set; -@SpringBootTest -public class AbilityControlManagerTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +class AbilityControlManagerTest { private TestServerAbilityControlManager serverAbilityControlManager = new TestServerAbilityControlManager(); - @Before - public void inject() { + @BeforeEach + void inject() { Map newTable = new HashMap<>(); newTable.put(AbilityKey.SERVER_TEST_1.getName(), true); serverAbilityControlManager.setCurrentSupportingAbility(newTable); } @Test - public void testCurrentNodeAbility() { + void testCurrentNodeAbility() { Set keySet = serverAbilityControlManager.getCurrentNodeAbilities(AbilityMode.SERVER).keySet(); // diable all - keySet.forEach(key -> serverAbilityControlManager - .disableCurrentNodeAbility(AbilityKey.getEnum(AbilityMode.SERVER, key))); + keySet.forEach(key -> serverAbilityControlManager.disableCurrentNodeAbility(AbilityKey.getEnum(AbilityMode.SERVER, key))); // get all keySet.forEach(key -> { - Assert.assertNotEquals(serverAbilityControlManager - .isCurrentNodeAbilityRunning(AbilityKey.getEnum(AbilityMode.SERVER, key)), AbilityStatus.SUPPORTED); + assertNotEquals(AbilityStatus.SUPPORTED, + serverAbilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.getEnum(AbilityMode.SERVER, key))); }); // enable all - keySet.forEach(key -> serverAbilityControlManager - .enableCurrentNodeAbility(AbilityKey.getEnum(AbilityMode.SERVER, key))); + keySet.forEach(key -> serverAbilityControlManager.enableCurrentNodeAbility(AbilityKey.getEnum(AbilityMode.SERVER, key))); // get all keySet.forEach(key -> { - Assert.assertEquals(serverAbilityControlManager - .isCurrentNodeAbilityRunning(AbilityKey.getEnum(AbilityMode.SERVER, key)), AbilityStatus.SUPPORTED); + assertEquals(AbilityStatus.SUPPORTED, + serverAbilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.getEnum(AbilityMode.SERVER, key))); }); } diff --git a/core/src/test/java/com/alibaba/nacos/core/ability/RemoteAbilityInitializerTest.java b/core/src/test/java/com/alibaba/nacos/core/ability/RemoteAbilityInitializerTest.java index b818e0fc629..d5e9c9964c5 100644 --- a/core/src/test/java/com/alibaba/nacos/core/ability/RemoteAbilityInitializerTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/ability/RemoteAbilityInitializerTest.java @@ -17,15 +17,15 @@ package com.alibaba.nacos.core.ability; import com.alibaba.nacos.api.ability.ServerAbilities; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class RemoteAbilityInitializerTest { +class RemoteAbilityInitializerTest { @Test - public void testInitialize() { + void testInitialize() { RemoteAbilityInitializer initializer = new RemoteAbilityInitializer(); ServerAbilities serverAbilities = new ServerAbilities(); assertFalse(serverAbilities.getRemoteAbility().isSupportRemoteConnection()); diff --git a/core/src/test/java/com/alibaba/nacos/core/ability/ServerAbilityInitializerHolderTest.java b/core/src/test/java/com/alibaba/nacos/core/ability/ServerAbilityInitializerHolderTest.java index d082428e64a..d2ec5d58f27 100644 --- a/core/src/test/java/com/alibaba/nacos/core/ability/ServerAbilityInitializerHolderTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/ability/ServerAbilityInitializerHolderTest.java @@ -16,14 +16,14 @@ package com.alibaba.nacos.core.ability; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class ServerAbilityInitializerHolderTest { +class ServerAbilityInitializerHolderTest { @Test - public void testGetInitializers() { + void testGetInitializers() { assertEquals(1, ServerAbilityInitializerHolder.getInstance().getInitializers().size()); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/ability/TestServerAbilityControlManager.java b/core/src/test/java/com/alibaba/nacos/core/ability/TestServerAbilityControlManager.java index 087b94ef1aa..a87d667f943 100644 --- a/core/src/test/java/com/alibaba/nacos/core/ability/TestServerAbilityControlManager.java +++ b/core/src/test/java/com/alibaba/nacos/core/ability/TestServerAbilityControlManager.java @@ -23,7 +23,7 @@ import java.util.Map; public class TestServerAbilityControlManager extends ServerAbilityControlManager { - + @JustForTest public void setCurrentSupportingAbility(Map ability) { currentNodeAbilities.get(AbilityMode.SERVER).clear(); diff --git a/core/src/test/java/com/alibaba/nacos/core/ability/config/AbilityConfigsTest.java b/core/src/test/java/com/alibaba/nacos/core/ability/config/AbilityConfigsTest.java index ccca0bb2c2e..6e2a56cf302 100644 --- a/core/src/test/java/com/alibaba/nacos/core/ability/config/AbilityConfigsTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/ability/config/AbilityConfigsTest.java @@ -24,15 +24,17 @@ import com.alibaba.nacos.core.ability.TestServerAbilityControlManager; import com.alibaba.nacos.core.ability.control.ServerAbilityControlManager; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.mock.env.MockEnvironment; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + /** * test for ability in config. * @@ -49,8 +51,8 @@ public class AbilityConfigsTest { private Map currentAbilities; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { environment = new MockEnvironment(); EnvUtil.setEnvironment(environment); abilityConfigs = new TestAbilityConfig(); @@ -68,7 +70,7 @@ void inject(AbilityConfigs abilityConfigs) { abilityConfigs.setAbilityHandlerRegistry(serverAbilityControlManager); this.serverAbilityControlManager = serverAbilityControlManager; } - + /** * fill field. * @@ -86,49 +88,49 @@ public void fill() throws Exception { } @Test - public void testLoadAbilities() throws Exception { + void testLoadAbilities() throws Exception { environment.setProperty(AbilityConfigs.PREFIX + AbilityKey.SERVER_TEST_1.getName(), Boolean.TRUE.toString()); environment.setProperty(AbilityConfigs.PREFIX + AbilityKey.SERVER_TEST_2.getName(), Boolean.FALSE.toString()); // test load fill(); ServerAbilityControlManager manager = new ServerAbilityControlManager(); // config has higher priority - Assert.assertEquals(manager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_1), AbilityStatus.SUPPORTED); - Assert.assertNotEquals(manager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_2), AbilityStatus.SUPPORTED); + assertEquals(AbilityStatus.SUPPORTED, manager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_1)); + assertNotEquals(AbilityStatus.SUPPORTED, manager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_2)); // clear currentAbilities.clear(); } @Test - public void testInit() { - Assert.assertEquals(serverAbilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_1), AbilityStatus.SUPPORTED); - Assert.assertEquals(serverAbilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_2), AbilityStatus.SUPPORTED); + void testInit() { + assertEquals(AbilityStatus.SUPPORTED, serverAbilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_1)); + assertEquals(AbilityStatus.SUPPORTED, serverAbilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_2)); } @Test - public void testConfigChange() throws InterruptedException { + void testConfigChange() throws InterruptedException { // test no change environment.setProperty(AbilityConfigs.PREFIX + AbilityKey.SERVER_TEST_1.getName(), Boolean.TRUE.toString()); environment.setProperty(AbilityConfigs.PREFIX + AbilityKey.SERVER_TEST_2.getName(), Boolean.TRUE.toString()); abilityConfigs.onEvent(new ServerConfigChangeEvent()); - Assert.assertEquals(serverAbilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_1), AbilityStatus.SUPPORTED); - Assert.assertEquals(serverAbilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_2), AbilityStatus.SUPPORTED); + assertEquals(AbilityStatus.SUPPORTED, serverAbilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_1)); + assertEquals(AbilityStatus.SUPPORTED, serverAbilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_2)); // test change environment.setProperty(AbilityConfigs.PREFIX + AbilityKey.SERVER_TEST_1.getName(), Boolean.FALSE.toString()); abilityConfigs.onEvent(new ServerConfigChangeEvent()); - Assert.assertNotEquals(serverAbilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_1), AbilityStatus.SUPPORTED); - Assert.assertEquals(serverAbilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_2), AbilityStatus.SUPPORTED); - + assertNotEquals(AbilityStatus.SUPPORTED, serverAbilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_1)); + assertEquals(AbilityStatus.SUPPORTED, serverAbilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_2)); + environment.setProperty(AbilityConfigs.PREFIX + AbilityKey.SERVER_TEST_1.getName(), Boolean.TRUE.toString()); abilityConfigs.onEvent(new ServerConfigChangeEvent()); - Assert.assertEquals(serverAbilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_1), AbilityStatus.SUPPORTED); - + assertEquals(AbilityStatus.SUPPORTED, serverAbilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_1)); + environment.setProperty(AbilityConfigs.PREFIX + AbilityKey.SERVER_TEST_1.getName(), Boolean.FALSE.toString()); environment.setProperty(AbilityConfigs.PREFIX + AbilityKey.SERVER_TEST_2.getName(), Boolean.FALSE.toString()); abilityConfigs.onEvent(new ServerConfigChangeEvent()); - Assert.assertNotEquals(serverAbilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_1), AbilityStatus.SUPPORTED); - Assert.assertNotEquals(serverAbilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_2), AbilityStatus.SUPPORTED); + assertNotEquals(AbilityStatus.SUPPORTED, serverAbilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_1)); + assertNotEquals(AbilityStatus.SUPPORTED, serverAbilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_2)); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/ability/config/TestAbilityConfig.java b/core/src/test/java/com/alibaba/nacos/core/ability/config/TestAbilityConfig.java index 446d2630bc3..3443cd3ea12 100644 --- a/core/src/test/java/com/alibaba/nacos/core/ability/config/TestAbilityConfig.java +++ b/core/src/test/java/com/alibaba/nacos/core/ability/config/TestAbilityConfig.java @@ -20,9 +20,11 @@ import java.util.Set; -/**. +/** + * . + * * @author Daydreamer - * @description Dynamically load ability from config. just for test + * @description Dynamically load ability from config. just for test * @date 2022/8/31 12:27 **/ public class TestAbilityConfig extends AbilityConfigs { diff --git a/core/src/test/java/com/alibaba/nacos/core/auth/AuthConfigTest.java b/core/src/test/java/com/alibaba/nacos/core/auth/AuthConfigTest.java index bb72f930751..13f4c1e30fd 100644 --- a/core/src/test/java/com/alibaba/nacos/core/auth/AuthConfigTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/auth/AuthConfigTest.java @@ -17,33 +17,35 @@ package com.alibaba.nacos.core.auth; -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 org.springframework.boot.web.servlet.FilterRegistrationBean; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * {@link AuthConfig} unit test. * * @author chenglu * @date 2021-07-06 13:36 */ -@RunWith(MockitoJUnitRunner.class) -public class AuthConfigTest { +@ExtendWith(MockitoExtension.class) +class AuthConfigTest { @Mock private AuthFilter authFilter; @Test - public void testAuthFilterRegistration() { + void testAuthFilterRegistration() { AuthConfig config = new AuthConfig(); FilterRegistrationBean filter = config.authFilterRegistration(authFilter); - Assert.assertTrue(filter.getFilter() instanceof AuthFilter); + assertTrue(filter.getFilter() instanceof AuthFilter); - Assert.assertTrue(filter.getUrlPatterns().contains("/*")); + assertTrue(filter.getUrlPatterns().contains("/*")); - Assert.assertEquals(6, filter.getOrder()); + assertEquals(6, filter.getOrder()); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/auth/AuthFilterTest.java b/core/src/test/java/com/alibaba/nacos/core/auth/AuthFilterTest.java index 075e6302baa..5baa64bf268 100644 --- a/core/src/test/java/com/alibaba/nacos/core/auth/AuthFilterTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/auth/AuthFilterTest.java @@ -21,14 +21,15 @@ import com.alibaba.nacos.auth.config.AuthConfigs; import com.alibaba.nacos.common.constant.HttpHeaderConsts; import com.alibaba.nacos.core.code.ControllerMethodsCache; +import com.alibaba.nacos.core.context.RequestContextHolder; import com.alibaba.nacos.sys.env.Constants; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; @@ -39,14 +40,16 @@ import javax.servlet.http.HttpServletResponse; import java.io.IOException; +import static org.junit.jupiter.api.Assertions.fail; + /** * {@link AuthFilter} unit test. * * @author chenglu * @date 2021-07-06 13:44 */ -@RunWith(MockitoJUnitRunner.class) -public class AuthFilterTest { +@ExtendWith(MockitoExtension.class) +class AuthFilterTest { @InjectMocks private AuthFilter authFilter; @@ -57,8 +60,13 @@ public class AuthFilterTest { @Mock private ControllerMethodsCache methodsCache; + @AfterEach + void tearDown() { + RequestContextHolder.removeContext(); + } + @Test - public void testDoFilter() { + void testDoFilter() { try { FilterChain filterChain = new MockFilterChain(); Mockito.when(authConfigs.isAuthEnabled()).thenReturn(true); @@ -79,21 +87,19 @@ public void testDoFilter() { Mockito.when(authConfigs.getServerIdentityValue()).thenReturn("3"); authFilter.doFilter(request, response, filterChain); - Mockito.when(methodsCache.getMethod(Mockito.any())) - .thenReturn(filterChain.getClass().getMethod("testSecured")); + Mockito.when(methodsCache.getMethod(Mockito.any())).thenReturn(filterChain.getClass().getMethod("testSecured")); authFilter.doFilter(request, response, filterChain); } catch (Exception e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } class MockFilterChain implements FilterChain { @Override - public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) - throws IOException, ServletException { + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException { System.out.println("filter chain executed"); } diff --git a/core/src/test/java/com/alibaba/nacos/core/auth/RemoteRequestAuthFilterTest.java b/core/src/test/java/com/alibaba/nacos/core/auth/RemoteRequestAuthFilterTest.java index 1a3114010b7..61f5963fcb2 100644 --- a/core/src/test/java/com/alibaba/nacos/core/auth/RemoteRequestAuthFilterTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/auth/RemoteRequestAuthFilterTest.java @@ -24,14 +24,18 @@ import com.alibaba.nacos.api.remote.response.Response; import com.alibaba.nacos.auth.annotation.Secured; import com.alibaba.nacos.auth.config.AuthConfigs; +import com.alibaba.nacos.core.context.RequestContextHolder; import com.alibaba.nacos.core.remote.RequestHandler; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; 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.assertNull; +import static org.junit.jupiter.api.Assertions.fail; /** * {@link RemoteRequestAuthFilter} unit test. @@ -39,8 +43,8 @@ * @author chenglu * @date 2021-07-06 16:14 */ -@RunWith(MockitoJUnitRunner.class) -public class RemoteRequestAuthFilterTest { +@ExtendWith(MockitoExtension.class) +class RemoteRequestAuthFilterTest { @InjectMocks private RemoteRequestAuthFilter remoteRequestAuthFilter; @@ -48,19 +52,23 @@ public class RemoteRequestAuthFilterTest { @Mock private AuthConfigs authConfigs; + @AfterEach + void tearDown() { + RequestContextHolder.removeContext(); + } + @Test - public void testFilter() { + void testFilter() { Mockito.when(authConfigs.isAuthEnabled()).thenReturn(true); Request healthCheckRequest = new HealthCheckRequest(); try { - Response healthCheckResponse = remoteRequestAuthFilter - .filter(healthCheckRequest, new RequestMeta(), MockRequestHandler.class); - Assert.assertNull(healthCheckResponse); + Response healthCheckResponse = remoteRequestAuthFilter.filter(healthCheckRequest, new RequestMeta(), MockRequestHandler.class); + assertNull(healthCheckResponse); } catch (NacosException e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/cluster/MemberUtilTest.java b/core/src/test/java/com/alibaba/nacos/core/cluster/MemberUtilTest.java index 679e5ada894..fd955b8d442 100644 --- a/core/src/test/java/com/alibaba/nacos/core/cluster/MemberUtilTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/cluster/MemberUtilTest.java @@ -18,13 +18,14 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.sys.env.EnvUtil; -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 org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.mock.env.MockEnvironment; @@ -38,15 +39,18 @@ import java.util.HashSet; import java.util.Set; -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; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class MemberUtilTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class MemberUtilTest { private static final String IP = "1.1.1.1"; @@ -63,8 +67,8 @@ public class MemberUtilTest { private String nacosHome; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { environment = new MockEnvironment(); EnvUtil.setEnvironment(environment); EnvUtil.setIsStandalone(true); @@ -79,13 +83,13 @@ private Member buildMember() { return Member.builder().ip(IP).port(PORT).state(NodeState.UP).build(); } - @After - public void tearDown() throws NacosException { + @AfterEach + void tearDown() throws NacosException { EnvUtil.setNacosHomePath(nacosHome); } @Test - public void testCopy() { + void testCopy() { Member expected = Member.builder().build(); expected.setIp("2.2.2.2"); expected.setPort(9999); @@ -102,31 +106,31 @@ public void testCopy() { } @Test - public void testSingleParseWithPort() { + void testSingleParseWithPort() { Member actual = MemberUtil.singleParse(IP + ":2222"); assertEquals(IP, actual.getIp()); assertEquals(2222, actual.getPort()); assertEquals(IP + ":2222", actual.getAddress()); assertEquals(NodeState.UP, actual.getState()); - assertEquals(true, actual.getExtendVal(MemberMetaDataConstants.READY_TO_UPGRADE)); + assertTrue((Boolean) actual.getExtendVal(MemberMetaDataConstants.READY_TO_UPGRADE)); assertEquals("1222", actual.getExtendVal(MemberMetaDataConstants.RAFT_PORT)); assertFalse(actual.getAbilities().getRemoteAbility().isSupportRemoteConnection()); } @Test - public void testSingleParseWithoutPort() { + void testSingleParseWithoutPort() { Member actual = MemberUtil.singleParse(IP); assertEquals(IP, actual.getIp()); assertEquals(PORT, actual.getPort()); assertEquals(IP + ":" + PORT, actual.getAddress()); assertEquals(NodeState.UP, actual.getState()); - assertEquals(true, actual.getExtendVal(MemberMetaDataConstants.READY_TO_UPGRADE)); + assertTrue((Boolean) actual.getExtendVal(MemberMetaDataConstants.READY_TO_UPGRADE)); assertEquals("7848", actual.getExtendVal(MemberMetaDataConstants.RAFT_PORT)); assertFalse(actual.getAbilities().getRemoteAbility().isSupportRemoteConnection()); } @Test - public void testIsSupportedLongCon() { + void testIsSupportedLongCon() { assertFalse(MemberUtil.isSupportedLongCon(originalMember)); originalMember.getAbilities().getRemoteAbility().setSupportRemoteConnection(true); assertTrue(MemberUtil.isSupportedLongCon(originalMember)); @@ -137,7 +141,7 @@ public void testIsSupportedLongCon() { } @Test - public void testMultiParse() { + void testMultiParse() { Collection address = new HashSet<>(); address.add("1.1.1.1:3306"); address.add("1.1.1.1"); @@ -146,7 +150,7 @@ public void testMultiParse() { } @Test - public void testSyncToFile() throws IOException { + void testSyncToFile() throws IOException { File file = new File(EnvUtil.getClusterConfFilePath()); file.getParentFile().mkdirs(); assertTrue(file.createNewFile()); @@ -159,14 +163,14 @@ public void testSyncToFile() throws IOException { return; } } - Assert.fail("No found member info in cluster.conf"); + fail("No found member info in cluster.conf"); } finally { file.delete(); } } @Test - public void testReadServerConf() { + void testReadServerConf() { Collection address = new HashSet<>(); address.add("1.1.1.1:3306"); address.add("1.1.1.1"); @@ -175,7 +179,7 @@ public void testReadServerConf() { } @Test - public void testSelectTargetMembers() { + void testSelectTargetMembers() { Collection input = new HashSet<>(); input.add(originalMember); Member member = buildMember(); @@ -186,105 +190,105 @@ public void testSelectTargetMembers() { } @Test - public void testIsBasicInfoChangedNoChangeWithoutExtendInfo() { + void testIsBasicInfoChangedNoChangeWithoutExtendInfo() { Member newMember = buildMember(); assertFalse(MemberUtil.isBasicInfoChanged(newMember, originalMember)); } @Test - public void testIsBasicInfoChangedNoChangeWithExtendInfo() { + void testIsBasicInfoChangedNoChangeWithExtendInfo() { Member newMember = buildMember(); newMember.setExtendVal("test", "test"); assertFalse(MemberUtil.isBasicInfoChanged(newMember, originalMember)); } @Test - public void testIsBasicInfoChangedForIp() { + void testIsBasicInfoChangedForIp() { Member newMember = buildMember(); newMember.setIp("1.1.1.2"); assertTrue(MemberUtil.isBasicInfoChanged(newMember, originalMember)); } @Test - public void testIsBasicInfoChangedForPort() { + void testIsBasicInfoChangedForPort() { Member newMember = buildMember(); newMember.setPort(PORT + 1); assertTrue(MemberUtil.isBasicInfoChanged(newMember, originalMember)); } @Test - public void testIsBasicInfoChangedForAddress() { + void testIsBasicInfoChangedForAddress() { Member newMember = buildMember(); newMember.setAddress("test"); assertTrue(MemberUtil.isBasicInfoChanged(newMember, originalMember)); } @Test - public void testIsBasicInfoChangedForStatus() { + void testIsBasicInfoChangedForStatus() { Member newMember = buildMember(); newMember.setState(NodeState.DOWN); assertTrue(MemberUtil.isBasicInfoChanged(newMember, originalMember)); } @Test - public void testIsBasicInfoChangedForMoreBasicExtendInfo() { + void testIsBasicInfoChangedForMoreBasicExtendInfo() { Member newMember = buildMember(); newMember.setExtendVal(MemberMetaDataConstants.VERSION, "TEST"); assertTrue(MemberUtil.isBasicInfoChanged(newMember, originalMember)); } @Test - public void testIsBasicInfoChangedForChangedBasicExtendInfo() { + void testIsBasicInfoChangedForChangedBasicExtendInfo() { Member newMember = buildMember(); newMember.setExtendVal(MemberMetaDataConstants.WEIGHT, "100"); assertTrue(MemberUtil.isBasicInfoChanged(newMember, originalMember)); } @Test - public void testIsBasicInfoChangedForChangedAbilities() { + void testIsBasicInfoChangedForChangedAbilities() { Member newMember = buildMember(); newMember.setGrpcReportEnabled(true); assertTrue(MemberUtil.isBasicInfoChanged(newMember, originalMember)); } @Test - public void testIsBasicInfoChangedForChangedNull() { + void testIsBasicInfoChangedForChangedNull() { Member newMember = buildMember(); assertTrue(MemberUtil.isBasicInfoChanged(newMember, null)); } @Test - public void testMemberOnFailWhenReachMaxFailAccessCnt() { + void testMemberOnFailWhenReachMaxFailAccessCnt() { final Member remote = buildMember(); mockMemberAddressInfos.add(remote.getAddress()); remote.setState(NodeState.SUSPICIOUS); remote.setFailAccessCnt(2); MemberUtil.onFail(memberManager, remote); - Assert.assertEquals(3, remote.getFailAccessCnt()); - Assert.assertEquals(NodeState.SUSPICIOUS, remote.getState()); + assertEquals(3, remote.getFailAccessCnt()); + assertEquals(NodeState.SUSPICIOUS, remote.getState()); verify(memberManager, never()).notifyMemberChange(remote); - Assert.assertTrue(mockMemberAddressInfos.isEmpty()); + assertTrue(mockMemberAddressInfos.isEmpty()); MemberUtil.onFail(memberManager, remote); - Assert.assertEquals(4, remote.getFailAccessCnt()); - Assert.assertEquals(NodeState.DOWN, remote.getState()); + assertEquals(4, remote.getFailAccessCnt()); + assertEquals(NodeState.DOWN, remote.getState()); verify(memberManager).notifyMemberChange(remote); } @Test - public void testMemberOnFailWhenConnectRefused() { + void testMemberOnFailWhenConnectRefused() { final Member remote = buildMember(); mockMemberAddressInfos.add(remote.getAddress()); remote.setFailAccessCnt(1); MemberUtil.onFail(memberManager, remote, new ConnectException(MemberUtil.TARGET_MEMBER_CONNECT_REFUSE_ERRMSG)); - Assert.assertEquals(2, remote.getFailAccessCnt()); - Assert.assertEquals(NodeState.DOWN, remote.getState()); - Assert.assertTrue(mockMemberAddressInfos.isEmpty()); + assertEquals(2, remote.getFailAccessCnt()); + assertEquals(NodeState.DOWN, remote.getState()); + assertTrue(mockMemberAddressInfos.isEmpty()); verify(memberManager).notifyMemberChange(remote); } @SuppressWarnings("checkstyle:AbbreviationAsWordInName") @Test - public void testMemberOnFailWhenMemberAlreadyNOUP() { + void testMemberOnFailWhenMemberAlreadyNOUP() { final Member remote = buildMember(); remote.setState(NodeState.DOWN); remote.setFailAccessCnt(4); @@ -293,7 +297,7 @@ public void testMemberOnFailWhenMemberAlreadyNOUP() { } @Test - public void testMemberOnSuccessFromDown() { + void testMemberOnSuccessFromDown() { final Member remote = buildMember(); remote.setState(NodeState.DOWN); remote.setFailAccessCnt(4); @@ -304,7 +308,7 @@ public void testMemberOnSuccessFromDown() { } @Test - public void testMemberOnSuccessWhenMemberAlreadyUP() { + void testMemberOnSuccessWhenMemberAlreadyUP() { final Member remote = buildMember(); memberManager.updateMember(remote); MemberUtil.onSuccess(memberManager, remote); @@ -312,7 +316,7 @@ public void testMemberOnSuccessWhenMemberAlreadyUP() { } @Test - public void testMemberOnSuccessWhenMemberNotUpdated() { + void testMemberOnSuccessWhenMemberNotUpdated() { final Member remote = buildMember(); final Member reportResult = buildMember(); MemberUtil.onSuccess(memberManager, remote, reportResult); @@ -322,7 +326,7 @@ public void testMemberOnSuccessWhenMemberNotUpdated() { } @Test - public void testMemberOnSuccessWhenMemberUpdatedAbilities() { + void testMemberOnSuccessWhenMemberUpdatedAbilities() { final Member remote = buildMember(); final Member reportResult = buildMember(); reportResult.getAbilities().getRemoteAbility().setSupportRemoteConnection(true); @@ -333,7 +337,7 @@ public void testMemberOnSuccessWhenMemberUpdatedAbilities() { } @Test - public void testMemberOnSuccessWhenMemberUpdatedExtendInfo() { + void testMemberOnSuccessWhenMemberUpdatedExtendInfo() { final Member remote = buildMember(); final Member reportResult = buildMember(); reportResult.setExtendVal(MemberMetaDataConstants.VERSION, "test"); diff --git a/core/src/test/java/com/alibaba/nacos/core/cluster/ServerMemberManagerTest.java b/core/src/test/java/com/alibaba/nacos/core/cluster/ServerMemberManagerTest.java index 1ce3f1eb415..63ad753f1ce 100644 --- a/core/src/test/java/com/alibaba/nacos/core/cluster/ServerMemberManagerTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/cluster/ServerMemberManagerTest.java @@ -30,14 +30,15 @@ import com.alibaba.nacos.core.cluster.remote.response.MemberReportResponse; import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.utils.ApplicationUtils; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.boot.web.context.WebServerInitializedEvent; import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext; import org.springframework.context.ConfigurableApplicationContext; @@ -49,9 +50,9 @@ import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; -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; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; @@ -60,8 +61,12 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class ServerMemberManagerTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class ServerMemberManagerTest { + + private static final AtomicBoolean EVENT_PUBLISH = new AtomicBoolean(false); @Mock private ConfigurableEnvironment environment; @@ -86,10 +91,8 @@ public class ServerMemberManagerTest { private ServerMemberManager serverMemberManager; - private static final AtomicBoolean EVENT_PUBLISH = new AtomicBoolean(false); - - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { when(environment.getProperty("server.port", Integer.class, 8848)).thenReturn(8848); when(environment.getProperty("nacos.member-change-event.queue.size", Integer.class, 128)).thenReturn(128); when(context.getBean(AuthConfigs.class)).thenReturn(authConfigs); @@ -103,21 +106,21 @@ public void setUp() throws Exception { NotifyCenter.getPublisherMap().put(MembersChangeEvent.class.getCanonicalName(), eventPublisher); } - @After - public void tearDown() throws NacosException { + @AfterEach + void tearDown() throws NacosException { EVENT_PUBLISH.set(false); NotifyCenter.deregisterPublisher(MembersChangeEvent.class); serverMemberManager.shutdown(); } @Test - public void testUpdateNonExistMember() { + void testUpdateNonExistMember() { Member newMember = Member.builder().ip("1.1.1.2").port(8848).state(NodeState.UP).build(); assertFalse(serverMemberManager.update(newMember)); } @Test - public void testUpdateDownMember() { + void testUpdateDownMember() { Member newMember = Member.builder().ip("1.1.1.1").port(8848).state(NodeState.DOWN).build(); assertTrue(serverMemberManager.update(newMember)); assertFalse(serverMemberManager.getMemberAddressInfos().contains("1.1.1.1:8848")); @@ -125,18 +128,17 @@ public void testUpdateDownMember() { } @Test - public void testUpdateVersionMember() { + void testUpdateVersionMember() { Member newMember = Member.builder().ip("1.1.1.1").port(8848).state(NodeState.UP).build(); newMember.setExtendVal(MemberMetaDataConstants.VERSION, "testVersion"); assertTrue(serverMemberManager.update(newMember)); assertTrue(serverMemberManager.getMemberAddressInfos().contains("1.1.1.1:8848")); - assertEquals("testVersion", - serverMemberManager.getServerList().get("1.1.1.1:8848").getExtendVal(MemberMetaDataConstants.VERSION)); + assertEquals("testVersion", serverMemberManager.getServerList().get("1.1.1.1:8848").getExtendVal(MemberMetaDataConstants.VERSION)); verify(eventPublisher).publish(any(MembersChangeEvent.class)); } @Test - public void testUpdateNonBasicExtendInfoMember() { + void testUpdateNonBasicExtendInfoMember() { Member newMember = Member.builder().ip("1.1.1.1").port(8848).state(NodeState.UP).build(); newMember.setExtendVal("naming", "test"); assertTrue(serverMemberManager.update(newMember)); @@ -146,12 +148,12 @@ public void testUpdateNonBasicExtendInfoMember() { } @Test - public void testHasMember() { + void testHasMember() { assertTrue(serverMemberManager.hasMember("1.1.1.1")); } @Test - public void testMemberLeave() { + void testMemberLeave() { Member member = Member.builder().ip("1.1.3.3").port(8848).state(NodeState.DOWN).build(); boolean joinResult = serverMemberManager.memberJoin(Collections.singletonList(member)); assertTrue(joinResult); @@ -164,40 +166,39 @@ public void testMemberLeave() { } @Test - public void testIsUnHealth() { + void testIsUnHealth() { assertFalse(serverMemberManager.isUnHealth("1.1.1.1")); } @Test - public void testIsFirstIp() { + void testIsFirstIp() { assertFalse(serverMemberManager.isFirstIp()); } @Test - public void testGetServerList() { + void testGetServerList() { assertEquals(2, serverMemberManager.getServerList().size()); } @Test - public void testEnvSetPort() { + void testEnvSetPort() { ServletWebServerApplicationContext context = new ServletWebServerApplicationContext(); context.setServerNamespace("management"); Mockito.when(mockEvent.getApplicationContext()).thenReturn(context); serverMemberManager.onApplicationEvent(mockEvent); int port = EnvUtil.getPort(); - Assert.assertEquals(port, 8848); + assertEquals(8848, port); } @Test - public void testHttpReportTaskWithoutMemberInfo() throws NacosException { + void testHttpReportTaskWithoutMemberInfo() throws NacosException { Member testMember = Member.builder().ip("1.1.1.1").port(8848).state(NodeState.DOWN) .extendInfo(Collections.singletonMap(MemberMetaDataConstants.VERSION, "test")).build(); testMember.setAbilities(new ServerAbilities()); testMember.getAbilities().getRemoteAbility().setSupportRemoteConnection(true); testMember.getAbilities().getRemoteAbility().setGrpcReportEnabled(false); serverMemberManager.updateMember(testMember); - assertTrue( - serverMemberManager.find("1.1.1.1:8848").getExtendInfo().containsKey(MemberMetaDataConstants.VERSION)); + assertTrue(serverMemberManager.find("1.1.1.1:8848").getExtendInfo().containsKey(MemberMetaDataConstants.VERSION)); NacosAsyncRestTemplate mockAsyncRestTemplate = mock(NacosAsyncRestTemplate.class); ReflectionTestUtils.setField(serverMemberManager, "asyncRestTemplate", mockAsyncRestTemplate); doAnswer(invocationOnMock -> { @@ -212,14 +213,13 @@ public void testHttpReportTaskWithoutMemberInfo() throws NacosException { } @Test - public void testGrpcReportTaskWithoutMemberInfo() throws NacosException { + void testGrpcReportTaskWithoutMemberInfo() throws NacosException { Member testMember = Member.builder().ip("1.1.1.1").port(8848).state(NodeState.DOWN) .extendInfo(Collections.singletonMap(MemberMetaDataConstants.VERSION, "test")).build(); testMember.setAbilities(new ServerAbilities()); testMember.getAbilities().getRemoteAbility().setSupportRemoteConnection(true); serverMemberManager.updateMember(testMember); - assertTrue( - serverMemberManager.find("1.1.1.1:8848").getExtendInfo().containsKey(MemberMetaDataConstants.VERSION)); + assertTrue(serverMemberManager.find("1.1.1.1:8848").getExtendInfo().containsKey(MemberMetaDataConstants.VERSION)); ServerMemberManager.MemberInfoReportTask infoReportTask = serverMemberManager.getInfoReportTask(); ClusterRpcClientProxy clusterRpcClientProxy = mock(ClusterRpcClientProxy.class); ReflectionTestUtils.setField(infoReportTask, "clusterRpcClientProxy", clusterRpcClientProxy); @@ -232,15 +232,14 @@ public void testGrpcReportTaskWithoutMemberInfo() throws NacosException { } @Test - public void testHttpReportTaskWithMemberInfoChanged() { + void testHttpReportTaskWithMemberInfoChanged() { Member testMember = Member.builder().ip("1.1.1.1").port(8848).state(NodeState.DOWN) .extendInfo(Collections.singletonMap(MemberMetaDataConstants.VERSION, "test")).build(); testMember.setAbilities(new ServerAbilities()); testMember.getAbilities().getRemoteAbility().setSupportRemoteConnection(true); testMember.getAbilities().getRemoteAbility().setGrpcReportEnabled(false); serverMemberManager.updateMember(testMember); - assertTrue( - serverMemberManager.find("1.1.1.1:8848").getExtendInfo().containsKey(MemberMetaDataConstants.VERSION)); + assertTrue(serverMemberManager.find("1.1.1.1:8848").getExtendInfo().containsKey(MemberMetaDataConstants.VERSION)); Member newMember = Member.builder().ip("1.1.1.1").port(8848).state(NodeState.DOWN) .extendInfo(Collections.singletonMap(MemberMetaDataConstants.VERSION, "new")).build(); NacosAsyncRestTemplate mockAsyncRestTemplate = mock(NacosAsyncRestTemplate.class); @@ -257,14 +256,13 @@ public void testHttpReportTaskWithMemberInfoChanged() { } @Test - public void testGrpcReportTaskWithMemberInfoChanged() throws NacosException { + void testGrpcReportTaskWithMemberInfoChanged() throws NacosException { Member testMember = Member.builder().ip("1.1.1.1").port(8848).state(NodeState.DOWN) .extendInfo(Collections.singletonMap(MemberMetaDataConstants.VERSION, "test")).build(); testMember.setAbilities(new ServerAbilities()); testMember.getAbilities().getRemoteAbility().setSupportRemoteConnection(true); serverMemberManager.updateMember(testMember); - assertTrue( - serverMemberManager.find("1.1.1.1:8848").getExtendInfo().containsKey(MemberMetaDataConstants.VERSION)); + assertTrue(serverMemberManager.find("1.1.1.1:8848").getExtendInfo().containsKey(MemberMetaDataConstants.VERSION)); Member newMember = Member.builder().ip("1.1.1.1").port(8848).state(NodeState.UP) .extendInfo(Collections.singletonMap(MemberMetaDataConstants.VERSION, "new")).build(); ServerMemberManager.MemberInfoReportTask infoReportTask = serverMemberManager.getInfoReportTask(); diff --git a/core/src/test/java/com/alibaba/nacos/core/cluster/lookup/AddressServerMemberLookupTest.java b/core/src/test/java/com/alibaba/nacos/core/cluster/lookup/AddressServerMemberLookupTest.java index b90ad9a89a2..aeade5ec76e 100644 --- a/core/src/test/java/com/alibaba/nacos/core/cluster/lookup/AddressServerMemberLookupTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/cluster/lookup/AddressServerMemberLookupTest.java @@ -22,18 +22,20 @@ import com.alibaba.nacos.common.http.param.Header; import com.alibaba.nacos.common.http.param.Query; import com.alibaba.nacos.common.model.RestResult; +import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.core.cluster.ServerMemberManager; import com.alibaba.nacos.core.utils.GenericType; import com.alibaba.nacos.core.utils.Loggers; +import com.alibaba.nacos.sys.env.Constants; import com.alibaba.nacos.sys.env.EnvUtil; -import junit.framework.TestCase; -import com.alibaba.nacos.common.utils.StringUtils; -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 org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.test.util.ReflectionTestUtils; @@ -41,13 +43,20 @@ import java.util.Map; 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.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class AddressServerMemberLookupTest extends TestCase { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class AddressServerMemberLookupTest { + + private final GenericType genericType = new GenericType() { + }; @Mock private NacosRestTemplate restTemplate; @@ -72,20 +81,19 @@ public class AddressServerMemberLookupTest extends TestCase { @Mock private ConfigurableEnvironment environment; - - private final GenericType genericType = new GenericType() { }; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { EnvUtil.setEnvironment(environment); when(environment.getProperty("maxHealthCheckFailCount", "12")).thenReturn("12"); when(environment.getProperty("nacos.core.address-server.retry", Integer.class, 5)).thenReturn(5); when(environment.getProperty("address.server.domain", "jmenv.tbsite.net")).thenReturn("jmenv.tbsite.net"); when(environment.getProperty("address.server.port", "8080")).thenReturn("8080"); when(environment.getProperty(eq("address.server.url"), any(String.class))).thenReturn("/nacos/serverlist"); + when(environment.getProperty(Constants.WEB_CONTEXT_PATH)).thenReturn("/nacos"); initAddressSys(); - when(restTemplate.get(eq(addressServerUrl), any(Header.EMPTY.getClass()), any(Query.EMPTY.getClass()), any(Type.class))) - .thenReturn(result); + when(restTemplate.get(eq(addressServerUrl), any(Header.EMPTY.getClass()), any(Query.EMPTY.getClass()), + any(Type.class))).thenReturn(result); addressServerMemberLookup = new AddressServerMemberLookup(); ReflectionTestUtils.setField(addressServerMemberLookup, "restTemplate", restTemplate); @@ -94,20 +102,20 @@ public void setUp() throws Exception { addressServerMemberLookup.start(); } - @After - public void tearDown() throws NacosException { + @AfterEach + void tearDown() throws NacosException { addressServerMemberLookup.destroy(); } @Test - public void testMemberChange() throws Exception { + void testMemberChange() throws Exception { addressServerMemberLookup.injectMemberManager(memberManager); verify(restTemplate).get(eq(addressServerUrl), any(Header.EMPTY.getClass()), any(Query.EMPTY.getClass()), any(Type.class)); } @Test - public void testInfo() { - Map infos = addressServerMemberLookup.info(); + void testInfo() { + Map infos = addressServerMemberLookup.info(); assertEquals(4, infos.size()); assertTrue(infos.containsKey("addressServerHealth")); assertTrue(infos.containsKey("addressServerUrl")); @@ -116,11 +124,10 @@ public void testInfo() { assertEquals(addressServerUrl, infos.get("addressServerUrl")); assertEquals(envIdUrl, infos.get("envIdUrl")); } - + @Test - public void testSyncFromAddressUrl() throws Exception { - RestResult result = restTemplate - .get(addressServerUrl, Header.EMPTY, Query.EMPTY, genericType.getType()); + void testSyncFromAddressUrl() throws Exception { + RestResult result = restTemplate.get(addressServerUrl, Header.EMPTY, Query.EMPTY, genericType.getType()); assertEquals("1.1.1.1:8848", result.getData()); } @@ -149,4 +156,4 @@ private void initAddressSys() { Loggers.CORE.info("ServerListService address-server port:" + addressPort); Loggers.CORE.info("ADDRESS_SERVER_URL:" + addressServerUrl); } -} \ No newline at end of file +} diff --git a/core/src/test/java/com/alibaba/nacos/core/cluster/lookup/FileConfigMemberLookupTest.java b/core/src/test/java/com/alibaba/nacos/core/cluster/lookup/FileConfigMemberLookupTest.java index 847c6aca827..59682b4c215 100644 --- a/core/src/test/java/com/alibaba/nacos/core/cluster/lookup/FileConfigMemberLookupTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/cluster/lookup/FileConfigMemberLookupTest.java @@ -20,56 +20,58 @@ import com.alibaba.nacos.core.cluster.Member; import com.alibaba.nacos.core.cluster.ServerMemberManager; import com.alibaba.nacos.sys.env.EnvUtil; -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 org.springframework.mock.env.MockEnvironment; import java.util.Collections; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.fail; + /** * {@link FileConfigMemberLookup} unit test. * * @author chenglu * @date 2021-07-08 22:23 */ -@RunWith(MockitoJUnitRunner.class) -public class FileConfigMemberLookupTest { +@ExtendWith(MockitoExtension.class) +class FileConfigMemberLookupTest { private FileConfigMemberLookup fileConfigMemberLookup; @Mock private ServerMemberManager memberManager; - @Before - public void setUp() throws NacosException { + @BeforeEach + void setUp() throws NacosException { EnvUtil.setEnvironment(new MockEnvironment()); fileConfigMemberLookup = new FileConfigMemberLookup(); fileConfigMemberLookup.injectMemberManager(memberManager); fileConfigMemberLookup.start(); } - @After - public void tearDown() throws NacosException { + @AfterEach + void tearDown() throws NacosException { fileConfigMemberLookup.destroy(); } @Test - public void testAfterLookup() { + void testAfterLookup() { try { fileConfigMemberLookup.afterLookup(Collections.singletonList(new Member())); } catch (Exception e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } @Test - public void testUseAddressServer() { - Assert.assertFalse(fileConfigMemberLookup.useAddressServer()); + void testUseAddressServer() { + assertFalse(fileConfigMemberLookup.useAddressServer()); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/cluster/lookup/LookupFactoryTest.java b/core/src/test/java/com/alibaba/nacos/core/cluster/lookup/LookupFactoryTest.java index c56962fdfd7..482d71f4499 100644 --- a/core/src/test/java/com/alibaba/nacos/core/cluster/lookup/LookupFactoryTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/cluster/lookup/LookupFactoryTest.java @@ -21,40 +21,41 @@ import com.alibaba.nacos.core.cluster.ServerMemberManager; import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.file.WatchFileCenter; -import junit.framework.TestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.core.env.StandardEnvironment; import org.springframework.mock.env.MockEnvironment; -@RunWith(MockitoJUnitRunner.class) -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class LookupFactoryTest extends TestCase { +import static org.junit.jupiter.api.Assertions.assertEquals; + +@ExtendWith(MockitoExtension.class) +@TestMethodOrder(MethodName.class) +class LookupFactoryTest { private static final String LOOKUP_MODE_TYPE = "nacos.core.member.lookup.type"; + MockEnvironment mockEnvironment; + @Mock private ServerMemberManager memberManager; private MemberLookup memberLookup; - MockEnvironment mockEnvironment; - - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { EnvUtil.setEnvironment(new StandardEnvironment()); mockEnvironment = new MockEnvironment(); EnvUtil.setEnvironment(mockEnvironment); } - @After - public void tearDown() throws NacosException { + @AfterEach + void tearDown() throws NacosException { WatchFileCenter.deregisterAllWatcher(EnvUtil.getConfPath()); memberManager.shutdown(); } @@ -65,14 +66,14 @@ public void tearDown() throws NacosException { * @throws NacosException NacosException */ @Test - public void createLookUpStandaloneMemberLookup() throws NacosException { + void createLookUpStandaloneMemberLookup() throws NacosException { EnvUtil.setIsStandalone(true); memberLookup = LookupFactory.createLookUp(memberManager); assertEquals(StandaloneMemberLookup.class, memberLookup.getClass()); } @Test - public void createLookUpFileConfigMemberLookup() throws Exception { + void createLookUpFileConfigMemberLookup() throws Exception { EnvUtil.setIsStandalone(false); mockEnvironment.setProperty(LOOKUP_MODE_TYPE, "file"); memberLookup = LookupFactory.createLookUp(memberManager); @@ -80,7 +81,7 @@ public void createLookUpFileConfigMemberLookup() throws Exception { } @Test - public void createLookUpAddressServerMemberLookup() throws Exception { + void createLookUpAddressServerMemberLookup() throws Exception { EnvUtil.setIsStandalone(false); mockEnvironment.setProperty(LOOKUP_MODE_TYPE, "address-server"); memberLookup = LookupFactory.createLookUp(memberManager); @@ -88,22 +89,22 @@ public void createLookUpAddressServerMemberLookup() throws Exception { } @Test - public void testSwitchLookup() throws Exception { + void testSwitchLookup() throws Exception { EnvUtil.setIsStandalone(false); createLookUpFileConfigMemberLookup(); EnvUtil.setIsStandalone(false); String name1 = "file"; MemberLookup memberLookup = LookupFactory.switchLookup(name1, memberManager); - assertEquals(memberLookup.getClass(), FileConfigMemberLookup.class); + assertEquals(FileConfigMemberLookup.class, memberLookup.getClass()); createLookUpAddressServerMemberLookup(); String name2 = "address-server"; memberLookup = LookupFactory.switchLookup(name2, memberManager); - assertEquals(memberLookup.getClass(), AddressServerMemberLookup.class); + assertEquals(AddressServerMemberLookup.class, memberLookup.getClass()); createLookUpStandaloneMemberLookup(); String name3 = "address-server"; memberLookup = LookupFactory.switchLookup(name3, memberManager); - assertEquals(memberLookup.getClass(), StandaloneMemberLookup.class); + assertEquals(StandaloneMemberLookup.class, memberLookup.getClass()); } } \ No newline at end of file diff --git a/core/src/test/java/com/alibaba/nacos/core/cluster/remote/ClusterRpcClientProxyTest.java b/core/src/test/java/com/alibaba/nacos/core/cluster/remote/ClusterRpcClientProxyTest.java index ffa6167e5ba..dfbbea95e72 100644 --- a/core/src/test/java/com/alibaba/nacos/core/cluster/remote/ClusterRpcClientProxyTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/cluster/remote/ClusterRpcClientProxyTest.java @@ -30,14 +30,15 @@ import com.alibaba.nacos.core.cluster.MembersChangeEvent; import com.alibaba.nacos.core.cluster.ServerMemberManager; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.mock.env.MockEnvironment; import org.springframework.test.util.ReflectionTestUtils; @@ -45,8 +46,10 @@ import java.util.Map; import java.util.concurrent.Executor; -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; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.when; /** @@ -55,8 +58,10 @@ * @author chenglu * @date 2021-07-08 13:22 */ -@RunWith(MockitoJUnitRunner.class) -public class ClusterRpcClientProxyTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class ClusterRpcClientProxyTest { @InjectMocks private ClusterRpcClientProxy clusterRpcClientProxy; @@ -69,8 +74,14 @@ public class ClusterRpcClientProxyTest { private Member member; - @Before - public void setUp() throws NacosException { + @AfterAll + static void tearDown() throws NacosException { + Map clientMap = (Map) ReflectionTestUtils.getField(RpcClientFactory.class, "CLIENT_MAP"); + clientMap.remove("Cluster-1.1.1.1:-1").shutdown(); + } + + @BeforeEach + void setUp() throws NacosException { EnvUtil.setEnvironment(new MockEnvironment()); member = new Member(); member.setIp("1.1.1.1"); @@ -81,34 +92,26 @@ public void setUp() throws NacosException { member.setAbilities(serverAbilities); when(serverMemberManager.allMembersWithoutSelf()).thenReturn(Collections.singletonList(member)); clusterRpcClientProxy.init(); - Map clientMap = (Map) ReflectionTestUtils - .getField(RpcClientFactory.class, "CLIENT_MAP"); + Map clientMap = (Map) ReflectionTestUtils.getField(RpcClientFactory.class, "CLIENT_MAP"); clientMap.remove("Cluster-" + member.getAddress()).shutdown(); clientMap.put("Cluster-" + member.getAddress(), client); when(client.getConnectionType()).thenReturn(ConnectionType.GRPC); } - @AfterClass - public static void tearDown() throws NacosException { - Map clientMap = (Map) ReflectionTestUtils - .getField(RpcClientFactory.class, "CLIENT_MAP"); - clientMap.remove("Cluster-1.1.1.1:-1").shutdown(); - } - @Test - public void testSendRequest() { + void testSendRequest() { try { Response response = clusterRpcClientProxy.sendRequest(member, new HealthCheckRequest()); } catch (NacosException e) { - Assert.assertEquals(-401, e.getErrCode()); + assertEquals(-401, e.getErrCode()); } catch (Exception e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } @Test - public void testAsyncRequest() { + void testAsyncRequest() { RequestCallBack requestCallBack = new RequestCallBack() { @Override public Executor getExecutor() { @@ -127,49 +130,49 @@ public void onResponse(Response response) { @Override public void onException(Throwable e) { - Assert.assertTrue(e instanceof NacosException); + assertTrue(e instanceof NacosException); } }; try { clusterRpcClientProxy.asyncRequest(member, new HealthCheckRequest(), requestCallBack); } catch (NacosException e) { - Assert.assertEquals(500, e.getErrCode()); + assertEquals(500, e.getErrCode()); } } @Test - public void testSendRequestToAllMembers() { + void testSendRequestToAllMembers() { try { clusterRpcClientProxy.sendRequestToAllMembers(new HealthCheckRequest()); } catch (NacosException e) { - Assert.assertEquals(-401, e.getErrCode()); + assertEquals(-401, e.getErrCode()); } } @Test - public void testOnEvent() { + void testOnEvent() { try { clusterRpcClientProxy.onEvent(MembersChangeEvent.builder().build()); } catch (Exception e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } @Test - public void testIsRunningForClientConnected() { + void testIsRunningForClientConnected() { when(client.isRunning()).thenReturn(true); assertTrue(clusterRpcClientProxy.isRunning(member)); } @Test - public void testIsRunningForClientNotConnected() { + void testIsRunningForClientNotConnected() { assertFalse(clusterRpcClientProxy.isRunning(member)); } @Test - public void testIsRunningForNonExist() { + void testIsRunningForNonExist() { Member member = new Member(); member.setIp("11.11.11.11"); assertFalse(clusterRpcClientProxy.isRunning(member)); diff --git a/core/src/test/java/com/alibaba/nacos/core/code/condition/ParamRequestConditionTest.java b/core/src/test/java/com/alibaba/nacos/core/code/condition/ParamRequestConditionTest.java index 3cc52aa80d5..56433752154 100644 --- a/core/src/test/java/com/alibaba/nacos/core/code/condition/ParamRequestConditionTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/code/condition/ParamRequestConditionTest.java @@ -17,39 +17,42 @@ package com.alibaba.nacos.core.code.condition; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + /** * {@link ParamRequestCondition} unit test. * * @author chenglu * @date 2021-07-06 11:56 */ -public class ParamRequestConditionTest { +class ParamRequestConditionTest { private ParamRequestCondition paramRequestCondition; - @Before - public void setUp() { + @BeforeEach + void setUp() { paramRequestCondition = new ParamRequestCondition("test=1244"); } @Test - public void testGetExpressions() { - Assert.assertEquals(1, paramRequestCondition.getExpressions().size()); + void testGetExpressions() { + assertEquals(1, paramRequestCondition.getExpressions().size()); } @Test - public void testGetMatchingCondition() { + void testGetMatchingCondition() { MockHttpServletRequest request = new MockHttpServletRequest(); ParamRequestCondition paramRequestCondition1 = paramRequestCondition.getMatchingCondition(request); - Assert.assertNull(paramRequestCondition1); + assertNull(paramRequestCondition1); request.setParameter("test", "1244"); ParamRequestCondition paramRequestCondition2 = paramRequestCondition.getMatchingCondition(request); - Assert.assertNotNull(paramRequestCondition2); + assertNotNull(paramRequestCondition2); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/code/condition/PathRequestConditionTest.java b/core/src/test/java/com/alibaba/nacos/core/code/condition/PathRequestConditionTest.java index 3a1749a3f04..b9e949bb32a 100644 --- a/core/src/test/java/com/alibaba/nacos/core/code/condition/PathRequestConditionTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/code/condition/PathRequestConditionTest.java @@ -17,10 +17,10 @@ package com.alibaba.nacos.core.code.condition; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static com.alibaba.nacos.sys.env.Constants.REQUEST_PATH_SEPARATOR; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link PathRequestCondition} unit test. @@ -28,11 +28,11 @@ * @author chenglu * @date 2021-07-06 16:37 */ -public class PathRequestConditionTest { +class PathRequestConditionTest { @Test - public void testPathRequestCondition() { + void testPathRequestCondition() { PathRequestCondition pathRequestCondition = new PathRequestCondition("method" + REQUEST_PATH_SEPARATOR + "path"); - Assert.assertTrue(pathRequestCondition.toString().contains("path")); + assertTrue(pathRequestCondition.toString().contains("path")); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/config/DistroModuleStateBuilderTest.java b/core/src/test/java/com/alibaba/nacos/core/config/DistroModuleStateBuilderTest.java index ee48cb6e639..74803b60856 100644 --- a/core/src/test/java/com/alibaba/nacos/core/config/DistroModuleStateBuilderTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/config/DistroModuleStateBuilderTest.java @@ -20,37 +20,37 @@ import com.alibaba.nacos.core.distributed.distro.DistroConstants; import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.module.ModuleState; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.mock.env.MockEnvironment; import java.util.Map; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * distro module state builder test. + * * @author 985492783@qq.com * @date 2023/4/7 23:51 */ -public class DistroModuleStateBuilderTest { +class DistroModuleStateBuilderTest { private ConfigurableEnvironment environment; - @Before - public void setUp() { + @BeforeEach + void setUp() { environment = new MockEnvironment(); EnvUtil.setEnvironment(environment); } @Test - public void testBuild() { + void testBuild() { ModuleState actual = new DistroModuleStateBuilder().build(); Map states = actual.getStates(); assertEquals(DistroConstants.DISTRO_MODULE, actual.getModuleName()); - assertEquals(DistroConstants.DEFAULT_DATA_SYNC_DELAY_MILLISECONDS, - states.get(DistroConstants.DATA_SYNC_DELAY_MILLISECONDS_STATE)); + assertEquals(DistroConstants.DEFAULT_DATA_SYNC_DELAY_MILLISECONDS, states.get(DistroConstants.DATA_SYNC_DELAY_MILLISECONDS_STATE)); assertEquals(DistroConstants.DEFAULT_DATA_SYNC_TIMEOUT_MILLISECONDS, states.get(DistroConstants.DATA_SYNC_TIMEOUT_MILLISECONDS_STATE)); assertEquals(DistroConstants.DEFAULT_DATA_SYNC_RETRY_DELAY_MILLISECONDS, diff --git a/core/src/test/java/com/alibaba/nacos/core/config/ModuleStateClusterTest.java b/core/src/test/java/com/alibaba/nacos/core/config/ModuleStateClusterTest.java index 0d02a76caa4..5cbf63eeaf9 100644 --- a/core/src/test/java/com/alibaba/nacos/core/config/ModuleStateClusterTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/config/ModuleStateClusterTest.java @@ -21,29 +21,30 @@ import com.alibaba.nacos.core.distributed.raft.RaftSysConstants; import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.module.ModuleStateHolder; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.mock.env.MockEnvironment; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * standalone module-state-builder test. + * * @author 985492783@qq.com * @date 2023/4/8 0:17 */ -public class ModuleStateClusterTest { +class ModuleStateClusterTest { private ConfigurableEnvironment environment; - + private ModuleStateHolder moduleStateHolder; - @Before - public void setUp() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { + @BeforeEach + void setUp() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { environment = new MockEnvironment(); EnvUtil.setEnvironment(environment); EnvUtil.setIsStandalone(false); @@ -53,7 +54,7 @@ public void setUp() throws NoSuchMethodException, InvocationTargetException, Ins } @Test - public void testStandaloneBuilder() { + void testStandaloneBuilder() { assertTrue(moduleStateHolder.getModuleState(DistroConstants.DISTRO_MODULE).isPresent()); assertTrue(moduleStateHolder.getModuleState(RaftSysConstants.RAFT_STATE).isPresent()); } diff --git a/core/src/test/java/com/alibaba/nacos/core/config/ModuleStateStandaloneTest.java b/core/src/test/java/com/alibaba/nacos/core/config/ModuleStateStandaloneTest.java index 9759452898f..f0f8fd1ee8f 100644 --- a/core/src/test/java/com/alibaba/nacos/core/config/ModuleStateStandaloneTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/config/ModuleStateStandaloneTest.java @@ -21,7 +21,7 @@ import com.alibaba.nacos.core.distributed.raft.RaftSysConstants; import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.module.ModuleStateHolder; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.springframework.core.env.ConfigurableEnvironment; @@ -30,7 +30,7 @@ import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * cluster module-state-builder test. @@ -38,15 +38,14 @@ * @author 985492783@qq.com * @date 2023/4/8 0:13 */ -public class ModuleStateStandaloneTest { +class ModuleStateStandaloneTest { private ConfigurableEnvironment environment; private ModuleStateHolder moduleStateHolder; @Test - public void testStandaloneBuilder() - throws InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException { + void testStandaloneBuilder() throws InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException { try (MockedStatic mockedStatic = Mockito.mockStatic(EnvUtil.class)) { environment = new MockEnvironment(); mockedStatic.when(EnvUtil::getEnvironment).thenReturn(environment); diff --git a/core/src/test/java/com/alibaba/nacos/core/config/RaftModuleStateBuilderTest.java b/core/src/test/java/com/alibaba/nacos/core/config/RaftModuleStateBuilderTest.java index 055bfebdd33..964ad24a9bb 100644 --- a/core/src/test/java/com/alibaba/nacos/core/config/RaftModuleStateBuilderTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/config/RaftModuleStateBuilderTest.java @@ -20,33 +20,34 @@ import com.alibaba.nacos.core.distributed.raft.RaftSysConstants; import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.module.ModuleState; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.mock.env.MockEnvironment; import java.util.Map; -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; /** * raft module state builder test. + * * @author 985492783@qq.com * @date 2023/4/8 0:18 */ -public class RaftModuleStateBuilderTest { +class RaftModuleStateBuilderTest { private ConfigurableEnvironment environment; - @Before - public void setUp() { + @BeforeEach + void setUp() { environment = new MockEnvironment(); EnvUtil.setEnvironment(environment); } @Test - public void testBuild() { + void testBuild() { ModuleState actual = new RaftModuleStateBuilder().build(); Map states = actual.getStates(); assertEquals(RaftSysConstants.RAFT_STATE, actual.getModuleName()); diff --git a/core/src/test/java/com/alibaba/nacos/core/context/RequestContextHolderTest.java b/core/src/test/java/com/alibaba/nacos/core/context/RequestContextHolderTest.java new file mode 100644 index 00000000000..38074cc9402 --- /dev/null +++ b/core/src/test/java/com/alibaba/nacos/core/context/RequestContextHolderTest.java @@ -0,0 +1,43 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.context; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class RequestContextHolderTest { + + @AfterEach + void tearDown() { + RequestContextHolder.removeContext(); + } + + @Test + void testGetContext() { + long timestamp = System.currentTimeMillis(); + RequestContext requestContext = RequestContextHolder.getContext(); + assertNotNull(requestContext); + assertNotNull(requestContext.getRequestId()); + assertTrue(requestContext.getRequestTimestamp() >= timestamp); + assertNotNull(requestContext.getBasicContext()); + assertNotNull(requestContext.getEngineContext()); + assertNotNull(requestContext.getAuthContext()); + } +} \ No newline at end of file diff --git a/core/src/test/java/com/alibaba/nacos/core/context/RequestContextTest.java b/core/src/test/java/com/alibaba/nacos/core/context/RequestContextTest.java new file mode 100644 index 00000000000..4392f7f653c --- /dev/null +++ b/core/src/test/java/com/alibaba/nacos/core/context/RequestContextTest.java @@ -0,0 +1,60 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.context; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +class RequestContextTest { + + long requestTimestamp; + + RequestContext requestContext; + + @BeforeEach + void setUp() { + requestTimestamp = System.currentTimeMillis(); + requestContext = new RequestContext(requestTimestamp); + } + + @Test + public void testGetRequestId() { + String requestId = requestContext.getRequestId(); + assertNotNull(requestId); + assertNotNull(UUID.fromString(requestId)); + requestContext.setRequestId("testRequestId"); + assertEquals("testRequestId", requestContext.getRequestId()); + } + + @Test + public void testGetRequestTimestamp() { + assertEquals(requestTimestamp, requestContext.getRequestTimestamp()); + } + + @Test + public void testSetExtensionContext() { + assertNull(requestContext.getExtensionContext("testKey")); + requestContext.addExtensionContext("testKey", "testValue"); + assertEquals("testValue", requestContext.getExtensionContext("testKey")); + } +} \ No newline at end of file diff --git a/core/src/test/java/com/alibaba/nacos/core/context/addition/AddressContextTest.java b/core/src/test/java/com/alibaba/nacos/core/context/addition/AddressContextTest.java new file mode 100644 index 00000000000..ce123f3e0cd --- /dev/null +++ b/core/src/test/java/com/alibaba/nacos/core/context/addition/AddressContextTest.java @@ -0,0 +1,68 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.context.addition; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class AddressContextTest { + + AddressContext addressContext; + + @BeforeEach + void setUp() { + addressContext = new AddressContext(); + } + + @Test + void testSetSourceIp() { + assertNull(addressContext.getSourceIp()); + addressContext.setSourceIp("127.0.0.1"); + assertEquals("127.0.0.1", addressContext.getSourceIp()); + } + + @Test + void testSetSourcePort() { + assertEquals(0, addressContext.getSourcePort()); + addressContext.setSourcePort(8080); + assertEquals(8080, addressContext.getSourcePort()); + } + + @Test + void testSetRemoteIp() { + assertNull(addressContext.getRemoteIp()); + addressContext.setRemoteIp("127.0.0.1"); + assertEquals("127.0.0.1", addressContext.getRemoteIp()); + } + + @Test + void testSetRemotePort() { + assertEquals(0, addressContext.getRemotePort()); + addressContext.setRemotePort(8080); + assertEquals(8080, addressContext.getRemotePort()); + } + + @Test + void testSetHost() { + assertNull(addressContext.getHost()); + addressContext.setHost("127.0.0.1"); + assertEquals("127.0.0.1", addressContext.getHost()); + } +} \ No newline at end of file diff --git a/core/src/test/java/com/alibaba/nacos/core/context/addition/AuthContextTest.java b/core/src/test/java/com/alibaba/nacos/core/context/addition/AuthContextTest.java new file mode 100644 index 00000000000..972749994fb --- /dev/null +++ b/core/src/test/java/com/alibaba/nacos/core/context/addition/AuthContextTest.java @@ -0,0 +1,61 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.context.addition; + +import com.alibaba.nacos.plugin.auth.api.IdentityContext; +import com.alibaba.nacos.plugin.auth.api.Resource; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Properties; + +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class AuthContextTest { + + AuthContext authContext; + + @BeforeEach + void setUp() { + authContext = new AuthContext(); + } + + @Test + void testSetIdentityContext() { + IdentityContext identityContext = new IdentityContext(); + assertNull(authContext.getIdentityContext()); + authContext.setIdentityContext(identityContext); + assertSame(identityContext, authContext.getIdentityContext()); + } + + @Test + void testSetResource() { + Resource resource = new Resource("", "", "", "", new Properties()); + assertNull(authContext.getResource()); + authContext.setResource(resource); + assertSame(resource, authContext.getResource()); + } + + @Test + void testSetAuthResult() { + assertNull(authContext.getAuthResult()); + authContext.setAuthResult(true); + assertTrue((boolean) authContext.getAuthResult()); + } +} \ No newline at end of file diff --git a/core/src/test/java/com/alibaba/nacos/core/context/addition/BasicContextTest.java b/core/src/test/java/com/alibaba/nacos/core/context/addition/BasicContextTest.java new file mode 100644 index 00000000000..90430f900e6 --- /dev/null +++ b/core/src/test/java/com/alibaba/nacos/core/context/addition/BasicContextTest.java @@ -0,0 +1,81 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.context.addition; + +import com.alibaba.nacos.api.common.Constants; +import com.alibaba.nacos.api.naming.remote.request.InstanceRequest; +import com.alibaba.nacos.common.utils.VersionUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +class BasicContextTest { + + BasicContext basicContext; + + @BeforeEach + void setUp() { + basicContext = new BasicContext(); + } + + @Test + void testGetAddressContext() { + assertNotNull(basicContext.getAddressContext()); + } + + @Test + void testSetUserAgent() { + assertNull(basicContext.getUserAgent()); + basicContext.setUserAgent(VersionUtils.getFullClientVersion()); + assertEquals(VersionUtils.getFullClientVersion(), basicContext.getUserAgent()); + } + + @Test + void testSetRequestProtocol() { + assertNull(basicContext.getRequestProtocol()); + basicContext.setRequestProtocol(BasicContext.HTTP_PROTOCOL); + assertEquals(BasicContext.HTTP_PROTOCOL, basicContext.getRequestProtocol()); + basicContext.setRequestProtocol(BasicContext.GRPC_PROTOCOL); + assertEquals(BasicContext.GRPC_PROTOCOL, basicContext.getRequestProtocol()); + } + + @Test + void testSetRequestTarget() { + assertNull(basicContext.getRequestTarget()); + basicContext.setRequestTarget("POST /v2/ns/instance"); + assertEquals("POST /v2/ns/instance", basicContext.getRequestTarget()); + basicContext.setRequestTarget(InstanceRequest.class.getSimpleName()); + assertEquals(InstanceRequest.class.getSimpleName(), basicContext.getRequestTarget()); + } + + @Test + void testSetApp() { + assertEquals("unknown", basicContext.getApp()); + basicContext.setApp("testApp"); + assertEquals("testApp", basicContext.getApp()); + } + + @Test + void testSetEncoding() { + assertEquals(Constants.ENCODE, basicContext.getEncoding()); + basicContext.setEncoding("GBK"); + assertEquals("GBK", basicContext.getEncoding()); + } +} \ No newline at end of file diff --git a/core/src/test/java/com/alibaba/nacos/core/context/addition/EngineContextTest.java b/core/src/test/java/com/alibaba/nacos/core/context/addition/EngineContextTest.java new file mode 100644 index 00000000000..b1a1e27c820 --- /dev/null +++ b/core/src/test/java/com/alibaba/nacos/core/context/addition/EngineContextTest.java @@ -0,0 +1,50 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.context.addition; + +import com.alibaba.nacos.common.utils.VersionUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class EngineContextTest { + + EngineContext engineContext; + + @BeforeEach + void setUp() { + engineContext = new EngineContext(); + } + + @Test + void testSetVersion() { + assertEquals(VersionUtils.version, engineContext.getVersion()); + engineContext.setVersion("testVersion"); + assertEquals("testVersion", engineContext.getVersion()); + } + + @Test + void testSetContext() { + assertNull(engineContext.getContext("test")); + assertEquals("default", engineContext.getContext("test", "default")); + engineContext.setContext("test", "testValue"); + assertEquals("testValue", engineContext.getContext("test")); + assertEquals("testValue", engineContext.getContext("test", "default")); + } +} \ No newline at end of file diff --git a/core/src/test/java/com/alibaba/nacos/core/context/remote/HttpRequestContextConfigTest.java b/core/src/test/java/com/alibaba/nacos/core/context/remote/HttpRequestContextConfigTest.java new file mode 100644 index 00000000000..998778215a6 --- /dev/null +++ b/core/src/test/java/com/alibaba/nacos/core/context/remote/HttpRequestContextConfigTest.java @@ -0,0 +1,36 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.context.remote; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.web.servlet.FilterRegistrationBean; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class HttpRequestContextConfigTest { + + @Test + void testRequestContextFilterRegistration() { + HttpRequestContextConfig contextConfig = new HttpRequestContextConfig(); + HttpRequestContextFilter filter = contextConfig.nacosRequestContextFilter(); + FilterRegistrationBean actual = contextConfig.requestContextFilterRegistration( + filter); + assertEquals(filter, actual.getFilter()); + assertEquals("/*", actual.getUrlPatterns().iterator().next()); + assertEquals(Integer.MIN_VALUE, actual.getOrder()); + } +} \ No newline at end of file diff --git a/core/src/test/java/com/alibaba/nacos/core/context/remote/HttpRequestContextFilterTest.java b/core/src/test/java/com/alibaba/nacos/core/context/remote/HttpRequestContextFilterTest.java new file mode 100644 index 00000000000..4664fd8afd3 --- /dev/null +++ b/core/src/test/java/com/alibaba/nacos/core/context/remote/HttpRequestContextFilterTest.java @@ -0,0 +1,152 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.context.remote; + +import com.alibaba.nacos.common.constant.HttpHeaderConsts; +import com.alibaba.nacos.core.context.RequestContext; +import com.alibaba.nacos.core.context.RequestContextHolder; +import com.alibaba.nacos.core.context.addition.BasicContext; +import org.apache.http.HttpHeaders; +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.jupiter.MockitoExtension; +import org.opentest4j.AssertionFailedError; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.Servlet; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class HttpRequestContextFilterTest { + + @Mock + private MockHttpServletRequest servletRequest; + + @Mock + private MockHttpServletResponse servletResponse; + + @Mock + private Servlet servlet; + + HttpRequestContextFilter filter; + + @BeforeEach + void setUp() { + filter = new HttpRequestContextFilter(); + RequestContextHolder.getContext(); + when(servletRequest.getHeader(HttpHeaders.HOST)).thenReturn("localhost"); + when(servletRequest.getHeader(HttpHeaders.USER_AGENT)).thenReturn("Nacos-Java-Client:v1.4.7"); + when(servletRequest.getHeader(HttpHeaderConsts.APP_FILED)).thenReturn("testApp"); + when(servletRequest.getMethod()).thenReturn("GET"); + when(servletRequest.getRequestURI()).thenReturn("/test/path"); + when(servletRequest.getCharacterEncoding()).thenReturn("GBK"); + when(servletRequest.getRemoteAddr()).thenReturn("1.1.1.1"); + when(servletRequest.getRemotePort()).thenReturn(3306); + when(servletRequest.getHeader("X-Forwarded-For")).thenReturn("2.2.2.2"); + } + + @AfterEach + void tearDown() { + RequestContextHolder.removeContext(); + } + + @Test + public void testDoFilterSetsCorrectContextValues() throws Exception { + MockNextFilter nextFilter = new MockNextFilter("testApp", "GBK"); + filter.doFilter(servletRequest, servletResponse, new MockFilterChain(servlet, nextFilter)); + if (null != nextFilter.error) { + throw nextFilter.error; + } + } + + @Test + public void testDoFilterWithoutEncoding() throws Exception { + when(servletRequest.getCharacterEncoding()).thenReturn(""); + MockNextFilter nextFilter = new MockNextFilter("testApp", "UTF-8"); + filter.doFilter(servletRequest, servletResponse, new MockFilterChain(servlet, nextFilter)); + if (null != nextFilter.error) { + throw nextFilter.error; + } + } + + @Test + public void testGetAppNameWithFallback() throws Exception { + when(servletRequest.getHeader(HttpHeaderConsts.APP_FILED)).thenReturn(""); + MockNextFilter nextFilter = new MockNextFilter("unknown", "GBK"); + filter.doFilter(servletRequest, servletResponse, new MockFilterChain(servlet, nextFilter)); + if (null != nextFilter.error) { + throw nextFilter.error; + } + } + + private static class MockNextFilter implements Filter { + + private final String app; + + private final String encoding; + + AssertionError error; + + public MockNextFilter(String app, String encoding) { + this.app = app; + this.encoding = encoding; + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + Filter.super.init(filterConfig); + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) + throws IOException, ServletException { + try { + RequestContext requestContext = RequestContextHolder.getContext(); + BasicContext basicContext = requestContext.getBasicContext(); + assertEquals("GET /test/path", basicContext.getRequestTarget()); + assertEquals(encoding, basicContext.getEncoding()); + assertEquals("Nacos-Java-Client:v1.4.7", basicContext.getUserAgent()); + assertEquals(app, basicContext.getApp()); + assertEquals("1.1.1.1", basicContext.getAddressContext().getRemoteIp()); + assertEquals("2.2.2.2", basicContext.getAddressContext().getSourceIp()); + assertEquals(3306, basicContext.getAddressContext().getRemotePort()); + assertEquals("localhost", basicContext.getAddressContext().getHost()); + } catch (AssertionFailedError error) { + this.error = error; + } + } + + @Override + public void destroy() { + Filter.super.destroy(); + } + } +} \ No newline at end of file diff --git a/core/src/test/java/com/alibaba/nacos/core/control/http/NacosHttpTpsFilterTest.java b/core/src/test/java/com/alibaba/nacos/core/control/http/NacosHttpTpsFilterTest.java index b3f2968681f..944c5775ddf 100644 --- a/core/src/test/java/com/alibaba/nacos/core/control/http/NacosHttpTpsFilterTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/control/http/NacosHttpTpsFilterTest.java @@ -26,14 +26,14 @@ import com.alibaba.nacos.plugin.control.tps.request.TpsCheckRequest; import com.alibaba.nacos.plugin.control.tps.response.TpsCheckResponse; import org.apache.catalina.core.AsyncContextImpl; -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.MockedStatic; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; @@ -48,14 +48,8 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class NacosHttpTpsFilterTest { - - @Mock - private ControlManagerCenter controlManagerCenter; - - @Mock - private TpsControlManager tpsControlManager; +@ExtendWith(MockitoExtension.class) +class NacosHttpTpsFilterTest { NacosHttpTpsFilter nacosHttpTpsFilter; @@ -64,18 +58,23 @@ public class NacosHttpTpsFilterTest { @Mock ControllerMethodsCache controllerMethodsCache; - @Before - public void before() { + @Mock + private ControlManagerCenter controlManagerCenter; + + @Mock + private TpsControlManager tpsControlManager; + + @BeforeEach + void before() { controlManagerCenterMockedStatic = Mockito.mockStatic(ControlManagerCenter.class); - controlManagerCenterMockedStatic.when(() -> ControlManagerCenter.getInstance()) - .thenReturn(controlManagerCenter); + controlManagerCenterMockedStatic.when(() -> ControlManagerCenter.getInstance()).thenReturn(controlManagerCenter); when(controlManagerCenter.getTpsControlManager()).thenReturn(tpsControlManager); nacosHttpTpsFilter = new NacosHttpTpsFilter(controllerMethodsCache); } - @After - public void after() { + @AfterEach + void after() { controlManagerCenterMockedStatic.close(); } @@ -83,7 +82,7 @@ public void after() { * test tps check passed ,response is null. */ @Test - public void testPass() throws Exception { + void testPass() throws Exception { HttpTpsCheckRequestParserRegistry.register(new HttpTpsCheckRequestParser() { @Override public TpsCheckRequest parse(HttpServletRequest httpServletRequest) { @@ -106,7 +105,7 @@ public String getName() { //mock http tps control method Method method = HealthCheckRequestHandler.class.getMethod("handle", Request.class, RequestMeta.class); - + MockHttpServletRequest httpServletRequest = Mockito.mock(MockHttpServletRequest.class); MockHttpServletResponse httpServletResponse = Mockito.mock(MockHttpServletResponse.class); MockFilterChain filterChain = Mockito.mock(MockFilterChain.class); @@ -124,7 +123,7 @@ public String getName() { * test tps check rejected ,response is not null. */ @Test - public void testRejected() throws Exception { + void testRejected() throws Exception { HttpTpsCheckRequestParserRegistry.register(new HttpTpsCheckRequestParser() { @Override public TpsCheckRequest parse(HttpServletRequest httpServletRequest) { @@ -147,7 +146,7 @@ public String getName() { //mock http tps control method Method method = HealthCheckRequestHandler.class.getMethod("handle", Request.class, RequestMeta.class); - + MockHttpServletRequest httpServletRequest = Mockito.mock(MockHttpServletRequest.class); MockHttpServletResponse httpServletResponse = Mockito.mock(MockHttpServletResponse.class); MockFilterChain filterChain = Mockito.mock(MockFilterChain.class); @@ -168,7 +167,7 @@ public String getName() { * test tps check exception ,return null skip. */ @Test - public void testTpsCheckException() throws Exception { + void testTpsCheckException() throws Exception { HttpTpsCheckRequestParserRegistry.register(new HttpTpsCheckRequestParser() { @Override public TpsCheckRequest parse(HttpServletRequest httpServletRequest) { diff --git a/core/src/test/java/com/alibaba/nacos/core/control/remote/TpsControlRequestFilterTest.java b/core/src/test/java/com/alibaba/nacos/core/control/remote/TpsControlRequestFilterTest.java index cd3f561c303..6301235a4b1 100644 --- a/core/src/test/java/com/alibaba/nacos/core/control/remote/TpsControlRequestFilterTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/control/remote/TpsControlRequestFilterTest.java @@ -28,20 +28,26 @@ import com.alibaba.nacos.plugin.control.tps.TpsControlManager; import com.alibaba.nacos.plugin.control.tps.request.TpsCheckRequest; import com.alibaba.nacos.plugin.control.tps.response.TpsCheckResponse; -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 static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.any; -@RunWith(MockitoJUnitRunner.class) -public class TpsControlRequestFilterTest { +@ExtendWith(MockitoExtension.class) +class TpsControlRequestFilterTest { + + TpsControlRequestFilter tpsControlRequestFilter; + + MockedStatic controlManagerCenterMockedStatic; @Mock private ControlManagerCenter controlManagerCenter; @@ -49,22 +55,17 @@ public class TpsControlRequestFilterTest { @Mock private TpsControlManager tpsControlManager; - TpsControlRequestFilter tpsControlRequestFilter; - - MockedStatic controlManagerCenterMockedStatic; - - @Before - public void before() { + @BeforeEach + void before() { tpsControlRequestFilter = new TpsControlRequestFilter(); controlManagerCenterMockedStatic = Mockito.mockStatic(ControlManagerCenter.class); - controlManagerCenterMockedStatic.when(() -> ControlManagerCenter.getInstance()) - .thenReturn(controlManagerCenter); + controlManagerCenterMockedStatic.when(() -> ControlManagerCenter.getInstance()).thenReturn(controlManagerCenter); Mockito.when(controlManagerCenter.getTpsControlManager()).thenReturn(tpsControlManager); } - @After - public void after() { + @AfterEach + void after() { controlManagerCenterMockedStatic.close(); } @@ -72,7 +73,7 @@ public void after() { * test tps check passed ,response is null. */ @Test - public void testPass() { + void testPass() { RemoteTpsCheckRequestParserRegistry.register(new RemoteTpsCheckRequestParser() { @Override public TpsCheckRequest parse(Request request, RequestMeta meta) { @@ -93,38 +94,35 @@ public String getName() { RequestMeta requestMeta = new RequestMeta(); TpsCheckResponse tpsCheckResponse = new TpsCheckResponse(true, 200, "success"); Mockito.when(tpsControlManager.check(any(TpsCheckRequest.class))).thenReturn(tpsCheckResponse); - Response filterResponse = tpsControlRequestFilter.filter(healthCheckRequest, requestMeta, - HealthCheckRequestHandler.class); - Assert.assertNull(filterResponse); + Response filterResponse = tpsControlRequestFilter.filter(healthCheckRequest, requestMeta, HealthCheckRequestHandler.class); + assertNull(filterResponse); } /** * test tps check rejected ,response is not null. */ @Test - public void testRejected() { + void testRejected() { HealthCheckRequest healthCheckRequest = new HealthCheckRequest(); RequestMeta requestMeta = new RequestMeta(); TpsCheckResponse tpsCheckResponse = new TpsCheckResponse(false, 5031, "rejected"); Mockito.when(tpsControlManager.check(any(TpsCheckRequest.class))).thenReturn(tpsCheckResponse); - Response filterResponse = tpsControlRequestFilter.filter(healthCheckRequest, requestMeta, - HealthCheckRequestHandler.class); - Assert.assertNotNull(filterResponse); - Assert.assertEquals(NacosException.OVER_THRESHOLD, filterResponse.getErrorCode()); - Assert.assertEquals("Tps Flow restricted:" + tpsCheckResponse.getMessage(), filterResponse.getMessage()); + Response filterResponse = tpsControlRequestFilter.filter(healthCheckRequest, requestMeta, HealthCheckRequestHandler.class); + assertNotNull(filterResponse); + assertEquals(NacosException.OVER_THRESHOLD, filterResponse.getErrorCode()); + assertEquals("Tps Flow restricted:" + tpsCheckResponse.getMessage(), filterResponse.getMessage()); } /** * test tps check exception ,return null skip. */ @Test - public void testTpsCheckException() { + void testTpsCheckException() { HealthCheckRequest healthCheckRequest = new HealthCheckRequest(); RequestMeta requestMeta = new RequestMeta(); Mockito.when(tpsControlManager.check(any(TpsCheckRequest.class))).thenThrow(new NacosRuntimeException(12345)); - Response filterResponse = tpsControlRequestFilter.filter(healthCheckRequest, requestMeta, - HealthCheckRequestHandler.class); - Assert.assertNull(filterResponse); + Response filterResponse = tpsControlRequestFilter.filter(healthCheckRequest, requestMeta, HealthCheckRequestHandler.class); + assertNull(filterResponse); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/controller/CoreOpsControllerTest.java b/core/src/test/java/com/alibaba/nacos/core/controller/CoreOpsControllerTest.java index f9d8faab5e2..d9dce09cd02 100644 --- a/core/src/test/java/com/alibaba/nacos/core/controller/CoreOpsControllerTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/controller/CoreOpsControllerTest.java @@ -25,27 +25,28 @@ import com.alibaba.nacos.core.distributed.id.IdGeneratorManager; import com.alibaba.nacos.core.distributed.id.SnowFlowerIdGenerator; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.env.MockEnvironment; import java.util.HashMap; import java.util.Map; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * {@link CoreOpsController} unit test. * * @author chenglu * @date 2021-07-07 22:20 */ -@RunWith(MockitoJUnitRunner.class) -public class CoreOpsControllerTest { +@ExtendWith(MockitoExtension.class) +class CoreOpsControllerTest { @InjectMocks private CoreOpsController coreOpsController; @@ -56,36 +57,36 @@ public class CoreOpsControllerTest { @Mock private IdGeneratorManager idGeneratorManager; - @Before - public void setUp() { + @BeforeEach + void setUp() { EnvUtil.setEnvironment(new MockEnvironment()); } @Test - public void testRaftOps() { + void testRaftOps() { Mockito.when(protocolManager.getCpProtocol()).thenAnswer(invocationOnMock -> { CPProtocol cpProtocol = Mockito.mock(CPProtocol.class); Mockito.when(cpProtocol.execute(Mockito.anyMap())).thenReturn(RestResultUtils.success("res")); return cpProtocol; }); - + RestResult result = coreOpsController.raftOps(new HashMap<>()); - Assert.assertEquals("res", result.getData()); + assertEquals("res", result.getData()); } @Test - public void testIdInfo() { + void testIdInfo() { Map idGeneratorMap = new HashMap<>(); idGeneratorMap.put("1", new SnowFlowerIdGenerator()); Mockito.when(idGeneratorManager.getGeneratorMap()).thenReturn(idGeneratorMap); - + RestResult>> res = coreOpsController.idInfo(); - Assert.assertEquals(2, res.getData().get("1").size()); + assertEquals(2, res.getData().get("1").size()); } @Test - public void testSetLogLevel() { + void testSetLogLevel() { String res = coreOpsController.setLogLevel("1", "info"); - Assert.assertEquals("200", res); + assertEquals("200", res); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/controller/NacosClusterControllerTest.java b/core/src/test/java/com/alibaba/nacos/core/controller/NacosClusterControllerTest.java index bc4eeab1471..9f7be753a28 100644 --- a/core/src/test/java/com/alibaba/nacos/core/controller/NacosClusterControllerTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/controller/NacosClusterControllerTest.java @@ -23,14 +23,13 @@ import com.alibaba.nacos.core.cluster.NodeState; import com.alibaba.nacos.core.cluster.ServerMemberManager; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.env.MockEnvironment; import java.util.Arrays; @@ -38,7 +37,9 @@ import java.util.Collections; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link NacosClusterController} unit test. @@ -46,8 +47,8 @@ * @author chenglu * @date 2021-07-07 22:53 */ -@RunWith(MockitoJUnitRunner.class) -public class NacosClusterControllerTest { +@ExtendWith(MockitoExtension.class) +class NacosClusterControllerTest { @InjectMocks private NacosClusterController nacosClusterController; @@ -55,13 +56,13 @@ public class NacosClusterControllerTest { @Mock private ServerMemberManager serverMemberManager; - @Before - public void setUp() { + @BeforeEach + void setUp() { EnvUtil.setEnvironment(new MockEnvironment()); } @Test - public void testSelf() { + void testSelf() { Member self = new Member(); Mockito.when(serverMemberManager.getSelf()).thenReturn(self); @@ -70,7 +71,7 @@ public void testSelf() { } @Test - public void testListNodes() { + void testListNodes() { Member member1 = new Member(); member1.setIp("1.1.1.1"); List members = Arrays.asList(member1); @@ -81,7 +82,7 @@ public void testListNodes() { } @Test - public void testListSimpleNodes() { + void testListSimpleNodes() { Mockito.when(serverMemberManager.getMemberAddressInfos()).thenReturn(Collections.singleton("1.1.1.1")); RestResult> result = nacosClusterController.listSimpleNodes(); @@ -89,7 +90,7 @@ public void testListSimpleNodes() { } @Test - public void testGetHealth() { + void testGetHealth() { Member self = new Member(); self.setState(NodeState.UP); Mockito.when(serverMemberManager.getSelf()).thenReturn(self); @@ -99,7 +100,7 @@ public void testGetHealth() { } @Test - public void testReport() { + void testReport() { Member self = new Member(); Mockito.when(serverMemberManager.update(Mockito.any())).thenReturn(true); Mockito.when(serverMemberManager.getSelf()).thenReturn(self); @@ -113,15 +114,15 @@ public void testReport() { } @Test - public void testSwitchLookup() { + void testSwitchLookup() { RestResult result = nacosClusterController.switchLookup("test"); - Assert.assertTrue(result.ok()); + assertTrue(result.ok()); } @Test - public void testLeave() throws Exception { + void testLeave() throws Exception { RestResult result = nacosClusterController.leave(Collections.singletonList("1.1.1.1"), true); - Assert.assertFalse(result.ok()); + assertFalse(result.ok()); assertEquals(405, result.getCode()); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/controller/ServerLoaderControllerTest.java b/core/src/test/java/com/alibaba/nacos/core/controller/ServerLoaderControllerTest.java index 1070be06c4f..279153720e8 100644 --- a/core/src/test/java/com/alibaba/nacos/core/controller/ServerLoaderControllerTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/controller/ServerLoaderControllerTest.java @@ -18,8 +18,8 @@ package com.alibaba.nacos.core.controller; import com.alibaba.nacos.api.ability.ServerAbilities; -import com.alibaba.nacos.api.remote.ability.ServerRemoteAbility; import com.alibaba.nacos.api.exception.NacosException; +import com.alibaba.nacos.api.remote.ability.ServerRemoteAbility; import com.alibaba.nacos.api.remote.response.ServerLoaderInfoResponse; import com.alibaba.nacos.core.cluster.Member; import com.alibaba.nacos.core.cluster.ServerMemberManager; @@ -29,13 +29,12 @@ import com.alibaba.nacos.core.remote.core.ServerLoaderInfoRequestHandler; import com.alibaba.nacos.core.remote.core.ServerReloaderRequestHandler; import com.alibaba.nacos.sys.env.EnvUtil; -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.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.ResponseEntity; import org.springframework.mock.env.MockEnvironment; import org.springframework.mock.web.MockHttpServletRequest; @@ -44,14 +43,16 @@ import java.util.HashMap; import java.util.Map; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * {@link ServerLoaderController} unit test. * * @author chenglu * @date 2021-07-07 23:10 */ -@RunWith(MockitoJUnitRunner.class) -public class ServerLoaderControllerTest { +@ExtendWith(MockitoExtension.class) +class ServerLoaderControllerTest { @InjectMocks private ServerLoaderController serverLoaderController; @@ -72,21 +73,21 @@ public class ServerLoaderControllerTest { private ServerLoaderInfoRequestHandler serverLoaderInfoRequestHandler; @Test - public void testCurrentClients() { + void testCurrentClients() { Mockito.when(connectionManager.currentClients()).thenReturn(new HashMap<>()); - + ResponseEntity> result = serverLoaderController.currentClients(); - Assert.assertEquals(0, result.getBody().size()); + assertEquals(0, result.getBody().size()); } @Test - public void testReloadCount() { + void testReloadCount() { ResponseEntity result = serverLoaderController.reloadCount(1, "1.1.1.1"); - Assert.assertEquals("success", result.getBody()); + assertEquals("success", result.getBody()); } @Test - public void testSmartReload() throws NacosException { + void testSmartReload() throws NacosException { EnvUtil.setEnvironment(new MockEnvironment()); Member member = new Member(); member.setIp("1.1.1.1"); @@ -97,31 +98,31 @@ public void testSmartReload() throws NacosException { serverAbilities.setRemoteAbility(serverRemoteAbility); member.setAbilities(serverAbilities); Mockito.when(serverMemberManager.allMembersWithoutSelf()).thenReturn(Collections.singletonList(member)); - + Map metrics = new HashMap<>(); metrics.put("conCount", "1"); metrics.put("sdkConCount", "1"); ServerLoaderInfoResponse serverLoaderInfoResponse = new ServerLoaderInfoResponse(); serverLoaderInfoResponse.setLoaderMetrics(metrics); Mockito.when(serverLoaderInfoRequestHandler.handle(Mockito.any(), Mockito.any())).thenReturn(serverLoaderInfoResponse); - + Mockito.when(serverMemberManager.getSelf()).thenReturn(member); - + MockHttpServletRequest httpServletRequest = new MockHttpServletRequest(); ResponseEntity result = serverLoaderController.smartReload(httpServletRequest, "1", null); - Assert.assertEquals("Ok", result.getBody()); + assertEquals("Ok", result.getBody()); } @Test - public void testReloadSingle() { + void testReloadSingle() { ResponseEntity result = serverLoaderController.reloadSingle("111", "1.1.1.1"); - Assert.assertEquals("success", result.getBody()); + assertEquals("success", result.getBody()); } @Test - public void testLoaderMetrics() throws NacosException { + void testLoaderMetrics() throws NacosException { EnvUtil.setEnvironment(new MockEnvironment()); Member member = new Member(); member.setIp("1.1.1.1"); @@ -132,7 +133,7 @@ public void testLoaderMetrics() throws NacosException { serverAbilities.setRemoteAbility(serverRemoteAbility); member.setAbilities(serverAbilities); Mockito.when(serverMemberManager.allMembersWithoutSelf()).thenReturn(Collections.singletonList(member)); - + Map metrics = new HashMap<>(); metrics.put("conCount", "1"); ServerLoaderInfoResponse serverLoaderInfoResponse = new ServerLoaderInfoResponse(); @@ -142,6 +143,6 @@ public void testLoaderMetrics() throws NacosException { Mockito.when(serverMemberManager.getSelf()).thenReturn(member); ResponseEntity> result = serverLoaderController.loaderMetrics(); - Assert.assertEquals(9, result.getBody().size()); + assertEquals(9, result.getBody().size()); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/controller/v2/CoreOpsV2ControllerTest.java b/core/src/test/java/com/alibaba/nacos/core/controller/v2/CoreOpsV2ControllerTest.java index d3ecfaf6c34..6fe9acb7da8 100644 --- a/core/src/test/java/com/alibaba/nacos/core/controller/v2/CoreOpsV2ControllerTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/controller/v2/CoreOpsV2ControllerTest.java @@ -28,22 +28,26 @@ import com.alibaba.nacos.core.model.vo.IdGeneratorVO; import com.alibaba.nacos.core.utils.Loggers; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.env.MockEnvironment; import java.util.HashMap; import java.util.List; import java.util.Map; -@RunWith(MockitoJUnitRunner.class) -public class CoreOpsV2ControllerTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@ExtendWith(MockitoExtension.class) +class CoreOpsV2ControllerTest { + + private final MockEnvironment mockEnvironment = new MockEnvironment(); @InjectMocks private CoreOpsV2Controller coreOpsV2Controller; @@ -54,15 +58,13 @@ public class CoreOpsV2ControllerTest { @Mock private IdGeneratorManager idGeneratorManager; - private final MockEnvironment mockEnvironment = new MockEnvironment(); - - @Before - public void setUp() { + @BeforeEach + void setUp() { EnvUtil.setEnvironment(mockEnvironment); } @Test - public void testRaftOps() { + void testRaftOps() { Mockito.when(protocolManager.getCpProtocol()).thenAnswer(invocationOnMock -> { CPProtocol cpProtocol = Mockito.mock(CPProtocol.class); Mockito.when(cpProtocol.execute(Mockito.anyMap())).thenReturn(RestResultUtils.success("res")); @@ -70,33 +72,33 @@ public void testRaftOps() { }); RestResult result = coreOpsV2Controller.raftOps(new HashMap<>()); - Assert.assertEquals("res", result.getData()); + assertEquals("res", result.getData()); } @Test - public void testIdInfo() { + void testIdInfo() { mockEnvironment.setProperty("nacos.core.snowflake.worker-id", "1"); Map idGeneratorMap = new HashMap<>(); idGeneratorMap.put("resource", new SnowFlowerIdGenerator()); Mockito.when(idGeneratorManager.getGeneratorMap()).thenReturn(idGeneratorMap); RestResult> res = coreOpsV2Controller.ids(); - - Assert.assertTrue(res.ok()); - Assert.assertEquals(1, res.getData().size()); - Assert.assertEquals("resource", res.getData().get(0).getResource()); - Assert.assertEquals(1L, res.getData().get(0).getInfo().getWorkerId().longValue()); - Assert.assertEquals(0L, res.getData().get(0).getInfo().getCurrentId().longValue()); + + assertTrue(res.ok()); + assertEquals(1, res.getData().size()); + assertEquals("resource", res.getData().get(0).getResource()); + assertEquals(1L, res.getData().get(0).getInfo().getWorkerId().longValue()); + assertEquals(0L, res.getData().get(0).getInfo().getCurrentId().longValue()); } @Test - public void testSetLogLevel() { + void testSetLogLevel() { LogUpdateRequest request = new LogUpdateRequest(); request.setLogName("core"); request.setLogLevel("debug"); RestResult res = coreOpsV2Controller.updateLog(request); - - Assert.assertTrue(res.ok()); - Assert.assertTrue(Loggers.CORE.isDebugEnabled()); + + assertTrue(res.ok()); + assertTrue(Loggers.CORE.isDebugEnabled()); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/controller/v2/NacosClusterControllerV2Test.java b/core/src/test/java/com/alibaba/nacos/core/controller/v2/NacosClusterControllerV2Test.java index 5936c4211ab..ee3f184d6b4 100644 --- a/core/src/test/java/com/alibaba/nacos/core/controller/v2/NacosClusterControllerV2Test.java +++ b/core/src/test/java/com/alibaba/nacos/core/controller/v2/NacosClusterControllerV2Test.java @@ -27,14 +27,13 @@ import com.alibaba.nacos.core.model.request.LookupUpdateRequest; import com.alibaba.nacos.core.service.NacosClusterOperationService; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.env.MockEnvironment; import java.util.Arrays; @@ -42,14 +41,17 @@ import java.util.Collections; import java.util.List; -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.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class NacosClusterControllerV2Test { +@ExtendWith(MockitoExtension.class) +class NacosClusterControllerV2Test { + + private final MockEnvironment environment = new MockEnvironment(); @InjectMocks private NacosClusterControllerV2 nacosClusterControllerV2; @@ -57,16 +59,14 @@ public class NacosClusterControllerV2Test { @Mock private NacosClusterOperationService nacosClusterOperationService; - private final MockEnvironment environment = new MockEnvironment(); - - @Before - public void setUp() { + @BeforeEach + void setUp() { nacosClusterControllerV2 = new NacosClusterControllerV2(nacosClusterOperationService); EnvUtil.setEnvironment(environment); } @Test - public void testSelf() { + void testSelf() { Member self = new Member(); when(nacosClusterOperationService.self()).thenReturn(self); @@ -76,7 +76,7 @@ public void testSelf() { } @Test - public void testListNodes() throws NacosException { + void testListNodes() throws NacosException { Member member1 = new Member(); member1.setIp("1.1.1.1"); member1.setPort(8848); @@ -95,7 +95,7 @@ public void testListNodes() throws NacosException { } @Test - public void testSelfHealth() { + void testSelfHealth() { String selfHealth = "UP"; when(nacosClusterOperationService.selfHealth()).thenReturn(selfHealth); @@ -105,7 +105,7 @@ public void testSelfHealth() { } @Test - public void testUpdate() throws NacosApiException { + void testUpdate() throws NacosApiException { Member member = new Member(); member.setIp("1.1.1.1"); member.setPort(8848); @@ -114,11 +114,11 @@ public void testUpdate() throws NacosApiException { Result result = nacosClusterControllerV2.updateNodes(Collections.singletonList(member)); verify(nacosClusterOperationService).updateNodes(any()); assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode()); - assertEquals(true, result.getData()); + assertTrue(result.getData()); } @Test - public void testSwitchLookup() throws NacosException { + void testSwitchLookup() throws NacosException { LookupUpdateRequest request = new LookupUpdateRequest(); request.setType("test"); @@ -126,13 +126,13 @@ public void testSwitchLookup() throws NacosException { Result result = nacosClusterControllerV2.updateLookup(request); verify(nacosClusterOperationService).updateLookup(any()); assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode()); - assertEquals(true, result.getData()); + assertTrue(result.getData()); } @Test - public void testLeave() throws Exception { + void testLeave() throws Exception { RestResult result = nacosClusterControllerV2.deleteNodes(Collections.singletonList("1.1.1.1")); - Assert.assertFalse(result.ok()); - Assert.assertEquals(405, result.getCode()); + assertFalse(result.ok()); + assertEquals(405, result.getCode()); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/distributed/distro/DistroConfigTest.java b/core/src/test/java/com/alibaba/nacos/core/distributed/distro/DistroConfigTest.java index 92d01976ab6..7232d1043bd 100644 --- a/core/src/test/java/com/alibaba/nacos/core/distributed/distro/DistroConfigTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/distributed/distro/DistroConfigTest.java @@ -19,17 +19,16 @@ import com.alibaba.nacos.common.event.ServerConfigChangeEvent; import com.alibaba.nacos.common.notify.NotifyCenter; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.mock.env.MockEnvironment; import java.lang.reflect.Constructor; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class DistroConfigTest { +class DistroConfigTest { private DistroConfig distroConfig; @@ -45,38 +44,38 @@ public class DistroConfigTest { private long loadDataRetryDelayMillis = 80000L; - @Before - public void setUp() { + @BeforeEach + void setUp() { EnvUtil.setEnvironment(new MockEnvironment()); distroConfig = DistroConfig.getInstance(); } @Test - public void testSetSyncDelayMillis() { + void testSetSyncDelayMillis() { distroConfig.setSyncDelayMillis(syncDelayMillis); assertEquals(syncDelayMillis, distroConfig.getSyncDelayMillis()); } @Test - public void testSetSyncRetryDelayMillis() { + void testSetSyncRetryDelayMillis() { distroConfig.setSyncRetryDelayMillis(syncRetryDelayMillis); assertEquals(syncRetryDelayMillis, distroConfig.getSyncRetryDelayMillis()); } @Test - public void testSetVerifyIntervalMillis() { + void testSetVerifyIntervalMillis() { distroConfig.setVerifyIntervalMillis(verifyIntervalMillis); assertEquals(verifyIntervalMillis, distroConfig.getVerifyIntervalMillis()); } @Test - public void testSetLoadDataRetryDelayMillis() { + void testSetLoadDataRetryDelayMillis() { distroConfig.setLoadDataRetryDelayMillis(loadDataRetryDelayMillis); assertEquals(loadDataRetryDelayMillis, distroConfig.getLoadDataRetryDelayMillis()); } @Test - public void testUpgradeConfig() throws InterruptedException { + void testUpgradeConfig() throws InterruptedException { assertEquals(DistroConstants.DEFAULT_DATA_SYNC_DELAY_MILLISECONDS, distroConfig.getSyncDelayMillis()); MockEnvironment environment = new MockEnvironment(); environment.setProperty(DistroConstants.DATA_SYNC_DELAY_MILLISECONDS, String.valueOf(syncDelayMillis)); @@ -87,7 +86,7 @@ public void testUpgradeConfig() throws InterruptedException { } @Test - public void testInitConfigFormEnv() throws ReflectiveOperationException { + void testInitConfigFormEnv() throws ReflectiveOperationException { MockEnvironment environment = new MockEnvironment(); EnvUtil.setEnvironment(environment); environment.setProperty(DistroConstants.DATA_SYNC_DELAY_MILLISECONDS, String.valueOf(syncDelayMillis)); @@ -100,13 +99,13 @@ public void testInitConfigFormEnv() throws ReflectiveOperationException { Constructor declaredConstructor = DistroConfig.class.getDeclaredConstructor(); declaredConstructor.setAccessible(true); DistroConfig distroConfig = declaredConstructor.newInstance(); - - Assert.assertEquals(distroConfig.getSyncDelayMillis(), syncDelayMillis); - Assert.assertEquals(distroConfig.getSyncTimeoutMillis(), syncTimeoutMillis); - Assert.assertEquals(distroConfig.getSyncRetryDelayMillis(), syncRetryDelayMillis); - Assert.assertEquals(distroConfig.getVerifyIntervalMillis(), verifyIntervalMillis); - Assert.assertEquals(distroConfig.getVerifyTimeoutMillis(), verifyTimeoutMillis); - Assert.assertEquals(distroConfig.getLoadDataRetryDelayMillis(), loadDataRetryDelayMillis); + + assertEquals(distroConfig.getSyncDelayMillis(), syncDelayMillis); + assertEquals(distroConfig.getSyncTimeoutMillis(), syncTimeoutMillis); + assertEquals(distroConfig.getSyncRetryDelayMillis(), syncRetryDelayMillis); + assertEquals(distroConfig.getVerifyIntervalMillis(), verifyIntervalMillis); + assertEquals(distroConfig.getVerifyTimeoutMillis(), verifyTimeoutMillis); + assertEquals(distroConfig.getLoadDataRetryDelayMillis(), loadDataRetryDelayMillis); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/distributed/distro/component/DistroComponentHolderTest.java b/core/src/test/java/com/alibaba/nacos/core/distributed/distro/component/DistroComponentHolderTest.java index 5901c7629f1..5896ee32de8 100644 --- a/core/src/test/java/com/alibaba/nacos/core/distributed/distro/component/DistroComponentHolderTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/distributed/distro/component/DistroComponentHolderTest.java @@ -16,17 +16,17 @@ package com.alibaba.nacos.core.distributed.distro.component; -import junit.framework.TestCase; -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 static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class DistroComponentHolderTest extends TestCase { +@ExtendWith(MockitoExtension.class) +class DistroComponentHolderTest { private final String type = "com.alibaba.nacos.naming.iplist."; @@ -44,8 +44,8 @@ public class DistroComponentHolderTest extends TestCase { @Mock private DistroDataProcessor distroDataProcessor; - @Before - public void setUp() { + @BeforeEach + void setUp() { componentHolder = new DistroComponentHolder(); componentHolder.registerDataStorage(type, distroDataStorage); componentHolder.registerTransportAgent(type, distroTransportAgent); @@ -55,30 +55,30 @@ public void setUp() { } @Test - public void testFindTransportAgent() { + void testFindTransportAgent() { DistroTransportAgent distroTransportAgent = componentHolder.findTransportAgent(type); assertEquals(this.distroTransportAgent, distroTransportAgent); } @Test - public void testFindDataStorage() { + void testFindDataStorage() { DistroDataStorage distroDataStorage = componentHolder.findDataStorage(type); assertEquals(this.distroDataStorage, distroDataStorage); } @Test - public void testGetDataStorageTypes() { + void testGetDataStorageTypes() { componentHolder.getDataStorageTypes(); } @Test - public void testFindFailedTaskHandler() { + void testFindFailedTaskHandler() { DistroFailedTaskHandler distroFailedTaskHandler = componentHolder.findFailedTaskHandler(type); assertEquals(this.distroFailedTaskHandler, distroFailedTaskHandler); } @Test - public void testFindDataProcessor() { + void testFindDataProcessor() { DistroDataProcessor distroDataProcessor = componentHolder.findDataProcessor(type); assertEquals(this.distroDataProcessor, distroDataProcessor); } diff --git a/core/src/test/java/com/alibaba/nacos/core/distributed/distro/entity/DistroDataTest.java b/core/src/test/java/com/alibaba/nacos/core/distributed/distro/entity/DistroDataTest.java index ac21924262e..18a362fd286 100644 --- a/core/src/test/java/com/alibaba/nacos/core/distributed/distro/entity/DistroDataTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/distributed/distro/entity/DistroDataTest.java @@ -17,31 +17,32 @@ package com.alibaba.nacos.core.distributed.distro.entity; import com.alibaba.nacos.consistency.DataOperation; -import junit.framework.TestCase; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class DistroDataTest extends TestCase { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class DistroDataTest { + + private final String type = "com.alibaba.nacos.naming.iplist."; private DistroData distroData; private DistroKey distroKey; - private final String type = "com.alibaba.nacos.naming.iplist."; - private int contentSize = 10; private final byte[] content = new byte[contentSize]; - @Before - public void setUp() { + @BeforeEach + void setUp() { distroKey = new DistroKey("checksum", type); distroData = new DistroData(distroKey, content); distroData.setType(DataOperation.VERIFY); } @Test - public void testGetters() { + void testGetters() { assertEquals(distroKey, distroData.getDistroKey()); assertEquals(content, distroData.getContent()); assertEquals(DataOperation.VERIFY, distroData.getType()); diff --git a/core/src/test/java/com/alibaba/nacos/core/distributed/distro/entity/DistroKeyTest.java b/core/src/test/java/com/alibaba/nacos/core/distributed/distro/entity/DistroKeyTest.java index 56497cae04c..5e99b3c3af0 100644 --- a/core/src/test/java/com/alibaba/nacos/core/distributed/distro/entity/DistroKeyTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/distributed/distro/entity/DistroKeyTest.java @@ -16,11 +16,12 @@ package com.alibaba.nacos.core.distributed.distro.entity; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class DistroKeyTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class DistroKeyTest { private final String type = "com.alibaba.nacos.naming.iplist."; @@ -32,8 +33,8 @@ public class DistroKeyTest { private DistroKey distroKey2; - @Before - public void setUp() { + @BeforeEach + void setUp() { distroKey1 = new DistroKey(resourceKey, type, targetServer); distroKey2 = new DistroKey(); distroKey2.setResourceKey(resourceKey); @@ -42,15 +43,15 @@ public void setUp() { } @Test - public void testGetters() { - Assert.assertEquals(distroKey2.getResourceKey(), resourceKey); - Assert.assertEquals(distroKey2.getResourceType(), type); - Assert.assertEquals(distroKey2.getTargetServer(), targetServer); - + void testGetters() { + assertEquals(distroKey2.getResourceKey(), resourceKey); + assertEquals(distroKey2.getResourceType(), type); + assertEquals(distroKey2.getTargetServer(), targetServer); + } @Test - public void testEquals() { - Assert.assertEquals(distroKey1, distroKey2); + void testEquals() { + assertEquals(distroKey1, distroKey2); } } \ No newline at end of file diff --git a/core/src/test/java/com/alibaba/nacos/core/distributed/distro/monitor/DistroRecordsHolderTest.java b/core/src/test/java/com/alibaba/nacos/core/distributed/distro/monitor/DistroRecordsHolderTest.java index acb5bd689d9..ec77a6700b8 100644 --- a/core/src/test/java/com/alibaba/nacos/core/distributed/distro/monitor/DistroRecordsHolderTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/distributed/distro/monitor/DistroRecordsHolderTest.java @@ -16,18 +16,18 @@ package com.alibaba.nacos.core.distributed.distro.monitor; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Optional; -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 DistroRecordsHolderTest { +class DistroRecordsHolderTest { @Test - public void testGetRecordIfExist() { + void testGetRecordIfExist() { Optional actual = DistroRecordsHolder.getInstance().getRecordIfExist("testGetRecordIfExist"); assertFalse(actual.isPresent()); DistroRecordsHolder.getInstance().getRecord("testGetRecordIfExist"); @@ -36,21 +36,21 @@ public void testGetRecordIfExist() { } @Test - public void testGetTotalSyncCount() { + void testGetTotalSyncCount() { long expected = DistroRecordsHolder.getInstance().getTotalSyncCount() + 1; DistroRecordsHolder.getInstance().getRecord("testGetTotalSyncCount").syncSuccess(); assertEquals(expected, DistroRecordsHolder.getInstance().getTotalSyncCount()); } @Test - public void testGetSuccessfulSyncCount() { + void testGetSuccessfulSyncCount() { long expected = DistroRecordsHolder.getInstance().getSuccessfulSyncCount() + 1; DistroRecordsHolder.getInstance().getRecord("testGetSuccessfulSyncCount").syncSuccess(); assertEquals(expected, DistroRecordsHolder.getInstance().getSuccessfulSyncCount()); } @Test - public void testGetFailedSyncCount() { + void testGetFailedSyncCount() { DistroRecordsHolder.getInstance().getRecord("testGetFailedSyncCount"); Optional actual = DistroRecordsHolder.getInstance().getRecordIfExist("testGetFailedSyncCount"); assertTrue(actual.isPresent()); @@ -61,7 +61,7 @@ public void testGetFailedSyncCount() { } @Test - public void testGetFailedVerifyCount() { + void testGetFailedVerifyCount() { DistroRecordsHolder.getInstance().getRecord("testGetFailedVerifyCount"); Optional actual = DistroRecordsHolder.getInstance().getRecordIfExist("testGetFailedVerifyCount"); assertTrue(actual.isPresent()); diff --git a/core/src/test/java/com/alibaba/nacos/core/distributed/distro/task/load/DistroLoadDataTaskTest.java b/core/src/test/java/com/alibaba/nacos/core/distributed/distro/task/load/DistroLoadDataTaskTest.java index 9591475e0a7..7181b644785 100644 --- a/core/src/test/java/com/alibaba/nacos/core/distributed/distro/task/load/DistroLoadDataTaskTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/distributed/distro/task/load/DistroLoadDataTaskTest.java @@ -27,13 +27,12 @@ import com.alibaba.nacos.core.distributed.distro.component.DistroTransportAgent; import com.alibaba.nacos.core.distributed.distro.entity.DistroData; import com.alibaba.nacos.sys.env.EnvUtil; -import junit.framework.TestCase; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.env.MockEnvironment; import org.springframework.test.util.ReflectionTestUtils; @@ -41,12 +40,14 @@ import java.util.List; import java.util.Map; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class DistroLoadDataTaskTest extends TestCase { +@ExtendWith(MockitoExtension.class) +class DistroLoadDataTaskTest { private final String type = "com.alibaba.nacos.naming.iplist."; @@ -78,13 +79,13 @@ public class DistroLoadDataTaskTest extends TestCase { @Mock private DistroCallback loadCallback; - @BeforeClass - public static void setUpBeforeClass() { + @BeforeAll + static void setUpBeforeClass() { EnvUtil.setEnvironment(new MockEnvironment()); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { List memberList = new LinkedList<>(); memberList.add(Member.builder().ip("2.2.2.2").port(8848).build()); memberList.add(Member.builder().ip("1.1.1.1").port(8848).build()); @@ -101,10 +102,9 @@ public void setUp() throws Exception { } @Test - public void testRun() { + void testRun() { distroLoadDataTask.run(); - Map loadCompletedMap = (Map) ReflectionTestUtils - .getField(distroLoadDataTask, "loadCompletedMap"); + Map loadCompletedMap = (Map) ReflectionTestUtils.getField(distroLoadDataTask, "loadCompletedMap"); assertNotNull(loadCompletedMap); assertTrue(loadCompletedMap.containsKey(type)); verify(distroTransportAgent).getDatumSnapshot(any(String.class)); diff --git a/core/src/test/java/com/alibaba/nacos/core/distributed/id/SnowFlowerInstanceIdGeneratorTest.java b/core/src/test/java/com/alibaba/nacos/core/distributed/id/SnowFlowerInstanceIdGeneratorTest.java index 0014015a714..a87fe6dfef5 100644 --- a/core/src/test/java/com/alibaba/nacos/core/distributed/id/SnowFlowerInstanceIdGeneratorTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/distributed/id/SnowFlowerInstanceIdGeneratorTest.java @@ -17,24 +17,24 @@ package com.alibaba.nacos.core.distributed.id; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.env.StandardEnvironment; import java.util.stream.IntStream; -public class SnowFlowerInstanceIdGeneratorTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +class SnowFlowerInstanceIdGeneratorTest { + @Test - public void nextId() { + void nextId() { EnvUtil.setEnvironment(new StandardEnvironment()); SnowFlowerIdGenerator generator = new SnowFlowerIdGenerator(); generator.initialize(1); - - long count = IntStream.range(0, 10).mapToObj(i -> generator.nextId()) - .distinct().count(); - - Assert.assertEquals(10, count); + + long count = IntStream.range(0, 10).mapToObj(i -> generator.nextId()).distinct().count(); + + assertEquals(10, count); } } \ No newline at end of file diff --git a/core/src/test/java/com/alibaba/nacos/core/distributed/raft/JRaftProtocolTest.java b/core/src/test/java/com/alibaba/nacos/core/distributed/raft/JRaftProtocolTest.java index 966f3f0b72e..e53dd5e43b8 100644 --- a/core/src/test/java/com/alibaba/nacos/core/distributed/raft/JRaftProtocolTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/distributed/raft/JRaftProtocolTest.java @@ -22,12 +22,13 @@ import com.alibaba.nacos.core.cluster.ServerMemberManager; import com.alipay.sofa.jraft.Node; import com.google.protobuf.Message; -import junit.framework.TestCase; -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.HashSet; @@ -40,8 +41,10 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class JRaftProtocolTest extends TestCase { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class JRaftProtocolTest { @Mock private JRaftServer serverMock; @@ -66,16 +69,15 @@ public class JRaftProtocolTest extends TestCase { private String groupId; - @Before - public void setUp() throws Exception { - super.setUp(); + @BeforeEach + void setUp() throws Exception { raftProtocol = new JRaftProtocol(memberManager); ReadRequest.Builder readRequestBuilder = ReadRequest.newBuilder(); readRequest = readRequestBuilder.build(); WriteRequest.Builder writeRequestBuilder = WriteRequest.newBuilder(); writeRequest = writeRequestBuilder.build(); - + Field raftServerField = JRaftProtocol.class.getDeclaredField("raftServer"); raftServerField.setAccessible(true); raftServerField.set(raftProtocol, serverMock); @@ -86,32 +88,32 @@ public void setUp() throws Exception { when(serverMock.get(readRequest)).thenReturn(futureMock); when(serverMock.commit(any(String.class), any(Message.class), any(CompletableFuture.class))).thenReturn(futureMock); - + groupId = "test_group"; when(serverMock.findNodeByGroup(groupId)).thenReturn(nodeMock); } @Test - public void testGetData() throws Exception { + void testGetData() throws Exception { raftProtocol.getData(readRequest); verify(serverMock).get(readRequest); } @Test - public void testWrite() throws Exception { + void testWrite() throws Exception { raftProtocol.write(writeRequest); verify(serverMock).commit(any(String.class), eq(writeRequest), any(CompletableFuture.class)); } @Test - public void testMemberChange() { + void testMemberChange() { Set addresses = new HashSet<>(); raftProtocol.memberChange(addresses); verify(serverMock, times(5)).peerChange(jRaftMaintainService, addresses); } @Test - public void testIsLeader() { + void testIsLeader() { raftProtocol.isLeader(groupId); verify(serverMock).findNodeByGroup(groupId); verify(nodeMock).isLeader(); diff --git a/core/src/test/java/com/alibaba/nacos/core/distributed/raft/JRaftServerTest.java b/core/src/test/java/com/alibaba/nacos/core/distributed/raft/JRaftServerTest.java index 996c0a9b9f7..30eedeb556c 100644 --- a/core/src/test/java/com/alibaba/nacos/core/distributed/raft/JRaftServerTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/distributed/raft/JRaftServerTest.java @@ -16,43 +16,43 @@ package com.alibaba.nacos.core.distributed.raft; +import com.alibaba.nacos.common.model.RestResult; +import com.alibaba.nacos.common.model.RestResultUtils; import com.alibaba.nacos.consistency.RequestProcessor; import com.alibaba.nacos.consistency.cp.RequestProcessor4CP; import com.alibaba.nacos.consistency.entity.ReadRequest; import com.alibaba.nacos.consistency.entity.Response; import com.alibaba.nacos.consistency.entity.WriteRequest; +import com.alibaba.nacos.core.cluster.Member; +import com.alibaba.nacos.core.distributed.ProtocolManager; import com.alibaba.nacos.core.distributed.raft.utils.FailoverClosure; +import com.alibaba.nacos.sys.env.EnvUtil; import com.alipay.sofa.jraft.CliService; import com.alipay.sofa.jraft.Node; import com.alipay.sofa.jraft.RaftGroupService; +import com.alipay.sofa.jraft.RouteTable; +import com.alipay.sofa.jraft.Status; +import com.alipay.sofa.jraft.conf.Configuration; import com.alipay.sofa.jraft.core.NodeImpl; import com.alipay.sofa.jraft.core.State; +import com.alipay.sofa.jraft.entity.PeerId; import com.alipay.sofa.jraft.error.RemotingException; +import com.alipay.sofa.jraft.rpc.CliRequests; import com.alipay.sofa.jraft.rpc.InvokeCallback; import com.alipay.sofa.jraft.rpc.RpcClient; +import com.alipay.sofa.jraft.rpc.impl.FutureImpl; import com.alipay.sofa.jraft.rpc.impl.cli.CliClientServiceImpl; import com.alipay.sofa.jraft.util.Endpoint; - -import com.alibaba.nacos.common.model.RestResult; -import com.alibaba.nacos.common.model.RestResultUtils; -import com.alibaba.nacos.core.cluster.Member; -import com.alibaba.nacos.core.distributed.ProtocolManager; -import com.alibaba.nacos.sys.env.EnvUtil; -import com.alipay.sofa.jraft.RouteTable; -import com.alipay.sofa.jraft.Status; -import com.alipay.sofa.jraft.conf.Configuration; -import com.alipay.sofa.jraft.entity.PeerId; -import com.alipay.sofa.jraft.rpc.CliRequests; -import com.alipay.sofa.jraft.rpc.impl.FutureImpl; import com.google.protobuf.Message; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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 org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.mock.env.MockEnvironment; import java.lang.reflect.Field; @@ -70,6 +70,8 @@ import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; +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.ArgumentMatchers.eq; import static org.mockito.Mockito.never; @@ -77,8 +79,12 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class JRaftServerTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class JRaftServerTest { + + private final String groupId = "test_group"; private PeerId peerId1; @@ -88,18 +94,11 @@ public class JRaftServerTest { private Configuration conf; - private final String groupId = "test_group"; - private JRaftServer server; @Mock private RequestProcessor4CP mockProcessor4CP; - @BeforeClass - public static void beforeClass() { - EnvUtil.setEnvironment(new MockEnvironment()); - } - @Mock private CliClientServiceImpl cliClientServiceMock; @@ -116,18 +115,23 @@ public static void beforeClass() { @Mock private Node node; - + @Mock private RequestProcessor requestProcessor; - + @Mock private RaftGroupService raftGroupService; - + @Mock private NacosStateMachine nacosStateMachine; - @Before - public void before() throws NoSuchFieldException, IllegalAccessException { + @BeforeAll + static void beforeClass() { + EnvUtil.setEnvironment(new MockEnvironment()); + } + + @BeforeEach + void before() throws NoSuchFieldException, IllegalAccessException { initPeersAndConfiguration(); RaftConfig config = new RaftConfig(); Collection initEvent = Collections.singletonList(Member.builder().ip("1.1.1.1").port(7848).build()); @@ -154,7 +158,7 @@ boolean peerChange(JRaftMaintainService maintainService, Set newPeers) { Field cliClientServiceField = JRaftServer.class.getDeclaredField("cliClientService"); cliClientServiceField.setAccessible(true); cliClientServiceField.set(server, cliClientServiceMock); - + // Inject the mocked cliServiceMock into server. Field cliServiceField = JRaftServer.class.getDeclaredField("cliService"); cliServiceField.setAccessible(true); @@ -212,13 +216,13 @@ private void setLeaderAs(PeerId peerId) { } @Test - public void testInvokeToLeader() + void testInvokeToLeader() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, RemotingException, InterruptedException { when(cliClientServiceMock.getRpcClient()).thenReturn(rpcClient); setLeaderAs(peerId1); int timeout = 3000; - Method invokeToLeaderMethod = JRaftServer.class.getDeclaredMethod("invokeToLeader", - String.class, Message.class, int.class, FailoverClosure.class); + Method invokeToLeaderMethod = JRaftServer.class.getDeclaredMethod("invokeToLeader", String.class, Message.class, int.class, + FailoverClosure.class); invokeToLeaderMethod.setAccessible(true); invokeToLeaderMethod.invoke(server, groupId, this.readRequest, timeout, null); verify(cliClientServiceMock).getRpcClient(); @@ -226,17 +230,17 @@ public void testInvokeToLeader() } @Test - public void testRefreshRouteTable() { + void testRefreshRouteTable() { server.refreshRouteTable(groupId); verify(cliClientServiceMock, times(1)).connect(peerId1.getEndpoint()); verify(cliClientServiceMock).getLeader(eq(peerId1.getEndpoint()), any(CliRequests.GetLeaderRequest.class), eq(null)); } @Test - public void testCommit() throws NoSuchFieldException, IllegalAccessException, TimeoutException, InterruptedException { + void testCommit() throws NoSuchFieldException, IllegalAccessException, TimeoutException, InterruptedException { WriteRequest.Builder writeRequestBuilder = WriteRequest.newBuilder(); WriteRequest writeRequest = writeRequestBuilder.build(); - + // No group is set, and make sure that an IllegalArgumentException will be thrown. CompletableFuture future = server.commit(groupId, writeRequest, this.future); verify(future).completeExceptionally(any(IllegalArgumentException.class)); @@ -254,10 +258,10 @@ public void testCommit() throws NoSuchFieldException, IllegalAccessException, Ti Field stateField = NodeImpl.class.getDeclaredField("state"); stateField.setAccessible(true); stateField.set(node, State.STATE_LEADER); - + server.commit(groupId, writeRequest, future); verify(cliClientServiceMock, never()).getRpcClient(); - + // make the node follower and verify the invokeToLeader is called. node = (NodeImpl) server.findNodeByGroup(groupId); stateField.setAccessible(true); @@ -269,14 +273,14 @@ public void testCommit() throws NoSuchFieldException, IllegalAccessException, Ti } @Test - public void testRegisterSelfToCluster() { + void testRegisterSelfToCluster() { PeerId selfPeerId = new PeerId("4.4.4.4", 8080); server.registerSelfToCluster(groupId, selfPeerId, conf); verify(cliServiceMock).addPeer(groupId, conf, selfPeerId); } @Test - public void testPeerChange() { + void testPeerChange() { AtomicBoolean changed = new AtomicBoolean(false); JRaftMaintainService service = new JRaftMaintainService(server) { @@ -291,38 +295,37 @@ public RestResult execute(Map args) { Member.builder().ip("127.0.0.1").port(80).build(), Member.builder().ip("127.0.0.2").port(81).build(), Member.builder().ip("127.0.0.3").port(82).build()); server.peerChange(service, ProtocolManager.toCPMembersInfo(firstEvent)); - Assert.assertFalse(changed.get()); + assertFalse(changed.get()); changed.set(false); Collection secondEvent = Arrays.asList(Member.builder().ip("1.1.1.1").port(7848).build(), Member.builder().ip("127.0.0.1").port(80).build(), Member.builder().ip("127.0.0.2").port(81).build(), Member.builder().ip("127.0.0.4").port(83).build()); server.peerChange(service, ProtocolManager.toCPMembersInfo(secondEvent)); - Assert.assertTrue(changed.get()); + assertTrue(changed.get()); changed.set(false); Collection thirdEvent = Arrays.asList(Member.builder().ip("1.1.1.1").port(7848).build(), - Member.builder().ip("127.0.0.2").port(81).build(), - Member.builder().ip("127.0.0.5").port(82).build()); + Member.builder().ip("127.0.0.2").port(81).build(), Member.builder().ip("127.0.0.5").port(82).build()); server.peerChange(service, ProtocolManager.toCPMembersInfo(thirdEvent)); - Assert.assertTrue(changed.get()); + assertTrue(changed.get()); changed.set(false); Collection fourEvent = Arrays.asList(Member.builder().ip("1.1.1.1").port(7848).build(), Member.builder().ip("127.0.0.1").port(80).build()); server.peerChange(service, ProtocolManager.toCPMembersInfo(fourEvent)); - Assert.assertTrue(changed.get()); + assertTrue(changed.get()); changed.set(false); Collection fiveEvent = Arrays.asList(Member.builder().ip("1.1.1.1").port(7848).build(), Member.builder().ip("127.0.0.1").port(80).build(), Member.builder().ip("127.0.0.3").port(81).build()); server.peerChange(service, ProtocolManager.toCPMembersInfo(fiveEvent)); - Assert.assertFalse(changed.get()); + assertFalse(changed.get()); changed.set(false); } - @After - public void shutdown() { + @AfterEach + void shutdown() { server.shutdown(); } diff --git a/core/src/test/java/com/alibaba/nacos/core/distributed/raft/processor/AbstractProcessorTest.java b/core/src/test/java/com/alibaba/nacos/core/distributed/raft/processor/AbstractProcessorTest.java index 968f377856c..89279e20dc4 100644 --- a/core/src/test/java/com/alibaba/nacos/core/distributed/raft/processor/AbstractProcessorTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/distributed/raft/processor/AbstractProcessorTest.java @@ -27,24 +27,26 @@ import com.alipay.sofa.jraft.rpc.Connection; import com.alipay.sofa.jraft.rpc.RpcContext; import com.google.protobuf.Message; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.atomic.AtomicReference; -public class AbstractProcessorTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class AbstractProcessorTest { private JRaftServer server = new JRaftServer() { @Override public void applyOperation(Node node, Message data, FailoverClosure closure) { - closure.setResponse( - Response.newBuilder().setSuccess(false).setErrMsg("Error message transmission").build()); + closure.setResponse(Response.newBuilder().setSuccess(false).setErrMsg("Error message transmission").build()); closure.run(new Status(RaftError.UNKNOWN, "Error message transmission")); } }; @Test - public void testErrorThroughRpc() { + void testErrorThroughRpc() { final AtomicReference reference = new AtomicReference<>(); RpcContext context = new RpcContext() { @@ -67,10 +69,10 @@ public String getRemoteAddress() { processor.execute(server, context, WriteRequest.newBuilder().build(), new JRaftServer.RaftGroupTuple()); Response response = reference.get(); - Assert.assertNotNull(response); + assertNotNull(response); - Assert.assertEquals("Error message transmission", response.getErrMsg()); - Assert.assertFalse(response.getSuccess()); + assertEquals("Error message transmission", response.getErrMsg()); + assertFalse(response.getSuccess()); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/listener/StandaloneProfileApplicationListenerTest.java b/core/src/test/java/com/alibaba/nacos/core/listener/StandaloneProfileApplicationListenerTest.java index 131a7bf64d6..97595561c34 100644 --- a/core/src/test/java/com/alibaba/nacos/core/listener/StandaloneProfileApplicationListenerTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/listener/StandaloneProfileApplicationListenerTest.java @@ -16,18 +16,18 @@ package com.alibaba.nacos.core.listener; -import com.alibaba.nacos.core.code.StandaloneProfileApplicationListener; import com.alibaba.nacos.common.utils.ArrayUtils; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +import com.alibaba.nacos.core.code.StandaloneProfileApplicationListener; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.env.Environment; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import static com.alibaba.nacos.sys.env.Constants.STANDALONE_SPRING_PROFILE; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link StandaloneProfileApplicationListener} Test. @@ -35,21 +35,21 @@ * @author Mercy * @since 0.2.2 */ -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @SpringBootTest(classes = StandaloneProfileApplicationListenerTest.class, webEnvironment = SpringBootTest.WebEnvironment.NONE) -public class StandaloneProfileApplicationListenerTest { +class StandaloneProfileApplicationListenerTest { @Autowired private Environment environment; - @BeforeClass - public static void init() { + @BeforeAll + static void init() { System.setProperty("nacos.standalone", "true"); } @Test - public void testProfile() { - Assert.assertTrue(ArrayUtils.contains(environment.getActiveProfiles(), STANDALONE_SPRING_PROFILE)); + void testProfile() { + assertTrue(ArrayUtils.contains(environment.getActiveProfiles(), STANDALONE_SPRING_PROFILE)); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/model/request/LogUpdateRequestTest.java b/core/src/test/java/com/alibaba/nacos/core/model/request/LogUpdateRequestTest.java index c5eabe5ccc6..e5c4d52ce75 100644 --- a/core/src/test/java/com/alibaba/nacos/core/model/request/LogUpdateRequestTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/model/request/LogUpdateRequestTest.java @@ -16,18 +16,19 @@ package com.alibaba.nacos.core.model.request; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class LogUpdateRequestTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class LogUpdateRequestTest { @Test - public void test() { + void test() { LogUpdateRequest request = new LogUpdateRequest(); request.setLogName("test"); request.setLogLevel("info"); - - Assert.assertEquals(request.getLogName(), "test"); - Assert.assertEquals(request.getLogLevel(), "info"); + + assertEquals("test", request.getLogName()); + assertEquals("info", request.getLogLevel()); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/model/request/LookupUpdateRequestTest.java b/core/src/test/java/com/alibaba/nacos/core/model/request/LookupUpdateRequestTest.java index 4414dec7866..9f7c5eee951 100644 --- a/core/src/test/java/com/alibaba/nacos/core/model/request/LookupUpdateRequestTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/model/request/LookupUpdateRequestTest.java @@ -16,16 +16,17 @@ package com.alibaba.nacos.core.model.request; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class LookupUpdateRequestTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class LookupUpdateRequestTest { @Test - public void test() { + void test() { LookupUpdateRequest request = new LookupUpdateRequest(); request.setType("type"); - - Assert.assertEquals(request.getType(), "type"); + + assertEquals("type", request.getType()); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/model/vo/InstanceIdGeneratorVOTest.java b/core/src/test/java/com/alibaba/nacos/core/model/vo/InstanceIdGeneratorVOTest.java index 47708b46a5c..9ccb6bffe40 100644 --- a/core/src/test/java/com/alibaba/nacos/core/model/vo/InstanceIdGeneratorVOTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/model/vo/InstanceIdGeneratorVOTest.java @@ -16,23 +16,24 @@ package com.alibaba.nacos.core.model.vo; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class InstanceIdGeneratorVOTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class InstanceIdGeneratorVOTest { @Test - public void test() { + void test() { IdGeneratorVO vo = new IdGeneratorVO(); IdGeneratorVO.IdInfo info = new IdGeneratorVO.IdInfo(); info.setWorkerId(1L); info.setCurrentId(2L); vo.setResource("test"); vo.setInfo(info); - - Assert.assertEquals(vo.getInfo(), info); - Assert.assertEquals(vo.getResource(), "test"); - Assert.assertEquals(vo.getInfo().getWorkerId().longValue(), 1L); - Assert.assertEquals(vo.getInfo().getCurrentId().longValue(), 2L); + + assertEquals(vo.getInfo(), info); + assertEquals("test", vo.getResource()); + assertEquals(1L, vo.getInfo().getWorkerId().longValue()); + assertEquals(2L, vo.getInfo().getCurrentId().longValue()); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/monitor/MetricsMonitorTest.java b/core/src/test/java/com/alibaba/nacos/core/monitor/MetricsMonitorTest.java index c957e5136fe..aa02b6ba8b2 100644 --- a/core/src/test/java/com/alibaba/nacos/core/monitor/MetricsMonitorTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/monitor/MetricsMonitorTest.java @@ -20,12 +20,13 @@ import io.micrometer.core.instrument.Timer; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import io.micrometer.prometheus.PrometheusMeterRegistry; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.context.ConfigurableApplicationContext; import java.util.HashMap; @@ -33,6 +34,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; /** @@ -41,23 +43,23 @@ * @author chenglu * @author liuyixiao */ -@RunWith(MockitoJUnitRunner.Silent.class) -public class MetricsMonitorTest { +@MockitoSettings(strictness = Strictness.LENIENT) +@ExtendWith(MockitoExtension.class) +class MetricsMonitorTest { @Mock private ConfigurableApplicationContext context; - @Before - public void initMeterRegistry() { + @BeforeEach + void initMeterRegistry() { ApplicationUtils.injectContext(context); when(context.getBean(PrometheusMeterRegistry.class)).thenReturn(null); // add simple meterRegistry. - NacosMeterRegistryCenter.getMeterRegistry(NacosMeterRegistryCenter.CORE_STABLE_REGISTRY) - .add(new SimpleMeterRegistry()); + NacosMeterRegistryCenter.getMeterRegistry(NacosMeterRegistryCenter.CORE_STABLE_REGISTRY).add(new SimpleMeterRegistry()); } - + @Test - public void testSdkServerExecutorMetric() { + void testSdkServerExecutorMetric() { MetricsMonitor.getSdkServerExecutorMetric().getPoolSize().set(1); MetricsMonitor.getSdkServerExecutorMetric().getMaximumPoolSize().set(1); MetricsMonitor.getSdkServerExecutorMetric().getCorePoolSize().set(1); @@ -65,18 +67,18 @@ public void testSdkServerExecutorMetric() { MetricsMonitor.getSdkServerExecutorMetric().getInQueueTaskCount().set(1); MetricsMonitor.getSdkServerExecutorMetric().getTaskCount().set(1); MetricsMonitor.getSdkServerExecutorMetric().getCompletedTaskCount().set(1); - Assert.assertEquals(MetricsMonitor.getSdkServerExecutorMetric().getType(), "grpcSdkServer"); - Assert.assertEquals(MetricsMonitor.getSdkServerExecutorMetric().getPoolSize().get(), 1); - Assert.assertEquals(MetricsMonitor.getSdkServerExecutorMetric().getMaximumPoolSize().get(), 1); - Assert.assertEquals(MetricsMonitor.getSdkServerExecutorMetric().getCorePoolSize().get(), 1); - Assert.assertEquals(MetricsMonitor.getSdkServerExecutorMetric().getActiveCount().get(), 1); - Assert.assertEquals(MetricsMonitor.getSdkServerExecutorMetric().getInQueueTaskCount().get(), 1); - Assert.assertEquals(MetricsMonitor.getSdkServerExecutorMetric().getTaskCount().get(), 1); - Assert.assertEquals(MetricsMonitor.getSdkServerExecutorMetric().getCompletedTaskCount().get(), 1); + assertEquals("grpcSdkServer", MetricsMonitor.getSdkServerExecutorMetric().getType()); + assertEquals(1, MetricsMonitor.getSdkServerExecutorMetric().getPoolSize().get()); + assertEquals(1, MetricsMonitor.getSdkServerExecutorMetric().getMaximumPoolSize().get()); + assertEquals(1, MetricsMonitor.getSdkServerExecutorMetric().getCorePoolSize().get()); + assertEquals(1, MetricsMonitor.getSdkServerExecutorMetric().getActiveCount().get()); + assertEquals(1, MetricsMonitor.getSdkServerExecutorMetric().getInQueueTaskCount().get()); + assertEquals(1, MetricsMonitor.getSdkServerExecutorMetric().getTaskCount().get()); + assertEquals(1, MetricsMonitor.getSdkServerExecutorMetric().getCompletedTaskCount().get()); } - + @Test - public void testClusterServerExecutorMetric() { + void testClusterServerExecutorMetric() { MetricsMonitor.getClusterServerExecutorMetric().getPoolSize().set(1); MetricsMonitor.getClusterServerExecutorMetric().getMaximumPoolSize().set(1); MetricsMonitor.getClusterServerExecutorMetric().getCorePoolSize().set(1); @@ -84,79 +86,79 @@ public void testClusterServerExecutorMetric() { MetricsMonitor.getClusterServerExecutorMetric().getInQueueTaskCount().set(1); MetricsMonitor.getClusterServerExecutorMetric().getTaskCount().set(1); MetricsMonitor.getClusterServerExecutorMetric().getCompletedTaskCount().set(1); - Assert.assertEquals(MetricsMonitor.getClusterServerExecutorMetric().getType(), "grpcClusterServer"); - Assert.assertEquals(MetricsMonitor.getClusterServerExecutorMetric().getPoolSize().get(), 1); - Assert.assertEquals(MetricsMonitor.getClusterServerExecutorMetric().getMaximumPoolSize().get(), 1); - Assert.assertEquals(MetricsMonitor.getClusterServerExecutorMetric().getCorePoolSize().get(), 1); - Assert.assertEquals(MetricsMonitor.getClusterServerExecutorMetric().getActiveCount().get(), 1); - Assert.assertEquals(MetricsMonitor.getClusterServerExecutorMetric().getInQueueTaskCount().get(), 1); - Assert.assertEquals(MetricsMonitor.getClusterServerExecutorMetric().getTaskCount().get(), 1); - Assert.assertEquals(MetricsMonitor.getClusterServerExecutorMetric().getCompletedTaskCount().get(), 1); + assertEquals("grpcClusterServer", MetricsMonitor.getClusterServerExecutorMetric().getType()); + assertEquals(1, MetricsMonitor.getClusterServerExecutorMetric().getPoolSize().get()); + assertEquals(1, MetricsMonitor.getClusterServerExecutorMetric().getMaximumPoolSize().get()); + assertEquals(1, MetricsMonitor.getClusterServerExecutorMetric().getCorePoolSize().get()); + assertEquals(1, MetricsMonitor.getClusterServerExecutorMetric().getActiveCount().get()); + assertEquals(1, MetricsMonitor.getClusterServerExecutorMetric().getInQueueTaskCount().get()); + assertEquals(1, MetricsMonitor.getClusterServerExecutorMetric().getTaskCount().get()); + assertEquals(1, MetricsMonitor.getClusterServerExecutorMetric().getCompletedTaskCount().get()); } @Test - public void testGetLongConnectionMonitor() { + void testGetLongConnectionMonitor() { AtomicInteger atomicInteger = MetricsMonitor.getLongConnectionMonitor(); - Assert.assertEquals(atomicInteger.get(), 0); + assertEquals(0, atomicInteger.get()); } @Test - public void testRaftReadIndexFailed() { + void testRaftReadIndexFailed() { MetricsMonitor.raftReadIndexFailed(); MetricsMonitor.raftReadIndexFailed(); - Assert.assertEquals(2D, MetricsMonitor.getRaftReadIndexFailed().totalAmount(), 0.01); + assertEquals(2D, MetricsMonitor.getRaftReadIndexFailed().totalAmount(), 0.01); } @Test - public void testRaftReadFromLeader() { + void testRaftReadFromLeader() { MetricsMonitor.raftReadFromLeader(); - Assert.assertEquals(1D, MetricsMonitor.getRaftFromLeader().totalAmount(), 0.01); + assertEquals(1D, MetricsMonitor.getRaftFromLeader().totalAmount(), 0.01); } @Test - public void testRaftApplyLogTimer() { + void testRaftApplyLogTimer() { Timer raftApplyTimerLog = MetricsMonitor.getRaftApplyLogTimer(); raftApplyTimerLog.record(10, TimeUnit.SECONDS); raftApplyTimerLog.record(20, TimeUnit.SECONDS); - Assert.assertEquals(0.5D, raftApplyTimerLog.totalTime(TimeUnit.MINUTES), 0.01); + assertEquals(0.5D, raftApplyTimerLog.totalTime(TimeUnit.MINUTES), 0.01); - Assert.assertEquals(30D, raftApplyTimerLog.totalTime(TimeUnit.SECONDS), 0.01); + assertEquals(30D, raftApplyTimerLog.totalTime(TimeUnit.SECONDS), 0.01); } @Test - public void testRaftApplyReadTimer() { + void testRaftApplyReadTimer() { Timer raftApplyReadTimer = MetricsMonitor.getRaftApplyReadTimer(); raftApplyReadTimer.record(10, TimeUnit.SECONDS); raftApplyReadTimer.record(20, TimeUnit.SECONDS); - Assert.assertEquals(0.5D, raftApplyReadTimer.totalTime(TimeUnit.MINUTES), 0.01); + assertEquals(0.5D, raftApplyReadTimer.totalTime(TimeUnit.MINUTES), 0.01); - Assert.assertEquals(30D, raftApplyReadTimer.totalTime(TimeUnit.SECONDS), 0.01); + assertEquals(30D, raftApplyReadTimer.totalTime(TimeUnit.SECONDS), 0.01); } - + @Test - public void testRefreshModuleConnectionCount() { + void testRefreshModuleConnectionCount() { // refresh Map map = new HashMap<>(); map.put("naming", 10); MetricsMonitor.refreshModuleConnectionCount(map); - Assert.assertEquals(1, MetricsMonitor.getModuleConnectionCnt().size()); - Assert.assertEquals(10, MetricsMonitor.getModuleConnectionCnt().get("naming").get()); - + assertEquals(1, MetricsMonitor.getModuleConnectionCnt().size()); + assertEquals(10, MetricsMonitor.getModuleConnectionCnt().get("naming").get()); + // refresh again map = new HashMap<>(); map.put("naming", 11); map.put("config", 1); MetricsMonitor.refreshModuleConnectionCount(map); - Assert.assertEquals(2, MetricsMonitor.getModuleConnectionCnt().size()); - Assert.assertEquals(11, MetricsMonitor.getModuleConnectionCnt().get("naming").get()); - Assert.assertEquals(1, MetricsMonitor.getModuleConnectionCnt().get("config").get()); - + assertEquals(2, MetricsMonitor.getModuleConnectionCnt().size()); + assertEquals(11, MetricsMonitor.getModuleConnectionCnt().get("naming").get()); + assertEquals(1, MetricsMonitor.getModuleConnectionCnt().get("config").get()); + // refresh again map = new HashMap<>(); map.put("naming", 1); MetricsMonitor.refreshModuleConnectionCount(map); - Assert.assertEquals(2, MetricsMonitor.getModuleConnectionCnt().size()); - Assert.assertEquals(1, MetricsMonitor.getModuleConnectionCnt().get("naming").get()); - Assert.assertEquals(0, MetricsMonitor.getModuleConnectionCnt().get("config").get()); + assertEquals(2, MetricsMonitor.getModuleConnectionCnt().size()); + assertEquals(1, MetricsMonitor.getModuleConnectionCnt().get("naming").get()); + assertEquals(0, MetricsMonitor.getModuleConnectionCnt().get("config").get()); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/monitor/NacosMeterRegistryCenterTest.java b/core/src/test/java/com/alibaba/nacos/core/monitor/NacosMeterRegistryCenterTest.java index 788bb013318..bf6103917d1 100644 --- a/core/src/test/java/com/alibaba/nacos/core/monitor/NacosMeterRegistryCenterTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/monitor/NacosMeterRegistryCenterTest.java @@ -18,45 +18,44 @@ import com.alibaba.nacos.sys.utils.ApplicationUtils; import io.micrometer.prometheus.PrometheusMeterRegistry; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.context.ConfigurableApplicationContext; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.Silent.class) -public class NacosMeterRegistryCenterTest { +@MockitoSettings(strictness = Strictness.LENIENT) +@ExtendWith(MockitoExtension.class) +class NacosMeterRegistryCenterTest { @Mock private ConfigurableApplicationContext context; - @Before - public void initMeterRegistry() { - ApplicationUtils.injectContext(context); - when(context.getBean(PrometheusMeterRegistry.class)).thenReturn(null); + @AfterAll + static void tearDown() { + ApplicationUtils.injectContext(null); } - @AfterClass - public static void tearDown() { - ApplicationUtils.injectContext(null); + @BeforeEach + void initMeterRegistry() { + ApplicationUtils.injectContext(context); + when(context.getBean(PrometheusMeterRegistry.class)).thenReturn(null); } @Test - public void testGetMeterRegistry() { - Assert.assertNotNull(NacosMeterRegistryCenter.getMeterRegistry(NacosMeterRegistryCenter.CORE_STABLE_REGISTRY)); - Assert.assertNotNull( - NacosMeterRegistryCenter.getMeterRegistry(NacosMeterRegistryCenter.CONFIG_STABLE_REGISTRY)); - Assert.assertNotNull( - NacosMeterRegistryCenter.getMeterRegistry(NacosMeterRegistryCenter.NAMING_STABLE_REGISTRY)); - Assert.assertNotNull( - NacosMeterRegistryCenter.getMeterRegistry(NacosMeterRegistryCenter.TOPN_CONFIG_CHANGE_REGISTRY)); - Assert.assertNotNull( - NacosMeterRegistryCenter.getMeterRegistry(NacosMeterRegistryCenter.TOPN_SERVICE_CHANGE_REGISTRY)); + void testGetMeterRegistry() { + assertNotNull(NacosMeterRegistryCenter.getMeterRegistry(NacosMeterRegistryCenter.CORE_STABLE_REGISTRY)); + assertNotNull(NacosMeterRegistryCenter.getMeterRegistry(NacosMeterRegistryCenter.CONFIG_STABLE_REGISTRY)); + assertNotNull(NacosMeterRegistryCenter.getMeterRegistry(NacosMeterRegistryCenter.NAMING_STABLE_REGISTRY)); + assertNotNull(NacosMeterRegistryCenter.getMeterRegistry(NacosMeterRegistryCenter.TOPN_CONFIG_CHANGE_REGISTRY)); + assertNotNull(NacosMeterRegistryCenter.getMeterRegistry(NacosMeterRegistryCenter.TOPN_SERVICE_CHANGE_REGISTRY)); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/monitor/topn/FixedSizePriorityQueueTest.java b/core/src/test/java/com/alibaba/nacos/core/monitor/topn/FixedSizePriorityQueueTest.java index c6ef68ee62b..659a89af5af 100644 --- a/core/src/test/java/com/alibaba/nacos/core/monitor/topn/FixedSizePriorityQueueTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/monitor/topn/FixedSizePriorityQueueTest.java @@ -16,27 +16,27 @@ package com.alibaba.nacos.core.monitor.topn; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; -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 FixedSizePriorityQueueTest { +class FixedSizePriorityQueueTest { @Test - public void testOfferEmpty() { + void testOfferEmpty() { FixedSizePriorityQueue queue = new FixedSizePriorityQueue<>(10, Comparator.naturalOrder()); List list = queue.toList(); assertTrue(list.isEmpty()); } @Test - public void testOfferLessThanSize() { + void testOfferLessThanSize() { FixedSizePriorityQueue queue = new FixedSizePriorityQueue<>(10, Comparator.naturalOrder()); for (int i = 0; i < 5; i++) { queue.offer(i); @@ -49,7 +49,7 @@ public void testOfferLessThanSize() { } @Test - public void testOfferMoreThanSizeWithIncreasing() { + void testOfferMoreThanSizeWithIncreasing() { FixedSizePriorityQueue queue = new FixedSizePriorityQueue<>(10, Comparator.naturalOrder()); for (int i = 0; i < 15; i++) { queue.offer(i); @@ -62,7 +62,7 @@ public void testOfferMoreThanSizeWithIncreasing() { } @Test - public void testOfferMoreThanSizeWithDecreasing() { + void testOfferMoreThanSizeWithDecreasing() { FixedSizePriorityQueue queue = new FixedSizePriorityQueue<>(10, Comparator.naturalOrder()); for (int i = 14; i > 0; i--) { queue.offer(i); @@ -75,7 +75,7 @@ public void testOfferMoreThanSizeWithDecreasing() { } @Test - public void testOfferMoreThanSizeWithShuffle() { + void testOfferMoreThanSizeWithShuffle() { List testCase = new ArrayList<>(50); for (int i = 0; i < 50; i++) { testCase.add(i); diff --git a/core/src/test/java/com/alibaba/nacos/core/monitor/topn/StringTopNCounterTest.java b/core/src/test/java/com/alibaba/nacos/core/monitor/topn/StringTopNCounterTest.java index c6c8e38c5f3..1ebe0253469 100644 --- a/core/src/test/java/com/alibaba/nacos/core/monitor/topn/StringTopNCounterTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/monitor/topn/StringTopNCounterTest.java @@ -19,46 +19,48 @@ import com.alibaba.nacos.common.event.ServerConfigChangeEvent; import com.alibaba.nacos.common.utils.Pair; import com.alibaba.nacos.sys.env.EnvUtil; -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.springframework.mock.env.MockEnvironment; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * unit test for TopNCounterMetricsContainer. * * @author liuyixiao */ -public class StringTopNCounterTest { +class StringTopNCounterTest { private StringTopNCounter stringTopNCounter; - @Before - public void setUp() { + @BeforeEach + void setUp() { stringTopNCounter = new StringTopNCounter(); } - @After - public void tearDown() { + @AfterEach + void tearDown() { stringTopNCounter.reset(); EnvUtil.setEnvironment(new MockEnvironment()); TopNConfig.getInstance().onEvent(new ServerConfigChangeEvent()); } @Test - public void testSet() { + void testSet() { stringTopNCounter.set("test1", 1); List> actual = stringTopNCounter.getTopNCounter(10); assertTopNCounter(actual, 1, new String[] {"test1"}, new Integer[] {1}); } @Test - public void testIncrement() { + void testIncrement() { stringTopNCounter.set("test", 0); assertTopNCounter(stringTopNCounter.getTopNCounter(10), 1, new String[] {"test"}, new Integer[] {0}); stringTopNCounter.increment("test"); @@ -66,27 +68,27 @@ public void testIncrement() { } @Test - public void testReset() { + void testReset() { stringTopNCounter.set("test", 1); stringTopNCounter.set("test1", 2); stringTopNCounter.set("test2", 3); - assertTopNCounter(stringTopNCounter.getTopNCounter(10), 3, new String[] {"test2", "test1", "test"}, - new Integer[] {3, 2, 1}); + assertTopNCounter(stringTopNCounter.getTopNCounter(10), 3, new String[] {"test2", "test1", "test"}, new Integer[] {3, 2, 1}); stringTopNCounter.reset(); assertTopNCounter(stringTopNCounter.getTopNCounter(10), 0, new String[] {}, new Integer[] {}); } @Test - public void testGetTopNCounter() { + void testGetTopNCounter() { for (int i = 0; i < 20; i++) { stringTopNCounter.set("test" + i, i); } - assertTopNCounter(stringTopNCounter.getTopNCounter(10), 10, new String[] {"test19", "test18", "test17", "test16", - "test15", "test14", "test13", "test12", "test11", "test10"}, new Integer[] {19, 18, 17, 16, 15, 14, 13, 12, 11, 10}); + assertTopNCounter(stringTopNCounter.getTopNCounter(10), 10, + new String[] {"test19", "test18", "test17", "test16", "test15", "test14", "test13", "test12", "test11", "test10"}, + new Integer[] {19, 18, 17, 16, 15, 14, 13, 12, 11, 10}); } @Test - public void testForTopnDisabled() { + void testForTopnDisabled() { MockEnvironment env = new MockEnvironment(); env.setProperty("nacos.core.monitor.topn.enabled", "false"); EnvUtil.setEnvironment(env); @@ -98,10 +100,10 @@ public void testForTopnDisabled() { } private void assertTopNCounter(List> actual, int size, String[] keys, Integer[] value) { - Assert.assertEquals(size, actual.size()); + assertEquals(size, actual.size()); for (int i = 0; i < size; i++) { - Assert.assertTrue(Arrays.asList(keys).contains(actual.get(i).getFirst())); - Assert.assertTrue(Arrays.asList(value).contains(actual.get(i).getSecond().get())); + assertTrue(Arrays.asList(keys).contains(actual.get(i).getFirst())); + assertTrue(Arrays.asList(value).contains(actual.get(i).getSecond().get())); } } } diff --git a/core/src/test/java/com/alibaba/nacos/core/namespace/repository/EmbeddedNamespacePersistServiceTest.java b/core/src/test/java/com/alibaba/nacos/core/namespace/repository/EmbeddedNamespacePersistServiceTest.java index 153caca6e3c..bf5d292acc2 100644 --- a/core/src/test/java/com/alibaba/nacos/core/namespace/repository/EmbeddedNamespacePersistServiceTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/namespace/repository/EmbeddedNamespacePersistServiceTest.java @@ -23,12 +23,11 @@ import com.alibaba.nacos.persistence.datasource.DynamicDataSource; import com.alibaba.nacos.persistence.repository.embedded.operate.DatabaseOperate; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.env.MockEnvironment; import org.springframework.test.util.ReflectionTestUtils; @@ -36,14 +35,18 @@ import java.util.List; import static com.alibaba.nacos.core.namespace.repository.NamespaceRowMapperInjector.TENANT_INFO_ROW_MAPPER; +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.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class EmbeddedNamespacePersistServiceTest { +@ExtendWith(MockitoExtension.class) +class EmbeddedNamespacePersistServiceTest { @Mock private DatabaseOperate databaseOperate; @@ -55,8 +58,8 @@ public class EmbeddedNamespacePersistServiceTest { private MockEnvironment environment; - @Before - public void setUp() { + @BeforeEach + void setUp() { EnvUtil.setIsStandalone(true); DatasourceConfiguration.setEmbeddedStorage(true); environment = new MockEnvironment(); @@ -67,7 +70,7 @@ public void setUp() { } @Test - public void insertTenantInfoAtomicTest1() { + void insertTenantInfoAtomicTest1() { String namespaceId = "testNsId"; String kp = "1"; @@ -84,7 +87,7 @@ public void insertTenantInfoAtomicTest1() { } @Test - public void insertTenantInfoAtomicTest2() { + void insertTenantInfoAtomicTest2() { String namespaceId = "testNsId"; String kp = "1"; @@ -94,15 +97,15 @@ public void insertTenantInfoAtomicTest2() { when(databaseOperate.update(anyList())).thenReturn(false); when(dataSourceService.getDataSourceType()).thenReturn("derby"); - Assert.assertThrows(NacosRuntimeException.class, - () -> embeddedNamespacePersistService.insertTenantInfoAtomic(kp, namespaceId, namespaceName, - namespaceDesc, createRes, System.currentTimeMillis())); + assertThrows(NacosRuntimeException.class, + () -> embeddedNamespacePersistService.insertTenantInfoAtomic(kp, namespaceId, namespaceName, namespaceDesc, createRes, + System.currentTimeMillis())); verify(databaseOperate).update(anyList()); } @Test - public void removeTenantInfoAtomicTest() { + void removeTenantInfoAtomicTest() { String namespaceId = "testNsId"; String kp = "1"; @@ -115,7 +118,7 @@ public void removeTenantInfoAtomicTest() { } @Test - public void updateTenantNameAtomicTest1() { + void updateTenantNameAtomicTest1() { String namespaceId = "testNsId"; String kp = "1"; @@ -130,7 +133,7 @@ public void updateTenantNameAtomicTest1() { } @Test - public void updateTenantNameAtomicTest2() { + void updateTenantNameAtomicTest2() { String namespaceId = "testNsId"; String kp = "1"; @@ -139,81 +142,77 @@ public void updateTenantNameAtomicTest2() { when(databaseOperate.update(anyList())).thenReturn(false); when(dataSourceService.getDataSourceType()).thenReturn("derby"); - Assert.assertThrows(NacosRuntimeException.class, - () -> embeddedNamespacePersistService.updateTenantNameAtomic(kp, namespaceId, namespaceName, - namespaceDesc)); + assertThrows(NacosRuntimeException.class, + () -> embeddedNamespacePersistService.updateTenantNameAtomic(kp, namespaceId, namespaceName, namespaceDesc)); verify(databaseOperate).update(anyList()); } @Test - public void findTenantByKpTest1() { + void findTenantByKpTest1() { String kp = "1"; List tenantInfoList = new ArrayList<>(1); tenantInfoList.add(new TenantInfo()); - when(databaseOperate.queryMany(anyString(), eq(new Object[] {kp}), eq(TENANT_INFO_ROW_MAPPER))).thenReturn( - tenantInfoList); + when(databaseOperate.queryMany(anyString(), eq(new Object[] {kp}), eq(TENANT_INFO_ROW_MAPPER))).thenReturn(tenantInfoList); when(dataSourceService.getDataSourceType()).thenReturn("derby"); List tenantByKp = embeddedNamespacePersistService.findTenantByKp(kp); - Assert.assertEquals(tenantByKp.get(0), tenantInfoList.get(0)); + assertEquals(tenantByKp.get(0), tenantInfoList.get(0)); } @Test - public void findTenantByKpTest2() { + void findTenantByKpTest2() { String kp = "1"; String tenantId = "tenantId"; TenantInfo tenantInfo = new TenantInfo(); tenantInfo.setTenantId(tenantId); - when(databaseOperate.queryOne(anyString(), eq(new Object[] {kp, tenantId}), - eq(TENANT_INFO_ROW_MAPPER))).thenReturn(tenantInfo); + when(databaseOperate.queryOne(anyString(), eq(new Object[] {kp, tenantId}), eq(TENANT_INFO_ROW_MAPPER))).thenReturn(tenantInfo); when(dataSourceService.getDataSourceType()).thenReturn("derby"); TenantInfo tenantByKp = embeddedNamespacePersistService.findTenantByKp(kp, tenantId); - Assert.assertEquals(tenantInfo.getTenantId(), tenantByKp.getTenantId()); + assertEquals(tenantInfo.getTenantId(), tenantByKp.getTenantId()); } @Test - public void generateLikeArgumentTest() { + void generateLikeArgumentTest() { String test = embeddedNamespacePersistService.generateLikeArgument("test"); String testB = embeddedNamespacePersistService.generateLikeArgument("test*"); - Assert.assertEquals("test", test); + assertEquals("test", test); - Assert.assertEquals("test%", testB); + assertEquals("test%", testB); } @Test - public void isExistTableTest() { + void isExistTableTest() { String tableName = "tableName"; String sql = String.format("SELECT 1 FROM %s FETCH FIRST ROW ONLY", tableName); when(databaseOperate.queryOne(sql, Integer.class)).thenReturn(1); boolean existTableA = embeddedNamespacePersistService.isExistTable(tableName); - Assert.assertTrue(existTableA); + assertTrue(existTableA); when(databaseOperate.queryOne(sql, Integer.class)).thenThrow(new RuntimeException("test")); boolean existTableB = embeddedNamespacePersistService.isExistTable(tableName); - Assert.assertFalse(existTableB); + assertFalse(existTableB); } @Test - public void tenantInfoCountByTenantIdTest() { + void tenantInfoCountByTenantIdTest() { String tenantId = "tenantId"; when(dataSourceService.getDataSourceType()).thenReturn("derby"); - Assert.assertThrows(IllegalArgumentException.class, - () -> embeddedNamespacePersistService.tenantInfoCountByTenantId(null)); + assertThrows(IllegalArgumentException.class, () -> embeddedNamespacePersistService.tenantInfoCountByTenantId(null)); when(databaseOperate.queryOne(anyString(), eq(new String[] {tenantId}), eq(Integer.class))).thenReturn(null); int i = embeddedNamespacePersistService.tenantInfoCountByTenantId(tenantId); - Assert.assertEquals(0, i); + assertEquals(0, i); when(databaseOperate.queryOne(anyString(), eq(new String[] {tenantId}), eq(Integer.class))).thenReturn(1); int j = embeddedNamespacePersistService.tenantInfoCountByTenantId(tenantId); - Assert.assertEquals(1, j); + assertEquals(1, j); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/namespace/repository/ExternalNamespacePersistServiceTest.java b/core/src/test/java/com/alibaba/nacos/core/namespace/repository/ExternalNamespacePersistServiceTest.java index b172cf7d356..8cd3947f080 100644 --- a/core/src/test/java/com/alibaba/nacos/core/namespace/repository/ExternalNamespacePersistServiceTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/namespace/repository/ExternalNamespacePersistServiceTest.java @@ -23,12 +23,11 @@ import com.alibaba.nacos.persistence.exception.NJdbcException; import com.alibaba.nacos.persistence.repository.embedded.operate.DatabaseOperate; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.dao.DataAccessException; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.CannotGetJdbcConnectionException; @@ -41,13 +40,18 @@ import java.util.List; import static com.alibaba.nacos.core.namespace.repository.NamespaceRowMapperInjector.TENANT_INFO_ROW_MAPPER; +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.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class ExternalNamespacePersistServiceTest { +@ExtendWith(MockitoExtension.class) +class ExternalNamespacePersistServiceTest { @Mock private DatabaseOperate databaseOperate; @@ -62,8 +66,8 @@ public class ExternalNamespacePersistServiceTest { private MockEnvironment environment; - @Before - public void setUp() { + @BeforeEach + void setUp() { EnvUtil.setIsStandalone(false); DatasourceConfiguration.setEmbeddedStorage(false); environment = new MockEnvironment(); @@ -76,7 +80,7 @@ public void setUp() { } @Test - public void insertTenantInfoAtomicTest() { + void insertTenantInfoAtomicTest() { String kp = "1"; String namespaceId = "namespaceId"; String namespaceName = "namespaceName"; @@ -85,16 +89,16 @@ public void insertTenantInfoAtomicTest() { externalNamespacePersistService.insertTenantInfoAtomic(kp, namespaceId, namespaceName, namespaceDesc, "nacos", System.currentTimeMillis()); - when(jt.update(anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyLong(), - anyLong())).thenThrow(new NJdbcException("test")); - Assert.assertThrows(DataAccessException.class, - () -> externalNamespacePersistService.insertTenantInfoAtomic(kp, namespaceId, namespaceName, - namespaceDesc, "nacos", System.currentTimeMillis())); + when(jt.update(anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyLong(), anyLong())).thenThrow( + new NJdbcException("test")); + assertThrows(DataAccessException.class, + () -> externalNamespacePersistService.insertTenantInfoAtomic(kp, namespaceId, namespaceName, namespaceDesc, "nacos", + System.currentTimeMillis())); } @Test - public void removeTenantInfoAtomicTest() { + void removeTenantInfoAtomicTest() { String kp = "1"; String namespaceId = "namespaceId"; when(dataSourceService.getDataSourceType()).thenReturn("mysql"); @@ -102,12 +106,11 @@ public void removeTenantInfoAtomicTest() { externalNamespacePersistService.removeTenantInfoAtomic(kp, namespaceId); when(jt.update(anyString(), anyString(), anyString())).thenThrow(new CannotGetJdbcConnectionException("test")); - Assert.assertThrows(CannotGetJdbcConnectionException.class, - () -> externalNamespacePersistService.removeTenantInfoAtomic(kp, namespaceId)); + assertThrows(CannotGetJdbcConnectionException.class, () -> externalNamespacePersistService.removeTenantInfoAtomic(kp, namespaceId)); } @Test - public void updateTenantNameAtomicTest() { + void updateTenantNameAtomicTest() { String kp = "1"; String namespaceId = "namespaceId"; String namespaceName = "namespaceName"; @@ -115,15 +118,13 @@ public void updateTenantNameAtomicTest() { when(dataSourceService.getDataSourceType()).thenReturn("mysql"); externalNamespacePersistService.updateTenantNameAtomic(kp, namespaceId, namespaceName, namespaceDesc); - when(jt.update(anyString(), anyString(), anyString(), anyLong(), anyString(), anyString())).thenThrow( - new NJdbcException("test")); - Assert.assertThrows(DataAccessException.class, - () -> externalNamespacePersistService.updateTenantNameAtomic(kp, namespaceId, namespaceName, - namespaceDesc)); + when(jt.update(anyString(), anyString(), anyString(), anyLong(), anyString(), anyString())).thenThrow(new NJdbcException("test")); + assertThrows(DataAccessException.class, + () -> externalNamespacePersistService.updateTenantNameAtomic(kp, namespaceId, namespaceName, namespaceDesc)); } @Test - public void findTenantByKpTest() { + void findTenantByKpTest() { String kp = "1"; when(dataSourceService.getDataSourceType()).thenReturn("mysql"); List tenantInfoList = new ArrayList<>(1); @@ -132,97 +133,90 @@ public void findTenantByKpTest() { when(jt.query(anyString(), eq(new Object[] {kp}), eq(TENANT_INFO_ROW_MAPPER))).thenReturn(tenantInfoList); List tenantByKp = externalNamespacePersistService.findTenantByKp(kp); - Assert.assertEquals(tenantInfoList.get(0), tenantByKp.get(0)); + assertEquals(tenantInfoList.get(0), tenantByKp.get(0)); when(jt.query(anyString(), eq(new Object[] {kp}), eq(TENANT_INFO_ROW_MAPPER))).thenThrow( new CannotGetJdbcConnectionException("test")); - Assert.assertThrows(CannotGetJdbcConnectionException.class, - () -> externalNamespacePersistService.findTenantByKp(kp)); + assertThrows(CannotGetJdbcConnectionException.class, () -> externalNamespacePersistService.findTenantByKp(kp)); - when(jt.query(anyString(), eq(new Object[] {kp}), eq(TENANT_INFO_ROW_MAPPER))).thenThrow( - new EmptyResultDataAccessException(1)); + when(jt.query(anyString(), eq(new Object[] {kp}), eq(TENANT_INFO_ROW_MAPPER))).thenThrow(new EmptyResultDataAccessException(1)); List tenantByKp1 = externalNamespacePersistService.findTenantByKp(kp); - Assert.assertEquals(Collections.emptyList(), tenantByKp1); + assertEquals(Collections.emptyList(), tenantByKp1); - when(jt.query(anyString(), eq(new Object[] {kp}), eq(TENANT_INFO_ROW_MAPPER))).thenThrow( - new RuntimeException("test")); - Assert.assertThrows(RuntimeException.class, () -> externalNamespacePersistService.findTenantByKp(kp)); + when(jt.query(anyString(), eq(new Object[] {kp}), eq(TENANT_INFO_ROW_MAPPER))).thenThrow(new RuntimeException("test")); + assertThrows(RuntimeException.class, () -> externalNamespacePersistService.findTenantByKp(kp)); } @Test - public void findTenantByKpTest2() { + void findTenantByKpTest2() { String kp = "1"; String namespaceId = "namespaceId"; when(dataSourceService.getDataSourceType()).thenReturn("mysql"); TenantInfo tenantInfo = new TenantInfo(); tenantInfo.setTenantId(namespaceId); - when(jt.queryForObject(anyString(), eq(new Object[] {kp, namespaceId}), eq(TENANT_INFO_ROW_MAPPER))).thenReturn( - tenantInfo); + when(jt.queryForObject(anyString(), eq(new Object[] {kp, namespaceId}), eq(TENANT_INFO_ROW_MAPPER))).thenReturn(tenantInfo); TenantInfo tenantByKp = externalNamespacePersistService.findTenantByKp(kp, namespaceId); - Assert.assertEquals(tenantInfo.getTenantId(), tenantByKp.getTenantId()); + assertEquals(tenantInfo.getTenantId(), tenantByKp.getTenantId()); when(jt.queryForObject(anyString(), eq(new Object[] {kp, namespaceId}), eq(TENANT_INFO_ROW_MAPPER))).thenThrow( new CannotGetJdbcConnectionException("test")); - Assert.assertThrows(CannotGetJdbcConnectionException.class, - () -> externalNamespacePersistService.findTenantByKp(kp, namespaceId)); + assertThrows(CannotGetJdbcConnectionException.class, () -> externalNamespacePersistService.findTenantByKp(kp, namespaceId)); when(jt.queryForObject(anyString(), eq(new Object[] {kp, namespaceId}), eq(TENANT_INFO_ROW_MAPPER))).thenThrow( new EmptyResultDataAccessException(1)); TenantInfo tenantByKp1 = externalNamespacePersistService.findTenantByKp(kp, namespaceId); - Assert.assertNull(tenantByKp1); + assertNull(tenantByKp1); when(jt.queryForObject(anyString(), eq(new Object[] {kp, namespaceId}), eq(TENANT_INFO_ROW_MAPPER))).thenThrow( new RuntimeException("test")); - Assert.assertThrows(RuntimeException.class, - () -> externalNamespacePersistService.findTenantByKp(kp, namespaceId)); + assertThrows(RuntimeException.class, () -> externalNamespacePersistService.findTenantByKp(kp, namespaceId)); } @Test - public void generateLikeArgumentTest() { + void generateLikeArgumentTest() { String test = externalNamespacePersistService.generateLikeArgument("test"); String testB = externalNamespacePersistService.generateLikeArgument("test*"); - Assert.assertEquals("test", test); + assertEquals("test", test); - Assert.assertEquals("test%", testB); + assertEquals("test%", testB); } @Test - public void isExistTableTest() { + void isExistTableTest() { String tableName = "tableName"; String sql = String.format("SELECT 1 FROM %s LIMIT 1", tableName); when(jt.queryForObject(eq(sql), eq(Integer.class))).thenReturn(1); boolean existTableA = externalNamespacePersistService.isExistTable(tableName); - Assert.assertTrue(existTableA); + assertTrue(existTableA); when(jt.queryForObject(eq(sql), eq(Integer.class))).thenThrow(new RuntimeException("test")); boolean existTableB = externalNamespacePersistService.isExistTable(tableName); - Assert.assertFalse(existTableB); + assertFalse(existTableB); } @Test - public void tenantInfoCountByTenantIdTest() { + void tenantInfoCountByTenantIdTest() { String tenantId = "tenantId"; when(dataSourceService.getDataSourceType()).thenReturn("mysql"); - Assert.assertThrows(IllegalArgumentException.class, - () -> externalNamespacePersistService.tenantInfoCountByTenantId(null)); + assertThrows(IllegalArgumentException.class, () -> externalNamespacePersistService.tenantInfoCountByTenantId(null)); when(jt.queryForObject(anyString(), eq(new String[] {tenantId}), eq(Integer.class))).thenReturn(null); int i = externalNamespacePersistService.tenantInfoCountByTenantId(tenantId); - Assert.assertEquals(0, i); + assertEquals(0, i); when(jt.queryForObject(anyString(), eq(new String[] {tenantId}), eq(Integer.class))).thenReturn(1); int j = externalNamespacePersistService.tenantInfoCountByTenantId(tenantId); - Assert.assertEquals(1, j); + assertEquals(1, j); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/paramcheck/CheckConfigurationTest.java b/core/src/test/java/com/alibaba/nacos/core/paramcheck/CheckConfigurationTest.java index 6505a37293a..a7535cbb8bd 100644 --- a/core/src/test/java/com/alibaba/nacos/core/paramcheck/CheckConfigurationTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/paramcheck/CheckConfigurationTest.java @@ -19,20 +19,35 @@ import com.alibaba.nacos.core.code.ControllerMethodsCache; import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.test.util.ReflectionTestUtils; + +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; /** * {@link CheckConfiguration} unit tests. + * * @author lynn.lqp * @date 2023/12/28 */ -public class CheckConfigurationTest { - +class CheckConfigurationTest { + @Test - public void testCheckerFilter() { + void testCheckerFilter() { CheckConfiguration checkConfiguration = new CheckConfiguration(); ControllerMethodsCache methodsCache = Mockito.mock(ControllerMethodsCache.class); ParamCheckerFilter checkerFilter = checkConfiguration.checkerFilter(methodsCache); assertNotNull(checkerFilter); } + + @Test + void testCheckerFilterRegistration() { + ParamCheckerFilter checkerFilter = Mockito.mock(ParamCheckerFilter.class); + CheckConfiguration configuration = new CheckConfiguration(); + FilterRegistrationBean registration = configuration.checkerFilterRegistration(checkerFilter); + String name = (String) ReflectionTestUtils.getField(registration, "name"); + assertEquals("checkerFilter", name); + assertEquals(8, registration.getOrder()); + } } diff --git a/core/src/test/java/com/alibaba/nacos/core/paramcheck/ParamCheckerFilterTest.java b/core/src/test/java/com/alibaba/nacos/core/paramcheck/ParamCheckerFilterTest.java index 85cd37950d2..86297cbb605 100644 --- a/core/src/test/java/com/alibaba/nacos/core/paramcheck/ParamCheckerFilterTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/paramcheck/ParamCheckerFilterTest.java @@ -19,36 +19,39 @@ import com.alibaba.nacos.core.code.ControllerMethodsCache; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; + import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; + import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Unit tests for the {@link ParamCheckerFilter}. + * * @author lynn.lqp * @date 2023/11/7 */ -public class ParamCheckerFilterTest { - +class ParamCheckerFilterTest { + private ParamCheckerFilter filter; - + private ControllerMethodsCache methodsCache; - + private ServerParamCheckConfig serverParamCheckConfig; - + private HttpServletRequest request; - + private HttpServletResponse response; - + private FilterChain chain; - + @BeforeEach - public void setUp() { + void setUp() { filter = new ParamCheckerFilter(mock(ControllerMethodsCache.class)); methodsCache = mock(ControllerMethodsCache.class); serverParamCheckConfig = mock(ServerParamCheckConfig.class); @@ -56,16 +59,16 @@ public void setUp() { response = mock(HttpServletResponse.class); chain = mock(FilterChain.class); } - + @Test - public void testDoFilterParamCheckDisabled() throws IOException, ServletException { + void testDoFilterParamCheckDisabled() throws IOException, ServletException { when(serverParamCheckConfig.isParamCheckEnabled()).thenReturn(false); filter.doFilter(request, response, chain); verify(chain).doFilter(request, response); } - + @Test - public void testDoFilterMethodNotFound() throws IOException, ServletException { + void testDoFilterMethodNotFound() throws IOException, ServletException { when(methodsCache.getMethod(request)).thenReturn(null); filter.doFilter(request, response, chain); verify(chain).doFilter(request, response); diff --git a/core/src/test/java/com/alibaba/nacos/core/paramcheck/ParamExtractorTest.java b/core/src/test/java/com/alibaba/nacos/core/paramcheck/ParamExtractorTest.java index aea71b90e39..1e56abb39b8 100644 --- a/core/src/test/java/com/alibaba/nacos/core/paramcheck/ParamExtractorTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/paramcheck/ParamExtractorTest.java @@ -18,13 +18,13 @@ import com.alibaba.nacos.common.paramcheck.ParamInfo; import com.alibaba.nacos.core.paramcheck.impl.ConfigRequestParamExtractor; -import org.junit.Test; +import org.junit.jupiter.api.Test; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * ParamCheckerTest. @@ -32,10 +32,10 @@ * @author 985492783@qq.com * @date 2023/11/7 20:16 */ -public class ParamExtractorTest { +class ParamExtractorTest { @Test - public void testCheckAnnotation() { + void testCheckAnnotation() { ExtractorManager.Extractor extractor = Controller.class.getAnnotation(ExtractorManager.Extractor.class); AbstractRpcParamExtractor paramExtractor = ExtractorManager.getRpcExtractor(extractor); assertEquals(paramExtractor.getClass().getSimpleName(), ConfigRequestParamExtractor.class.getSimpleName()); diff --git a/core/src/test/java/com/alibaba/nacos/core/paramcheck/ServerParamCheckConfigTest.java b/core/src/test/java/com/alibaba/nacos/core/paramcheck/ServerParamCheckConfigTest.java index 2a99dd57c65..2a35a09713a 100644 --- a/core/src/test/java/com/alibaba/nacos/core/paramcheck/ServerParamCheckConfigTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/paramcheck/ServerParamCheckConfigTest.java @@ -17,18 +17,18 @@ package com.alibaba.nacos.core.paramcheck; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.mock.env.MockEnvironment; import java.lang.reflect.Constructor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; -public class ServerParamCheckConfigTest { +class ServerParamCheckConfigTest { @Test - public void getConfigFromEnv() throws ReflectiveOperationException { + void getConfigFromEnv() throws ReflectiveOperationException { MockEnvironment environment = new MockEnvironment(); EnvUtil.setEnvironment(environment); environment.setProperty("nacos.core.param.check.enabled", String.valueOf(false)); @@ -39,20 +39,20 @@ public void getConfigFromEnv() throws ReflectiveOperationException { ServerParamCheckConfig paramCheckConfig = declaredConstructor.newInstance(); assertFalse(paramCheckConfig.isParamCheckEnabled()); - assertEquals(paramCheckConfig.getActiveParamChecker(), "default"); + assertEquals("default", paramCheckConfig.getActiveParamChecker()); } @Test - public void setParamCheckEnabled() { + void setParamCheckEnabled() { ServerParamCheckConfig paramCheckConfig = ServerParamCheckConfig.getInstance(); paramCheckConfig.setParamCheckEnabled(false); assertFalse(paramCheckConfig.isParamCheckEnabled()); } @Test - public void setActiveParamChecker() { + void setActiveParamChecker() { ServerParamCheckConfig paramCheckConfig = ServerParamCheckConfig.getInstance(); paramCheckConfig.setActiveParamChecker("test"); - assertEquals(paramCheckConfig.getActiveParamChecker(), "test"); + assertEquals("test", paramCheckConfig.getActiveParamChecker()); } } \ No newline at end of file diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/ClientConnectionEventListenerRegistryTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/ClientConnectionEventListenerRegistryTest.java index 737b400867e..50ef83633dc 100644 --- a/core/src/test/java/com/alibaba/nacos/core/remote/ClientConnectionEventListenerRegistryTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/remote/ClientConnectionEventListenerRegistryTest.java @@ -17,23 +17,25 @@ package com.alibaba.nacos.core.remote; -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.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Objects; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + /** * {@link ClientConnectionEventListenerRegistry} uint test. * * @author chenglu * @date 2021-07-02 14:43 */ -@RunWith(MockitoJUnitRunner.class) -public class ClientConnectionEventListenerRegistryTest { +@ExtendWith(MockitoExtension.class) +class ClientConnectionEventListenerRegistryTest { @InjectMocks private ClientConnectionEventListenerRegistry registry; @@ -42,7 +44,7 @@ public class ClientConnectionEventListenerRegistryTest { private Connection connection; @Test - public void testRegistryMethods() { + void testRegistryMethods() { try { registry.registerClientConnectionEventListener(new MockClientConnectionEventListener()); @@ -52,7 +54,7 @@ public void testRegistryMethods() { } catch (Exception e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } @@ -60,12 +62,12 @@ class MockClientConnectionEventListener extends ClientConnectionEventListener { @Override public void clientConnected(Connection connect) { - Assert.assertTrue(Objects.nonNull(connect)); + assertTrue(Objects.nonNull(connect)); } @Override public void clientDisConnected(Connection connect) { - Assert.assertTrue(Objects.nonNull(connect)); + assertTrue(Objects.nonNull(connect)); } } } diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/ConnectionManagerTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/ConnectionManagerTest.java index 622c6bb45ae..aa8fd830d49 100644 --- a/core/src/test/java/com/alibaba/nacos/core/remote/ConnectionManagerTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/remote/ConnectionManagerTest.java @@ -23,18 +23,17 @@ import com.alibaba.nacos.plugin.control.configs.ControlConfigs; import com.alibaba.nacos.sys.env.EnvUtil; import io.grpc.netty.shaded.io.netty.channel.Channel; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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 org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.env.MockEnvironment; import java.io.File; @@ -42,14 +41,21 @@ import java.util.Map; import java.util.UUID; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + /** * {@link ConnectionManager} unit test. * * @author chenglu * @date 2021-07-02 14:57 */ -@RunWith(MockitoJUnitRunner.class) -public class ConnectionManagerTest { +@ExtendWith(MockitoExtension.class) +class ConnectionManagerTest { + + static MockedStatic propertyUtilMockedStatic; @InjectMocks private ConnectionManager connectionManager; @@ -70,24 +76,22 @@ public class ConnectionManagerTest { private String clientIp = "1.1.1.1"; - static MockedStatic propertyUtilMockedStatic; - - @BeforeClass - public static void setUpClass() { + @BeforeAll + static void setUpClass() { propertyUtilMockedStatic = Mockito.mockStatic(ControlConfigs.class); propertyUtilMockedStatic.when(ControlConfigs::getInstance).thenReturn(new ControlConfigs()); } - @AfterClass - public static void afterClass() { + @AfterAll + static void afterClass() { if (propertyUtilMockedStatic != null) { propertyUtilMockedStatic.close(); } } - @Before - public void setUp() { + @BeforeEach + void setUp() { EnvUtil.setEnvironment(new MockEnvironment()); // create base file path File baseDir = new File(EnvUtil.getNacosHome(), "data"); @@ -109,63 +113,63 @@ public void setUp() { connectionManager.register(connectId, connection); } - @After - public void tearDown() { + @AfterEach + void tearDown() { connectionManager.unregister(connectId); } @Test - public void testCheckValid() { - Assert.assertTrue(connectionManager.checkValid(connectId)); + void testCheckValid() { + assertTrue(connectionManager.checkValid(connectId)); } @Test - public void testTraced() { - Assert.assertFalse(connectionManager.traced(clientIp)); + void testTraced() { + assertFalse(connectionManager.traced(clientIp)); } @Test - public void testGetConnection() { - Assert.assertEquals(connection, connectionManager.getConnection(connectId)); + void testGetConnection() { + assertEquals(connection, connectionManager.getConnection(connectId)); } @Test - public void testGetConnectionsByClientIp() { - Assert.assertEquals(1, connectionManager.getConnectionByIp(clientIp).size()); + void testGetConnectionsByClientIp() { + assertEquals(1, connectionManager.getConnectionByIp(clientIp).size()); } @Test - public void testGetCurrentConnectionCount() { - Assert.assertEquals(1, connectionManager.getCurrentConnectionCount()); + void testGetCurrentConnectionCount() { + assertEquals(1, connectionManager.getCurrentConnectionCount()); } @Test - public void testRefreshActiveTime() { + void testRefreshActiveTime() { try { connectionManager.refreshActiveTime(connectId); } catch (Exception e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } @Test - public void testLoadSingle() throws NacosException { + void testLoadSingle() throws NacosException { Mockito.when(connectionMeta.isSdkSource()).thenReturn(true); connectionManager.loadSingle(connectId, clientIp); } @Test - public void testCurrentClientsCount() { + void testCurrentClientsCount() { Map labels = new HashMap<>(); labels.put("key", "value"); - Assert.assertEquals(1, connectionManager.currentClientsCount(labels)); + assertEquals(1, connectionManager.currentClientsCount(labels)); } @Test - public void testCurrentSdkCount() { - Assert.assertEquals(1, connectionManager.currentSdkClientCount()); + void testCurrentSdkCount() { + assertEquals(1, connectionManager.currentSdkClientCount()); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/HealthCheckRequestHandlerTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/HealthCheckRequestHandlerTest.java index b77a80b6363..256be12f209 100644 --- a/core/src/test/java/com/alibaba/nacos/core/remote/HealthCheckRequestHandlerTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/remote/HealthCheckRequestHandlerTest.java @@ -18,8 +18,9 @@ package com.alibaba.nacos.core.remote; import com.alibaba.nacos.api.remote.response.HealthCheckResponse; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * {@link HealthCheckRequestHandler} unit test. @@ -27,12 +28,12 @@ * @author chenglu * @date 2021-07-02 19:17 */ -public class HealthCheckRequestHandlerTest { +class HealthCheckRequestHandlerTest { @Test - public void testHandle() { + void testHandle() { HealthCheckRequestHandler handler = new HealthCheckRequestHandler(); HealthCheckResponse response = handler.handle(null, null); - Assert.assertNotNull(response); + assertNotNull(response); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/RequestFiltersTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/RequestFiltersTest.java index 8682562ff81..284d3a825c8 100644 --- a/core/src/test/java/com/alibaba/nacos/core/remote/RequestFiltersTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/remote/RequestFiltersTest.java @@ -21,8 +21,9 @@ import com.alibaba.nacos.api.remote.request.Request; import com.alibaba.nacos.api.remote.request.RequestMeta; import com.alibaba.nacos.api.remote.response.Response; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * {@link RequestFilters} unit test. @@ -30,10 +31,10 @@ * @author chenglu * @date 2021-07-02 19:20 */ -public class RequestFiltersTest { +class RequestFiltersTest { @Test - public void testRegisterFilter() { + void testRegisterFilter() { RequestFilters requestFilters = new RequestFilters(); requestFilters.registerFilter(new AbstractRequestFilter() { @Override @@ -41,7 +42,7 @@ protected Response filter(Request request, RequestMeta meta, Class handlerClazz) return null; } }); - - Assert.assertEquals(1, requestFilters.filters.size()); + + assertEquals(1, requestFilters.filters.size()); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/RequestHandlerRegistryTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/RequestHandlerRegistryTest.java index d124f2a5fed..8ce0a734d05 100644 --- a/core/src/test/java/com/alibaba/nacos/core/remote/RequestHandlerRegistryTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/remote/RequestHandlerRegistryTest.java @@ -18,28 +18,29 @@ package com.alibaba.nacos.core.remote; import com.alibaba.nacos.api.remote.request.HealthCheckRequest; -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.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.event.ContextRefreshedEvent; import java.util.HashMap; import java.util.Map; +import static org.junit.jupiter.api.Assertions.assertNotNull; + /** * {@link RequestHandlerRegistry} unit test. * * @author chenglu * @date 2021-07-02 19:22 */ -@RunWith(MockitoJUnitRunner.class) -public class RequestHandlerRegistryTest { +@ExtendWith(MockitoExtension.class) +class RequestHandlerRegistryTest { @InjectMocks private RequestHandlerRegistry registry; @@ -50,8 +51,8 @@ public class RequestHandlerRegistryTest { @Mock private AnnotationConfigApplicationContext applicationContext; - @Before - public void setUp() { + @BeforeEach + void setUp() { Map handlerMap = new HashMap<>(); handlerMap.put(HealthCheckRequestHandler.class.getSimpleName(), new HealthCheckRequestHandler()); Mockito.when(applicationContext.getBeansOfType(Mockito.any())).thenReturn(handlerMap); @@ -60,7 +61,7 @@ public void setUp() { } @Test - public void testGetByRequestType() { - Assert.assertNotNull(registry.getByRequestType(HealthCheckRequest.class.getSimpleName())); + void testGetByRequestType() { + assertNotNull(registry.getByRequestType(HealthCheckRequest.class.getSimpleName())); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/RpcPushServiceTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/RpcPushServiceTest.java index cd863f2f76b..89bbb7745ef 100644 --- a/core/src/test/java/com/alibaba/nacos/core/remote/RpcPushServiceTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/remote/RpcPushServiceTest.java @@ -21,24 +21,25 @@ import com.alibaba.nacos.api.remote.PushCallBack; import com.alibaba.nacos.common.remote.exception.ConnectionAlreadyClosedException; import com.alibaba.nacos.core.remote.grpc.GrpcConnection; -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.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.UUID; +import static org.junit.jupiter.api.Assertions.fail; + /** * {@link RpcPushService} unit test. * * @author chenglu * @date 2021-07-02 19:35 */ -@RunWith(MockitoJUnitRunner.class) -public class RpcPushServiceTest { +@ExtendWith(MockitoExtension.class) +class RpcPushServiceTest { @InjectMocks private RpcPushService rpcPushService; @@ -52,7 +53,7 @@ public class RpcPushServiceTest { private String connectId = UUID.randomUUID().toString(); @Test - public void testPushWithCallback() { + void testPushWithCallback() { try { Mockito.when(connectionManager.getConnection(Mockito.any())).thenReturn(null); rpcPushService.pushWithCallback(connectId, null, new PushCallBack() { @@ -60,38 +61,36 @@ public void testPushWithCallback() { public long getTimeout() { return 0; } - + @Override public void onSuccess() { System.out.println("success"); } - + @Override public void onFail(Throwable e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } }, null); } catch (Exception e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } @Test - public void testPushWithoutAck() { + void testPushWithoutAck() { Mockito.when(connectionManager.getConnection(Mockito.any())).thenReturn(grpcConnection); try { - Mockito.when(grpcConnection.request(Mockito.any(), Mockito.eq(3000L))) - .thenThrow(ConnectionAlreadyClosedException.class); + Mockito.when(grpcConnection.request(Mockito.any(), Mockito.eq(3000L))).thenThrow(ConnectionAlreadyClosedException.class); rpcPushService.pushWithoutAck(connectId, null); - - Mockito.when(grpcConnection.request(Mockito.any(), Mockito.eq(3000L))) - .thenThrow(NacosException.class); + + Mockito.when(grpcConnection.request(Mockito.any(), Mockito.eq(3000L))).thenThrow(NacosException.class); rpcPushService.pushWithoutAck(connectId, null); } catch (Exception e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } try { @@ -99,7 +98,7 @@ public void testPushWithoutAck() { rpcPushService.pushWithoutAck(connectId, null); } catch (Exception e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } } diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/core/RpcAckCallbackInitorOrCleanerTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/core/RpcAckCallbackInitorOrCleanerTest.java index 84a7286f76a..090f807ab20 100644 --- a/core/src/test/java/com/alibaba/nacos/core/remote/core/RpcAckCallbackInitorOrCleanerTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/remote/core/RpcAckCallbackInitorOrCleanerTest.java @@ -20,7 +20,7 @@ import com.alibaba.nacos.core.remote.Connection; import com.alibaba.nacos.core.remote.ConnectionMeta; import com.alibaba.nacos.core.remote.grpc.GrpcConnection; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashMap; @@ -30,10 +30,10 @@ * @author chenglu * @date 2021-07-01 13:39 */ -public class RpcAckCallbackInitorOrCleanerTest { - +class RpcAckCallbackInitorOrCleanerTest { + @Test - public void testInitAndCleaner() { + void testInitAndCleaner() { String connectId = "11"; ConnectionMeta meta = new ConnectionMeta(connectId, "", "", 80, 80, "GRPC", "", "", new HashMap<>()); Connection connection = new GrpcConnection(meta, null, null); diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/core/ServerLoaderInfoRequestHandlerTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/core/ServerLoaderInfoRequestHandlerTest.java index 24a2571122f..bc72df998af 100644 --- a/core/src/test/java/com/alibaba/nacos/core/remote/core/ServerLoaderInfoRequestHandlerTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/remote/core/ServerLoaderInfoRequestHandlerTest.java @@ -22,13 +22,15 @@ import com.alibaba.nacos.api.remote.request.ServerLoaderInfoRequest; import com.alibaba.nacos.api.remote.response.ServerLoaderInfoResponse; import com.alibaba.nacos.core.remote.ConnectionManager; -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.InjectMocks; 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; +import static org.junit.jupiter.api.Assertions.fail; /** * {@link ServerLoaderInfoRequestHandler} unit test. @@ -36,8 +38,8 @@ * @author chenglu * @date 2021-07-01 12:48 */ -@RunWith(MockitoJUnitRunner.class) -public class ServerLoaderInfoRequestHandlerTest { +@ExtendWith(MockitoExtension.class) +class ServerLoaderInfoRequestHandlerTest { @InjectMocks private ServerLoaderInfoRequestHandler handler; @@ -46,21 +48,21 @@ public class ServerLoaderInfoRequestHandlerTest { private ConnectionManager connectionManager; @Test - public void testHandle() { + void testHandle() { Mockito.when(connectionManager.currentClientsCount()).thenReturn(1); Mockito.when(connectionManager.currentClientsCount(Mockito.any())).thenReturn(1); - + ServerLoaderInfoRequest request = new ServerLoaderInfoRequest(); RequestMeta meta = new RequestMeta(); - + try { ServerLoaderInfoResponse response = handler.handle(request, meta); String sdkConCount = response.getMetricsValue("sdkConCount"); - Assert.assertEquals(sdkConCount, "1"); + assertEquals("1", sdkConCount); } catch (NacosException e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } } diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/core/ServerReloaderRequestHandlerTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/core/ServerReloaderRequestHandlerTest.java index 8b41c72f117..3ea87fa6377 100644 --- a/core/src/test/java/com/alibaba/nacos/core/remote/core/ServerReloaderRequestHandlerTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/remote/core/ServerReloaderRequestHandlerTest.java @@ -22,13 +22,15 @@ import com.alibaba.nacos.api.remote.request.ServerReloadRequest; import com.alibaba.nacos.api.remote.response.ServerReloadResponse; import com.alibaba.nacos.core.remote.ConnectionManager; -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.InjectMocks; 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; +import static org.junit.jupiter.api.Assertions.fail; /** * {@link ServerReloaderRequestHandler} unit test. @@ -36,8 +38,8 @@ * @author chenglu * @date 2021-07-01 13:04 */ -@RunWith(MockitoJUnitRunner.class) -public class ServerReloaderRequestHandlerTest { +@ExtendWith(MockitoExtension.class) +class ServerReloaderRequestHandlerTest { @InjectMocks private ServerReloaderRequestHandler handler; @@ -46,9 +48,9 @@ public class ServerReloaderRequestHandlerTest { private ConnectionManager connectionManager; @Test - public void testHandle() { + void testHandle() { Mockito.when(connectionManager.currentClientsCount(Mockito.any())).thenReturn(2); - + ServerReloadRequest reloadRequest = new ServerReloadRequest(); reloadRequest.setReloadCount(2); reloadRequest.setReloadServer("test"); @@ -57,19 +59,19 @@ public void testHandle() { try { ServerReloadResponse reloadResponse = handler.handle(reloadRequest, meta); - Assert.assertEquals("ignore", reloadResponse.getMessage()); + assertEquals("ignore", reloadResponse.getMessage()); } catch (NacosException e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } reloadRequest.setReloadCount(1); try { ServerReloadResponse reloadResponse = handler.handle(reloadRequest, meta); - Assert.assertEquals("ok", reloadResponse.getMessage()); + assertEquals("ok", reloadResponse.getMessage()); } catch (NacosException e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/grpc/GrpcBiStreamRequestAcceptorTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/GrpcBiStreamRequestAcceptorTest.java index 7968b4da8bd..b75aa50232d 100644 --- a/core/src/test/java/com/alibaba/nacos/core/remote/grpc/GrpcBiStreamRequestAcceptorTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/GrpcBiStreamRequestAcceptorTest.java @@ -27,8 +27,11 @@ import com.alibaba.nacos.common.remote.PayloadRegistry; import com.alibaba.nacos.common.remote.client.grpc.GrpcUtils; import com.alibaba.nacos.core.remote.ConnectionManager; +import com.asarkar.grpc.test.GrpcCleanupExtension; +import com.asarkar.grpc.test.Resources; import io.grpc.Context; import io.grpc.Contexts; +import io.grpc.ManagedChannel; import io.grpc.Metadata; import io.grpc.Server; import io.grpc.ServerCall; @@ -37,32 +40,30 @@ import io.grpc.inprocess.InProcessChannelBuilder; import io.grpc.inprocess.InProcessServerBuilder; import io.grpc.stub.StreamObserver; -import io.grpc.testing.GrpcCleanupRule; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -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.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.IOException; +import java.time.Duration; import java.util.UUID; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; + /** * {@link GrpcBiStreamRequestAcceptor} unit test. * * @author chenglu * @date 2021-06-30 17:11 */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith({MockitoExtension.class, GrpcCleanupExtension.class}) public class GrpcBiStreamRequestAcceptorTest { - @Rule - public GrpcCleanupRule grpcCleanupRule = new GrpcCleanupRule(); - public BiRequestStreamGrpc.BiRequestStreamStub streamStub; @Mock @@ -77,13 +78,12 @@ public class GrpcBiStreamRequestAcceptorTest { private String requestId = UUID.randomUUID().toString(); - @Before - public void setUp() throws IOException { + @BeforeEach + void setUp(Resources resources) throws IOException { PayloadRegistry.init(); String serverName = InProcessServerBuilder.generateName(); String remoteIp = "127.0.0.1"; - Server mockServer = InProcessServerBuilder - .forName(serverName).directExecutor().addService(acceptor) + Server mockServer = InProcessServerBuilder.forName(serverName).directExecutor().addService(acceptor) .intercept(new ServerInterceptor() { @Override public ServerCall.Listener interceptCall(ServerCall serverCall, Metadata metadata, @@ -94,20 +94,21 @@ public ServerCall.Listener interceptCall(ServerCall serverCall, .withValue(GrpcServerConstants.CONTEXT_KEY_CONN_REMOTE_IP, remoteIp); return Contexts.interceptCall(ctx, serverCall, metadata, serverCallHandler); } - }) - .build(); - grpcCleanupRule.register(mockServer.start()); - streamStub = BiRequestStreamGrpc.newStub(grpcCleanupRule.register(InProcessChannelBuilder.forName(serverName).directExecutor().build())); + }).build(); + resources.register(mockServer.start(), Duration.ofSeconds(20)); + ManagedChannel channel = InProcessChannelBuilder.forName(serverName).directExecutor().build(); + resources.register(channel, Duration.ofSeconds(20L)); + streamStub = BiRequestStreamGrpc.newStub(channel); Mockito.doReturn(true).when(connectionManager).traced(Mockito.any()); } @Test - public void testConnectionSetupRequest() { + void testConnectionSetupRequest() { StreamObserver streamObserver = new StreamObserver() { @Override public void onNext(Payload payload) { System.out.println("Receive data from server, data: " + payload); - Assert.assertNotNull(payload); + assertNotNull(payload); ConnectResetRequest connectResetRequest = (ConnectResetRequest) GrpcUtils.parse(payload); Response response = new ConnectResetResponse(); response.setRequestId(connectResetRequest.getRequestId()); @@ -115,12 +116,12 @@ public void onNext(Payload payload) { payloadStreamObserver.onNext(res); payloadStreamObserver.onCompleted(); } - + @Override public void onError(Throwable throwable) { - Assert.fail(throwable.getMessage()); + fail(throwable.getMessage()); } - + @Override public void onCompleted() { System.out.println("complete"); @@ -130,7 +131,7 @@ public void onCompleted() { RequestMeta metadata = new RequestMeta(); metadata.setClientIp("127.0.0.1"); metadata.setConnectionId(connectId); - + ConnectionSetupRequest connectionSetupRequest = new ConnectionSetupRequest(); connectionSetupRequest.setRequestId(requestId); connectionSetupRequest.setClientVersion("2.0.3"); diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/grpc/GrpcConnectionTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/GrpcConnectionTest.java index 102b4b8a0fa..171e4b1d417 100644 --- a/core/src/test/java/com/alibaba/nacos/core/remote/grpc/GrpcConnectionTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/GrpcConnectionTest.java @@ -32,25 +32,28 @@ import io.grpc.netty.shaded.io.netty.channel.Channel; import io.grpc.netty.shaded.io.netty.channel.DefaultEventLoop; import io.grpc.stub.ServerCallStreamObserver; -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 org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import java.io.IOException; import java.util.HashMap; import java.util.Map; -@RunWith(MockitoJUnitRunner.class) -public class GrpcConnectionTest { - - @Mock - private Channel channel; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class GrpcConnectionTest { @Mock ServerCallStreamObserver streamObserver; @@ -65,18 +68,21 @@ public class GrpcConnectionTest { MockedStatic controlManagerCenterMockedStatic; - @After - public void setDown() throws IOException { + @Mock + private Channel channel; + + @AfterEach + void setDown() throws IOException { if (controlManagerCenterMockedStatic != null) { controlManagerCenterMockedStatic.close(); } } - @Before - public void setUp() throws IOException { + @BeforeEach + void setUp() throws IOException { String ip = "1.1.1.1"; - ConnectionMeta connectionMeta = new ConnectionMeta("connectId" + System.currentTimeMillis(), ip, ip, 8888, 9848, - "GRPC", "", "", new HashMap<>()); + ConnectionMeta connectionMeta = new ConnectionMeta("connectId" + System.currentTimeMillis(), ip, ip, 8888, 9848, "GRPC", "", "", + new HashMap<>()); Mockito.when(channel.isOpen()).thenReturn(true); Mockito.when(channel.isActive()).thenReturn(true); connection = new GrpcConnection(connectionMeta, streamObserver, channel); @@ -85,56 +91,56 @@ public void setUp() throws IOException { } @Test - public void testStatusRuntimeException() { + void testStatusRuntimeException() { Mockito.doReturn(new DefaultEventLoop()).when(channel).eventLoop(); Mockito.doThrow(new StatusRuntimeException(Status.CANCELLED)).when(streamObserver).onNext(Mockito.any()); Mockito.doReturn(true).when(streamObserver).isReady(); try { connection.request(new NotifySubscriberRequest(), 3000L); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertTrue(e instanceof ConnectionAlreadyClosedException); - Assert.assertTrue(e.getCause() instanceof StatusRuntimeException); + assertTrue(e instanceof ConnectionAlreadyClosedException); + assertTrue(e.getCause() instanceof StatusRuntimeException); } } @Test - public void testIllegalStateException() { + void testIllegalStateException() { Mockito.doReturn(new DefaultEventLoop()).when(channel).eventLoop(); Mockito.doThrow(new IllegalStateException()).when(streamObserver).onNext(Mockito.any()); Mockito.doReturn(true).when(streamObserver).isReady(); try { connection.request(new NotifySubscriberRequest(), 1000L); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertTrue(e instanceof ConnectionAlreadyClosedException); - Assert.assertTrue(e.getCause() instanceof IllegalStateException); + assertTrue(e instanceof ConnectionAlreadyClosedException); + assertTrue(e.getCause() instanceof IllegalStateException); } } @Test - public void testOtherException() { + void testOtherException() { Mockito.doReturn(new DefaultEventLoop()).when(channel).eventLoop(); Mockito.doThrow(new Error("OOM")).when(streamObserver).onNext(Mockito.any()); Mockito.doReturn(true).when(streamObserver).isReady(); try { connection.request(new NotifySubscriberRequest(), 3000L); - Assert.assertTrue(false); + assertTrue(false); } catch (Throwable e) { - Assert.assertTrue(e instanceof NacosRuntimeException); - Assert.assertTrue(e.getCause() instanceof Error); + assertTrue(e instanceof NacosRuntimeException); + assertTrue(e.getCause() instanceof Error); } } @Test - public void testNormal() { + void testNormal() { Mockito.doReturn(new DefaultEventLoop()).when(channel).eventLoop(); Mockito.doReturn(true).when(streamObserver).isReady(); - Assert.assertTrue(connection.isConnected()); + assertTrue(connection.isConnected()); try { new Thread(new Runnable() { @Override @@ -151,13 +157,11 @@ public void run() { throw new RuntimeException(e); } } - Map.Entry next = stringDefaultRequestFutureMap.entrySet() - .iterator().next(); + Map.Entry next = stringDefaultRequestFutureMap.entrySet().iterator().next(); NotifySubscriberResponse notifySubscriberResponse = new NotifySubscriberResponse(); notifySubscriberResponse.setRequestId(next.getValue().getRequestId()); try { - RpcAckCallbackSynchronizer.ackNotify(connection.getMetaInfo().getConnectionId(), - notifySubscriberResponse); + RpcAckCallbackSynchronizer.ackNotify(connection.getMetaInfo().getConnectionId(), notifySubscriberResponse); } catch (Exception e) { //ignore } @@ -165,15 +169,15 @@ public void run() { } }).start(); connection.request(new NotifySubscriberRequest(), 3000L); - Assert.assertTrue(true); + assertTrue(true); } catch (Throwable e) { e.printStackTrace(); - Assert.assertFalse(true); + assertFalse(true); } } @Test - public void testBusy() { + void testBusy() { controlManagerCenterMockedStatic = Mockito.mockStatic(ControlManagerCenter.class); Mockito.when(ControlManagerCenter.getInstance()).thenReturn(controlManagerCenter); Mockito.when(ControlManagerCenter.getInstance().getTpsControlManager()).thenReturn(tpsControlManager); @@ -182,9 +186,9 @@ public void testBusy() { try { connection.request(new NotifySubscriberRequest(), 3000L); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertTrue(e instanceof ConnectionBusyException); + assertTrue(e instanceof ConnectionBusyException); } try { @@ -194,17 +198,17 @@ public void testBusy() { } try { connection.request(new NotifySubscriberRequest(), 3000L); - Assert.assertTrue(false); + assertTrue(false); } catch (Exception e) { - Assert.assertTrue(e instanceof ConnectionBusyException); + assertTrue(e instanceof ConnectionBusyException); } - Assert.assertTrue(connection.getMetaInfo().pushQueueBlockTimesLastOver(3000)); + assertTrue(connection.getMetaInfo().pushQueueBlockTimesLastOver(3000)); } @Test - public void testClose() { + void testClose() { Mockito.doThrow(new IllegalStateException()).when(streamObserver).onCompleted(); connection.close(); diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/grpc/GrpcRequestAcceptorTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/GrpcRequestAcceptorTest.java index 47183b8ec7e..6dae97b9734 100644 --- a/core/src/test/java/com/alibaba/nacos/core/remote/grpc/GrpcRequestAcceptorTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/GrpcRequestAcceptorTest.java @@ -36,8 +36,11 @@ import com.alibaba.nacos.core.remote.RequestHandler; import com.alibaba.nacos.core.remote.RequestHandlerRegistry; import com.alibaba.nacos.sys.utils.ApplicationUtils; +import com.asarkar.grpc.test.GrpcCleanupExtension; +import com.asarkar.grpc.test.Resources; import io.grpc.Context; import io.grpc.Contexts; +import io.grpc.ManagedChannel; import io.grpc.Metadata; import io.grpc.ServerCall; import io.grpc.ServerCallHandler; @@ -45,33 +48,32 @@ import io.grpc.inprocess.InProcessChannelBuilder; import io.grpc.inprocess.InProcessServerBuilder; import io.grpc.stub.StreamObserver; -import io.grpc.testing.GrpcCleanupRule; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -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.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.IOException; +import java.time.Duration; import java.util.HashMap; import java.util.UUID; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + /** * {@link GrpcRequestAcceptor} unit test. * * @author chenglu * @date 2021-07-01 10:49 */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith({MockitoExtension.class, GrpcCleanupExtension.class}) public class GrpcRequestAcceptorTest { - @Rule - public GrpcCleanupRule grpcCleanupRule = new GrpcCleanupRule(); - @Mock private ConnectionManager connectionManager; @@ -89,12 +91,12 @@ public class GrpcRequestAcceptorTest { private MockRequestHandler mockHandler; - @Before - public void setUp() throws IOException { + @BeforeEach + void setUp(Resources resources) throws IOException { String serverName = InProcessServerBuilder.generateName(); String remoteIp = "127.0.0.1"; - grpcCleanupRule.register(InProcessServerBuilder.forName(serverName).directExecutor().addService(acceptor) - .intercept(new ServerInterceptor() { + resources.register( + InProcessServerBuilder.forName(serverName).directExecutor().addService(acceptor).intercept(new ServerInterceptor() { @Override public ServerCall.Listener interceptCall(ServerCall serverCall, Metadata metadata, ServerCallHandler serverCallHandler) { @@ -104,15 +106,16 @@ public ServerCall.Listener interceptCall(ServerCall serverCall, .withValue(GrpcServerConstants.CONTEXT_KEY_CONN_REMOTE_IP, remoteIp); return Contexts.interceptCall(ctx, serverCall, metadata, serverCallHandler); } - }).build().start()); - streamStub = RequestGrpc.newStub( - grpcCleanupRule.register(InProcessChannelBuilder.forName(serverName).directExecutor().build())); + }).build().start(), Duration.ofSeconds(20L)); + ManagedChannel channel = InProcessChannelBuilder.forName(serverName).directExecutor().build(); + resources.register(channel, Duration.ofSeconds(20L)); + streamStub = RequestGrpc.newStub(channel); mockHandler = new MockRequestHandler(); PayloadRegistry.init(); } @Test - public void testApplicationUnStarted() { + void testApplicationUnStarted() { RequestMeta metadata = new RequestMeta(); metadata.setClientIp("127.0.0.1"); metadata.setConnectionId(connectId); @@ -125,14 +128,14 @@ public void testApplicationUnStarted() { public void onNext(Payload payload) { System.out.println("Receive data from server: " + payload); Object res = GrpcUtils.parse(payload); - Assert.assertTrue(res instanceof ErrorResponse); + assertTrue(res instanceof ErrorResponse); ErrorResponse errorResponse = (ErrorResponse) res; - Assert.assertEquals(errorResponse.getErrorCode(), NacosException.INVALID_SERVER_STATUS); + assertEquals(NacosException.INVALID_SERVER_STATUS, errorResponse.getErrorCode()); } @Override public void onError(Throwable throwable) { - Assert.fail(throwable.getMessage()); + fail(throwable.getMessage()); } @Override @@ -145,7 +148,7 @@ public void onCompleted() { } @Test - public void testServerCheckRequest() { + void testServerCheckRequest() { ApplicationUtils.setStarted(true); RequestMeta metadata = new RequestMeta(); metadata.setClientIp("127.0.0.1"); @@ -159,12 +162,12 @@ public void testServerCheckRequest() { public void onNext(Payload payload) { System.out.println("Receive data from server: " + payload); Object res = GrpcUtils.parse(payload); - Assert.assertTrue(res instanceof ServerCheckResponse); + assertTrue(res instanceof ServerCheckResponse); } @Override public void onError(Throwable throwable) { - Assert.fail(throwable.getMessage()); + fail(throwable.getMessage()); } @Override @@ -178,7 +181,7 @@ public void onCompleted() { } @Test - public void testNoRequestHandler() { + void testNoRequestHandler() { ApplicationUtils.setStarted(true); RequestMeta metadata = new RequestMeta(); metadata.setClientIp("127.0.0.1"); @@ -192,15 +195,15 @@ public void testNoRequestHandler() { public void onNext(Payload payload) { System.out.println("Receive data from server: " + payload); Object res = GrpcUtils.parse(payload); - Assert.assertTrue(res instanceof ErrorResponse); + assertTrue(res instanceof ErrorResponse); ErrorResponse errorResponse = (ErrorResponse) res; - Assert.assertEquals(errorResponse.getErrorCode(), NacosException.NO_HANDLER); + assertEquals(NacosException.NO_HANDLER, errorResponse.getErrorCode()); } @Override public void onError(Throwable throwable) { - Assert.fail(throwable.getMessage()); + fail(throwable.getMessage()); } @Override @@ -214,7 +217,7 @@ public void onCompleted() { } @Test - public void testConnectionNotRegister() { + void testConnectionNotRegister() { ApplicationUtils.setStarted(true); Mockito.when(requestHandlerRegistry.getByRequestType(Mockito.anyString())).thenReturn(mockHandler); Mockito.when(connectionManager.checkValid(Mockito.any())).thenReturn(false); @@ -231,15 +234,15 @@ public void testConnectionNotRegister() { public void onNext(Payload payload) { System.out.println("Receive data from server: " + payload); Object res = GrpcUtils.parse(payload); - Assert.assertTrue(res instanceof ErrorResponse); + assertTrue(res instanceof ErrorResponse); ErrorResponse errorResponse = (ErrorResponse) res; - Assert.assertEquals(errorResponse.getErrorCode(), NacosException.UN_REGISTER); + assertEquals(NacosException.UN_REGISTER, errorResponse.getErrorCode()); } @Override public void onError(Throwable throwable) { - Assert.fail(throwable.getMessage()); + fail(throwable.getMessage()); } @Override @@ -253,7 +256,7 @@ public void onCompleted() { } @Test - public void testRequestContentError() { + void testRequestContentError() { ApplicationUtils.setStarted(true); Mockito.when(requestHandlerRegistry.getByRequestType(Mockito.anyString())).thenReturn(mockHandler); Mockito.when(connectionManager.checkValid(Mockito.any())).thenReturn(true); @@ -263,15 +266,15 @@ public void testRequestContentError() { public void onNext(Payload payload) { System.out.println("Receive data from server: " + payload); Object res = GrpcUtils.parse(payload); - Assert.assertTrue(res instanceof ErrorResponse); + assertTrue(res instanceof ErrorResponse); ErrorResponse errorResponse = (ErrorResponse) res; - Assert.assertEquals(errorResponse.getErrorCode(), NacosException.BAD_GATEWAY); + assertEquals(NacosException.BAD_GATEWAY, errorResponse.getErrorCode()); } @Override public void onError(Throwable throwable) { - Assert.fail(throwable.getMessage()); + fail(throwable.getMessage()); } @Override @@ -285,13 +288,12 @@ public void onCompleted() { } @Test - public void testHandleRequestSuccess() { + void testHandleRequestSuccess() { ApplicationUtils.setStarted(true); Mockito.when(requestHandlerRegistry.getByRequestType(Mockito.anyString())).thenReturn(mockHandler); Mockito.when(connectionManager.checkValid(Mockito.any())).thenReturn(true); String ip = "1.1.1.1"; - ConnectionMeta connectionMeta = new ConnectionMeta(connectId, ip, ip, 8888, 9848, "GRPC", "", "", - new HashMap<>()); + ConnectionMeta connectionMeta = new ConnectionMeta(connectId, ip, ip, 8888, 9848, "GRPC", "", "", new HashMap<>()); Connection connection = new GrpcConnection(connectionMeta, null, null); Mockito.when(connectionManager.getConnection(Mockito.any())).thenReturn(connection); @@ -306,12 +308,12 @@ public void testHandleRequestSuccess() { public void onNext(Payload payload) { System.out.println("Receive data from server: " + payload); Object res = GrpcUtils.parse(payload); - Assert.assertTrue(res instanceof HealthCheckResponse); + assertTrue(res instanceof HealthCheckResponse); } @Override public void onError(Throwable throwable) { - Assert.fail(throwable.getMessage()); + fail(throwable.getMessage()); } @Override @@ -325,7 +327,7 @@ public void onCompleted() { } @Test - public void testHandleRequestError() { + void testHandleRequestError() { ApplicationUtils.setStarted(true); Mockito.when(requestHandlerRegistry.getByRequestType(Mockito.anyString())).thenReturn(mockHandler); Mockito.when(connectionManager.checkValid(Mockito.any())).thenReturn(true); @@ -341,15 +343,15 @@ public void testHandleRequestError() { public void onNext(Payload payload) { System.out.println("Receive data from server: " + payload); Object res = GrpcUtils.parse(payload); - Assert.assertTrue(res instanceof ErrorResponse); + assertTrue(res instanceof ErrorResponse); ErrorResponse errorResponse = (ErrorResponse) res; - Assert.assertEquals(errorResponse.getErrorCode(), NacosException.SERVER_ERROR); + assertEquals(NacosException.SERVER_ERROR, errorResponse.getErrorCode()); } @Override public void onError(Throwable throwable) { - Assert.fail(throwable.getMessage()); + fail(throwable.getMessage()); } @Override diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/grpc/GrpcServerTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/GrpcServerTest.java index 2b99a809017..b4a9eb49191 100644 --- a/core/src/test/java/com/alibaba/nacos/core/remote/grpc/GrpcServerTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/GrpcServerTest.java @@ -20,62 +20,66 @@ import com.alibaba.nacos.common.remote.ConnectionType; import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.utils.ApplicationUtils; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +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 org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.mock.env.MockEnvironment; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * {@link GrpcSdkServer} and {@link GrpcClusterServer} unit test. * * @author chenglu * @date 2021-06-30 14:32 */ -@RunWith(MockitoJUnitRunner.Silent.class) -public class GrpcServerTest { +@MockitoSettings(strictness = Strictness.LENIENT) +@ExtendWith(MockitoExtension.class) +class GrpcServerTest { static MockedStatic applicationUtilsMockedStatic = null; private BaseGrpcServer grpcSdkServer; - @BeforeClass - public static void setUpBeforeClass() { + @BeforeAll + static void setUpBeforeClass() { EnvUtil.setEnvironment(new MockEnvironment()); applicationUtilsMockedStatic = Mockito.mockStatic(ApplicationUtils.class); } - @AfterClass - public static void after() { + @AfterAll + static void after() { applicationUtilsMockedStatic.close(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (null != grpcSdkServer) { grpcSdkServer.stopServer(); } } @Test - public void testGrpcSdkServer() throws Exception { + void testGrpcSdkServer() throws Exception { grpcSdkServer = new GrpcSdkServer(); grpcSdkServer.start(); - Assert.assertEquals(grpcSdkServer.getConnectionType(), ConnectionType.GRPC); - Assert.assertEquals(grpcSdkServer.rpcPortOffset(), 1000); + assertEquals(ConnectionType.GRPC, grpcSdkServer.getConnectionType()); + assertEquals(1000, grpcSdkServer.rpcPortOffset()); } @Test - public void testGrpcClusterServer() throws Exception { + void testGrpcClusterServer() throws Exception { grpcSdkServer = new GrpcClusterServer(); grpcSdkServer.start(); - Assert.assertEquals(grpcSdkServer.getConnectionType(), ConnectionType.GRPC); - Assert.assertEquals(grpcSdkServer.rpcPortOffset(), 1001); + assertEquals(ConnectionType.GRPC, grpcSdkServer.getConnectionType()); + assertEquals(1001, grpcSdkServer.rpcPortOffset()); grpcSdkServer.stopServer(); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/ClusterProtocolNegotiatorBuilderSingletonTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/ClusterProtocolNegotiatorBuilderSingletonTest.java new file mode 100644 index 00000000000..e550e94149c --- /dev/null +++ b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/ClusterProtocolNegotiatorBuilderSingletonTest.java @@ -0,0 +1,70 @@ +/* + * Copyright 1999-2020 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.remote.grpc.negotiator; + +import com.alibaba.nacos.common.utils.Pair; +import com.alibaba.nacos.sys.env.EnvUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.mock.env.MockEnvironment; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +/** + * Test ClusterProtocolNegotiatorBuilderSingleton. + * + * @author stone-98 + * @date 2024/2/21 + */ +class ClusterProtocolNegotiatorBuilderSingletonTest { + + @BeforeEach + void setUp() throws Exception { + ConfigurableEnvironment environment = new MockEnvironment(); + EnvUtil.setEnvironment(environment); + } + + @AfterEach + void tearDown() throws Exception { + } + + @Test + void testSingletonInstance() { + AbstractProtocolNegotiatorBuilderSingleton singleton1 = ClusterProtocolNegotiatorBuilderSingleton.getSingleton(); + AbstractProtocolNegotiatorBuilderSingleton singleton2 = ClusterProtocolNegotiatorBuilderSingleton.getSingleton(); + assertSame(singleton1, singleton2); + } + + @Test + void testDefaultBuilderPair() { + Pair defaultPair = ClusterProtocolNegotiatorBuilderSingleton.getSingleton().defaultBuilderPair(); + assertNotNull(defaultPair); + assertEquals(ClusterProtocolNegotiatorBuilderSingleton.TYPE_PROPERTY_KEY, defaultPair.getFirst()); + assertNotNull(defaultPair.getSecond()); + } + + @Test + void testType() { + String type = ClusterProtocolNegotiatorBuilderSingleton.getSingleton().type(); + assertNotNull(type); + assertEquals(ClusterProtocolNegotiatorBuilderSingleton.TYPE_PROPERTY_KEY, type); + } +} diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/SdkProtocolNegotiatorBuilderSingletonTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/SdkProtocolNegotiatorBuilderSingletonTest.java new file mode 100644 index 00000000000..61e5761de19 --- /dev/null +++ b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/SdkProtocolNegotiatorBuilderSingletonTest.java @@ -0,0 +1,70 @@ +/* + * Copyright 1999-2020 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.remote.grpc.negotiator; + +import com.alibaba.nacos.common.utils.Pair; +import com.alibaba.nacos.sys.env.EnvUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.mock.env.MockEnvironment; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +/** + * Test SdkProtocolNegotiatorBuilderSingleton. + * + * @author stone-98 + * @date 2024/2/21 + */ +class SdkProtocolNegotiatorBuilderSingletonTest { + + @BeforeEach + void setUp() throws Exception { + ConfigurableEnvironment environment = new MockEnvironment(); + EnvUtil.setEnvironment(environment); + } + + @AfterEach + void tearDown() throws Exception { + } + + @Test + void testSingletonInstance() { + AbstractProtocolNegotiatorBuilderSingleton singleton1 = SdkProtocolNegotiatorBuilderSingleton.getSingleton(); + AbstractProtocolNegotiatorBuilderSingleton singleton2 = SdkProtocolNegotiatorBuilderSingleton.getSingleton(); + assertSame(singleton1, singleton2); + } + + @Test + void testDefaultBuilderPair() { + Pair defaultPair = SdkProtocolNegotiatorBuilderSingleton.getSingleton().defaultBuilderPair(); + assertNotNull(defaultPair); + assertEquals(SdkProtocolNegotiatorBuilderSingleton.TYPE_PROPERTY_KEY, defaultPair.getFirst()); + assertNotNull(defaultPair.getSecond()); + } + + @Test + void testType() { + String type = SdkProtocolNegotiatorBuilderSingleton.getSingleton().type(); + assertNotNull(type); + assertEquals(SdkProtocolNegotiatorBuilderSingleton.TYPE_PROPERTY_KEY, type); + } +} diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/ClusterDefaultTlsProtocolNegotiatorBuilderTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/ClusterDefaultTlsProtocolNegotiatorBuilderTest.java new file mode 100644 index 00000000000..a55d2f49463 --- /dev/null +++ b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/ClusterDefaultTlsProtocolNegotiatorBuilderTest.java @@ -0,0 +1,82 @@ +/* + * Copyright 1999-2020 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.remote.grpc.negotiator.tls; + +import com.alibaba.nacos.common.remote.client.RpcConstants; +import com.alibaba.nacos.core.remote.grpc.negotiator.NacosGrpcProtocolNegotiator; +import com.alibaba.nacos.sys.env.EnvUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.MutablePropertySources; +import org.springframework.core.env.PropertiesPropertySource; +import org.springframework.mock.env.MockEnvironment; + +import java.util.Properties; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * Test ClusterDefaultTlsProtocolNegotiatorBuilder. + * + * @author stone-98 + * @date 2023/12/25 + */ +class ClusterDefaultTlsProtocolNegotiatorBuilderTest { + + private ConfigurableEnvironment environment; + + private ClusterDefaultTlsProtocolNegotiatorBuilder builder; + + @BeforeEach + void setUp() { + environment = new MockEnvironment(); + EnvUtil.setEnvironment(environment); + builder = new ClusterDefaultTlsProtocolNegotiatorBuilder(); + } + + @AfterEach + void tearDown() throws NoSuchFieldException, IllegalAccessException { + } + + @Test + void testBuildTlsDisabled() { + assertNull(builder.build()); + } + + @Test + void testBuildTlsEnabled() { + Properties properties = new Properties(); + properties.setProperty(RpcConstants.NACOS_PEER_RPC + ".enableTls", "true"); + properties.setProperty(RpcConstants.NACOS_PEER_RPC + ".compatibility", "false"); + properties.setProperty(RpcConstants.NACOS_PEER_RPC + ".ciphers", "ECDHE-RSA-AES128-GCM-SHA256,ECDHE-RSA-AES256-GCM-SHA384"); + properties.setProperty(RpcConstants.NACOS_PEER_RPC + ".protocols", "TLSv1.2,TLSv1.3"); + properties.setProperty(RpcConstants.NACOS_PEER_RPC + ".certPrivateKey", "test-server-key.pem"); + properties.setProperty(RpcConstants.NACOS_PEER_RPC + ".certChainFile", "test-server-cert.pem"); + properties.setProperty(RpcConstants.NACOS_PEER_RPC + ".trustCollectionCertFile", "test-ca-cert.pem"); + + PropertiesPropertySource propertySource = new PropertiesPropertySource("myPropertySource", properties); + MutablePropertySources propertySources = environment.getPropertySources(); + propertySources.addLast(propertySource); + + NacosGrpcProtocolNegotiator negotiator = builder.build(); + assertNotNull(negotiator); + } + +} diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/DefaultTlsContextBuilderTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/DefaultTlsContextBuilderTest.java deleted file mode 100644 index f947a367a83..00000000000 --- a/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/DefaultTlsContextBuilderTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright 1999-2023 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.core.remote.grpc.negotiator.tls; - -import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; -import com.alibaba.nacos.core.remote.tls.RpcServerTlsConfig; -import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.mock.env.MockEnvironment; - -import java.lang.reflect.Field; - -public class DefaultTlsContextBuilderTest { - - private ConfigurableEnvironment environment; - - @Before - public void setUp() throws Exception { - environment = new MockEnvironment(); - EnvUtil.setEnvironment(environment); - RpcServerTlsConfig.getInstance().setEnableTls(true); - } - - @After - public void tearDown() throws Exception { - RpcServerTlsConfig.getInstance().setEnableTls(false); - RpcServerTlsConfig.getInstance().setTrustAll(false); - RpcServerTlsConfig.getInstance().setMutualAuthEnable(false); - RpcServerTlsConfig.getInstance().setCertChainFile(null); - RpcServerTlsConfig.getInstance().setCertPrivateKey(null); - RpcServerTlsConfig.getInstance().setCiphers(null); - RpcServerTlsConfig.getInstance().setProtocols(null); - RpcServerTlsConfig.getInstance().setTrustCollectionCertFile(null); - RpcServerTlsConfig.getInstance().setSslProvider(""); - clearRpcServerTlsConfigInstance(); - } - - @Test(expected = IllegalArgumentException.class) - public void testGetSslContextIllegal() { - DefaultTlsContextBuilder.getSslContext(RpcServerTlsConfig.getInstance()); - } - - @Test - public void testGetSslContextWithoutMutual() { - RpcServerTlsConfig grpcServerConfig = RpcServerTlsConfig.getInstance(); - grpcServerConfig.setCiphers("ECDHE-RSA-AES128-GCM-SHA256,ECDHE-RSA-AES256-GCM-SHA384"); - grpcServerConfig.setProtocols("TLSv1.2,TLSv1.3"); - grpcServerConfig.setCertPrivateKey("test-server-key.pem"); - grpcServerConfig.setCertChainFile("test-server-cert.pem"); - DefaultTlsContextBuilder.getSslContext(RpcServerTlsConfig.getInstance()); - } - - @Test - public void testGetSslContextWithMutual() { - RpcServerTlsConfig grpcServerConfig = RpcServerTlsConfig.getInstance(); - grpcServerConfig.setTrustAll(true); - grpcServerConfig.setMutualAuthEnable(true); - grpcServerConfig.setCiphers("ECDHE-RSA-AES128-GCM-SHA256,ECDHE-RSA-AES256-GCM-SHA384"); - grpcServerConfig.setProtocols("TLSv1.2,TLSv1.3"); - grpcServerConfig.setCertPrivateKey("test-server-key.pem"); - grpcServerConfig.setCertChainFile("test-server-cert.pem"); - DefaultTlsContextBuilder.getSslContext(RpcServerTlsConfig.getInstance()); - } - - @Test - public void testGetSslContextWithMutualAndPart() { - RpcServerTlsConfig grpcServerConfig = RpcServerTlsConfig.getInstance(); - grpcServerConfig.setMutualAuthEnable(true); - grpcServerConfig.setCiphers("ECDHE-RSA-AES128-GCM-SHA256,ECDHE-RSA-AES256-GCM-SHA384"); - grpcServerConfig.setProtocols("TLSv1.2,TLSv1.3"); - grpcServerConfig.setCertPrivateKey("test-server-key.pem"); - grpcServerConfig.setCertChainFile("test-server-cert.pem"); - grpcServerConfig.setTrustCollectionCertFile("test-ca-cert.pem"); - DefaultTlsContextBuilder.getSslContext(RpcServerTlsConfig.getInstance()); - } - - @Test(expected = IllegalArgumentException.class) - public void testGetSslContextWithMutualAndPartIllegal() { - RpcServerTlsConfig grpcServerConfig = RpcServerTlsConfig.getInstance(); - grpcServerConfig.setMutualAuthEnable(true); - grpcServerConfig.setCiphers("ECDHE-RSA-AES128-GCM-SHA256,ECDHE-RSA-AES256-GCM-SHA384"); - grpcServerConfig.setProtocols("TLSv1.2,TLSv1.3"); - grpcServerConfig.setCertPrivateKey("test-server-key.pem"); - grpcServerConfig.setCertChainFile("test-server-cert.pem"); - DefaultTlsContextBuilder.getSslContext(RpcServerTlsConfig.getInstance()); - } - - @Test(expected = NacosRuntimeException.class) - public void testGetSslContextForNonExistFile() { - RpcServerTlsConfig grpcServerConfig = RpcServerTlsConfig.getInstance(); - grpcServerConfig.setCiphers("ECDHE-RSA-AES128-GCM-SHA256,ECDHE-RSA-AES256-GCM-SHA384"); - grpcServerConfig.setProtocols("TLSv1.2,TLSv1.3"); - grpcServerConfig.setCertPrivateKey("non-exist-server-key.pem"); - grpcServerConfig.setCertChainFile("non-exist-cert.pem"); - DefaultTlsContextBuilder.getSslContext(RpcServerTlsConfig.getInstance()); - } - - private static void clearRpcServerTlsConfigInstance() throws Exception { - Field instanceField = RpcServerTlsConfig.class.getDeclaredField("instance"); - instanceField.setAccessible(true); - instanceField.set(null, null); - } -} \ No newline at end of file diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/DefaultTlsProtocolNegotiatorBuilderTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/DefaultTlsProtocolNegotiatorBuilderTest.java deleted file mode 100644 index 24e0a6fd782..00000000000 --- a/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/DefaultTlsProtocolNegotiatorBuilderTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 1999-2023 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.core.remote.grpc.negotiator.tls; - -import com.alibaba.nacos.core.remote.tls.RpcServerTlsConfig; -import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.mock.env.MockEnvironment; - -import java.lang.reflect.Field; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -public class DefaultTlsProtocolNegotiatorBuilderTest { - - private ConfigurableEnvironment environment; - - private DefaultTlsProtocolNegotiatorBuilder builder; - - @Before - public void setUp() throws Exception { - environment = new MockEnvironment(); - EnvUtil.setEnvironment(environment); - builder = new DefaultTlsProtocolNegotiatorBuilder(); - } - - @After - public void tearDown() throws Exception { - RpcServerTlsConfig.getInstance().setEnableTls(false); - RpcServerTlsConfig.getInstance().setCertChainFile(null); - RpcServerTlsConfig.getInstance().setCertPrivateKey(null); - clearRpcServerTlsConfigInstance(); - } - - @Test - public void testBuildDisabled() { - assertNull(builder.build()); - } - - @Test - public void testBuildEnabled() { - RpcServerTlsConfig.getInstance().setEnableTls(true); - RpcServerTlsConfig.getInstance().setCertPrivateKey("test-server-key.pem"); - RpcServerTlsConfig.getInstance().setCertChainFile("test-server-cert.pem"); - assertNotNull(builder.build()); - } - - private static void clearRpcServerTlsConfigInstance() throws Exception { - Field instanceField = RpcServerTlsConfig.class.getDeclaredField("instance"); - instanceField.setAccessible(true); - instanceField.set(null, null); - } -} \ No newline at end of file diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/RpcServerSslContextRefresherHolderTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/RpcServerSslContextRefresherHolderTest.java new file mode 100644 index 00000000000..95e8872e07b --- /dev/null +++ b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/RpcServerSslContextRefresherHolderTest.java @@ -0,0 +1,53 @@ +/* + * Copyright 1999-2020 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.remote.grpc.negotiator.tls; + +import com.alibaba.nacos.sys.env.EnvUtil; +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.jupiter.MockitoExtension; +import org.springframework.core.env.ConfigurableEnvironment; + + +/** + * Test RpcServerSslContextRefresherHolder. + * + * @author stone-98 + */ +@ExtendWith(MockitoExtension.class) +class RpcServerSslContextRefresherHolderTest { + + @Mock + private ConfigurableEnvironment environment; + + @BeforeEach + void setUp() { + EnvUtil.setEnvironment(environment); + } + + @AfterEach + void tearDown() { + } + + @Test + void testInit() { + } + +} diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/SdkDefaultTlsContextBuilderTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/SdkDefaultTlsContextBuilderTest.java new file mode 100644 index 00000000000..73a603cbdd6 --- /dev/null +++ b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/SdkDefaultTlsContextBuilderTest.java @@ -0,0 +1,117 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.remote.grpc.negotiator.tls; + +import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; +import com.alibaba.nacos.core.remote.tls.RpcServerTlsConfig; +import com.alibaba.nacos.sys.env.EnvUtil; +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.jupiter.MockitoExtension; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.mock.env.MockEnvironment; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.when; + +/** + * {@link DefaultTlsContextBuilder} unit test. + * + * @author stone-98 + * @date 2024-03-11 17:11 + */ +@ExtendWith(MockitoExtension.class) +class SdkDefaultTlsContextBuilderTest { + + private ConfigurableEnvironment environment; + + @Mock + private RpcServerTlsConfig rpcServerTlsConfig; + + @BeforeEach + void setUp() throws Exception { + environment = new MockEnvironment(); + EnvUtil.setEnvironment(environment); + } + + @AfterEach + void tearDown() throws Exception { + } + + @Test + void testGetSslContextIllegal() { + assertThrows(IllegalArgumentException.class, () -> { + DefaultTlsContextBuilder.getSslContext(rpcServerTlsConfig); + }); + } + + @Test + void testGetSslContextWithoutMutual() { + when(rpcServerTlsConfig.getCiphers()).thenReturn("ECDHE-RSA-AES128-GCM-SHA256,ECDHE-RSA-AES256-GCM-SHA384"); + when(rpcServerTlsConfig.getProtocols()).thenReturn("TLSv1.2,TLSv1.3"); + when(rpcServerTlsConfig.getCertPrivateKey()).thenReturn("test-server-key.pem"); + when(rpcServerTlsConfig.getCertChainFile()).thenReturn("test-server-cert.pem"); + DefaultTlsContextBuilder.getSslContext(rpcServerTlsConfig); + } + + @Test + void testGetSslContextWithMutual() { + when(rpcServerTlsConfig.getTrustAll()).thenReturn(true); + when(rpcServerTlsConfig.getMutualAuthEnable()).thenReturn(true); + when(rpcServerTlsConfig.getCiphers()).thenReturn("ECDHE-RSA-AES128-GCM-SHA256,ECDHE-RSA-AES256-GCM-SHA384"); + when(rpcServerTlsConfig.getProtocols()).thenReturn("TLSv1.2,TLSv1.3"); + when(rpcServerTlsConfig.getCertPrivateKey()).thenReturn("test-server-key.pem"); + when(rpcServerTlsConfig.getCertChainFile()).thenReturn("test-server-cert.pem"); + DefaultTlsContextBuilder.getSslContext(rpcServerTlsConfig); + } + + @Test + void testGetSslContextWithMutualAndPart() { + when(rpcServerTlsConfig.getMutualAuthEnable()).thenReturn(true); + when(rpcServerTlsConfig.getCiphers()).thenReturn("ECDHE-RSA-AES128-GCM-SHA256,ECDHE-RSA-AES256-GCM-SHA384"); + when(rpcServerTlsConfig.getProtocols()).thenReturn("TLSv1.2,TLSv1.3"); + when(rpcServerTlsConfig.getCertPrivateKey()).thenReturn("test-server-key.pem"); + when(rpcServerTlsConfig.getCertChainFile()).thenReturn("test-server-cert.pem"); + when(rpcServerTlsConfig.getTrustCollectionCertFile()).thenReturn("test-ca-cert.pem"); + DefaultTlsContextBuilder.getSslContext(rpcServerTlsConfig); + } + + @Test + void testGetSslContextWithMutualAndPartIllegal() { + assertThrows(IllegalArgumentException.class, () -> { + when(rpcServerTlsConfig.getMutualAuthEnable()).thenReturn(true); + when(rpcServerTlsConfig.getCiphers()).thenReturn("ECDHE-RSA-AES128-GCM-SHA256,ECDHE-RSA-AES256-GCM-SHA384"); + when(rpcServerTlsConfig.getProtocols()).thenReturn("TLSv1.2,TLSv1.3"); + when(rpcServerTlsConfig.getCertPrivateKey()).thenReturn("test-server-key.pem"); + when(rpcServerTlsConfig.getCertChainFile()).thenReturn("test-server-cert.pem"); + DefaultTlsContextBuilder.getSslContext(rpcServerTlsConfig); + }); + } + + @Test + void testGetSslContextForNonExistFile() { + assertThrows(NacosRuntimeException.class, () -> { + when(rpcServerTlsConfig.getCertPrivateKey()).thenReturn("non-exist-server-key.pem"); + when(rpcServerTlsConfig.getCertChainFile()).thenReturn("non-exist-cert.pem"); + DefaultTlsContextBuilder.getSslContext(rpcServerTlsConfig); + }); + } + +} diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/SdkDefaultTlsProtocolNegotiatorBuilderTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/SdkDefaultTlsProtocolNegotiatorBuilderTest.java new file mode 100644 index 00000000000..f2f0e5ff662 --- /dev/null +++ b/core/src/test/java/com/alibaba/nacos/core/remote/grpc/negotiator/tls/SdkDefaultTlsProtocolNegotiatorBuilderTest.java @@ -0,0 +1,77 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.remote.grpc.negotiator.tls; + +import com.alibaba.nacos.sys.env.EnvUtil; +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.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.mock.env.MockEnvironment; + +import java.util.Properties; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class SdkDefaultTlsProtocolNegotiatorBuilderTest { + + private ConfigurableEnvironment environment; + + private SdkDefaultTlsProtocolNegotiatorBuilder builder; + + @Mock + private Properties properties; + + @BeforeEach + void setUp() throws Exception { + environment = new MockEnvironment(); + EnvUtil.setEnvironment(environment); + builder = new SdkDefaultTlsProtocolNegotiatorBuilder(); + } + + @AfterEach + void tearDown() throws Exception { + } + + @Test + void testBuildDisabled() { + assertNull(builder.build()); + } + + @Test + void testBuildEnabled() { + try (final MockedStatic envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class)) { + when(EnvUtil.getProperties()).thenReturn(properties); + when(properties.getProperty("nacos.remote.server.rpc.tls.enableTls")).thenReturn("true"); + when(properties.getProperty("nacos.remote.server.rpc.tls.certPrivateKey")).thenReturn("test-server-key.pem"); + when(properties.getProperty("nacos.remote.server.rpc.tls.certChainFile")).thenReturn("test-server-cert.pem"); + assertNotNull(builder.build()); + } + } +} diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/tls/RpcClusterServerSslContextRefresherTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/tls/RpcClusterServerSslContextRefresherTest.java new file mode 100644 index 00000000000..d2149787524 --- /dev/null +++ b/core/src/test/java/com/alibaba/nacos/core/remote/tls/RpcClusterServerSslContextRefresherTest.java @@ -0,0 +1,56 @@ +/* + * Copyright 1999-2021 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package com.alibaba.nacos.core.remote.tls; + +import com.alibaba.nacos.core.remote.BaseRpcServer; + +/** + * {@link RpcServerSslContextRefresher} uint test. + * + * @author stone-98 + * @date 2024-06-21 21:43 + */ +public class RpcClusterServerSslContextRefresherTest implements RpcServerSslContextRefresher { + + public static final String NAME = "cluster-refresher-test"; + + @Override + public SslContextChangeAware refresh(BaseRpcServer baseRpcServer) { + return new SslContextChangeAware() { + @Override + public void init(BaseRpcServer baseRpcServer) { + + } + + @Override + public void onSslContextChange() { + + } + + @Override + public void shutdown() { + + } + }; + } + + @Override + public String getName() { + return NAME; + } +} diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/tls/RpcSdkServerSslContextRefresherTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/tls/RpcSdkServerSslContextRefresherTest.java new file mode 100644 index 00000000000..20018a726ca --- /dev/null +++ b/core/src/test/java/com/alibaba/nacos/core/remote/tls/RpcSdkServerSslContextRefresherTest.java @@ -0,0 +1,56 @@ +/* + * Copyright 1999-2021 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package com.alibaba.nacos.core.remote.tls; + +import com.alibaba.nacos.core.remote.BaseRpcServer; + +/** + * {@link RpcServerSslContextRefresher} uint test. + * + * @author stone-98 + * @date 2024-06-21 21:43 + */ +public class RpcSdkServerSslContextRefresherTest implements RpcServerSslContextRefresher { + + public static final String NAME = "sdk-refresher-test"; + + @Override + public SslContextChangeAware refresh(BaseRpcServer baseRpcServer) { + return new SslContextChangeAware() { + @Override + public void init(BaseRpcServer baseRpcServer) { + + } + + @Override + public void onSslContextChange() { + + } + + @Override + public void shutdown() { + + } + }; + } + + @Override + public String getName() { + return NAME; + } +} diff --git a/core/src/test/java/com/alibaba/nacos/core/remote/tls/RpcServerSslContextRefresherHolderTest.java b/core/src/test/java/com/alibaba/nacos/core/remote/tls/RpcServerSslContextRefresherHolderTest.java new file mode 100644 index 00000000000..74e4cae7b3c --- /dev/null +++ b/core/src/test/java/com/alibaba/nacos/core/remote/tls/RpcServerSslContextRefresherHolderTest.java @@ -0,0 +1,105 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.core.remote.tls; + +import com.alibaba.nacos.sys.env.EnvUtil; +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.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.mock.env.MockEnvironment; + +import java.lang.reflect.Method; +import java.util.Properties; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +/** + * {@link RpcServerSslContextRefresherHolder} unit test. + */ +@ExtendWith(MockitoExtension.class) +public class RpcServerSslContextRefresherHolderTest { + + private MockEnvironment mockEnvironment; + + private MockedStatic rpcServerTlsConfigFactoryMockedStatic; + + @BeforeEach + public void setUp() { + mockEnvironment = new MockEnvironment(); + EnvUtil.setEnvironment(mockEnvironment); + + // Mock RpcServerTlsConfigFactory.getInstance() to return mock instances + rpcServerTlsConfigFactoryMockedStatic = Mockito.mockStatic(RpcServerTlsConfigFactory.class); + + // Mock config + RpcServerTlsConfig sdkServerTlsConfig = Mockito.mock(RpcServerTlsConfig.class); + RpcServerTlsConfig clusterServerTlsConfig = Mockito.mock(RpcServerTlsConfig.class); + + // Mock the static method RpcServerTlsConfigFactory.getInstance() + rpcServerTlsConfigFactoryMockedStatic.when(RpcServerTlsConfigFactory::getInstance) + .thenReturn(Mockito.mock(RpcServerTlsConfigFactory.class)); + + // Mock createSdkConfig method to return the mock sdkServerTlsConfig + when(RpcServerTlsConfigFactory.getInstance().createSdkConfig(any(Properties.class))).thenReturn( + sdkServerTlsConfig); + + // Mock createClusterConfig method to return the mock clusterServerTlsConfig + when(RpcServerTlsConfigFactory.getInstance().createClusterConfig(any(Properties.class))).thenReturn( + clusterServerTlsConfig); + + // Mock getSslContextRefresher to return specific names + when(sdkServerTlsConfig.getSslContextRefresher()).thenReturn(RpcSdkServerSslContextRefresherTest.NAME); + when(clusterServerTlsConfig.getSslContextRefresher()).thenReturn(RpcClusterServerSslContextRefresherTest.NAME); + } + + /** + * afterEach. + */ + @AfterEach + public void tearDown() { + // Clear the mocked static instance + if (rpcServerTlsConfigFactoryMockedStatic != null) { + rpcServerTlsConfigFactoryMockedStatic.close(); + } + // Reset the environment + EnvUtil.setEnvironment(null); + } + + @Test + public void testInitAndGet() throws Exception { + // Call init method. + callInit(); + RpcServerSslContextRefresher sdkInstance = RpcServerSslContextRefresherHolder.getSdkInstance(); + RpcServerSslContextRefresher clusterInstance = RpcServerSslContextRefresherHolder.getClusterInstance(); + + assertEquals(RpcSdkServerSslContextRefresherTest.NAME, sdkInstance.getName()); + assertEquals(RpcClusterServerSslContextRefresherTest.NAME, clusterInstance.getName()); + } + + private void callInit() throws Exception { + Class clazz = RpcServerSslContextRefresherHolder.class; + Method method = clazz.getDeclaredMethod("init"); + method.setAccessible(true); + method.invoke(null); + } +} diff --git a/core/src/test/java/com/alibaba/nacos/core/service/NacosClusterOperationServiceTest.java b/core/src/test/java/com/alibaba/nacos/core/service/NacosClusterOperationServiceTest.java index 5e46a42f745..e84ae4e1a6e 100644 --- a/core/src/test/java/com/alibaba/nacos/core/service/NacosClusterOperationServiceTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/service/NacosClusterOperationServiceTest.java @@ -22,19 +22,19 @@ import com.alibaba.nacos.core.cluster.ServerMemberManager; import com.alibaba.nacos.core.model.request.LookupUpdateRequest; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.env.MockEnvironment; import java.util.Arrays; import java.util.Collection; import java.util.List; -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; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -42,29 +42,30 @@ /** * NacosClusterOperationTest. + * * @author dongyafei * @date 2022/8/15 */ -@RunWith(MockitoJUnitRunner.class) -public class NacosClusterOperationServiceTest { +@ExtendWith(MockitoExtension.class) +class NacosClusterOperationServiceTest { + + @Mock + private final MockEnvironment environment = new MockEnvironment(); private NacosClusterOperationService nacosClusterOperationService; @Mock private ServerMemberManager serverMemberManager; - @Mock - private final MockEnvironment environment = new MockEnvironment(); - - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { this.nacosClusterOperationService = new NacosClusterOperationService(serverMemberManager); EnvUtil.setEnvironment(environment); } @Test - public void testSelf() { + void testSelf() { Member member = new Member(); member.setIp("1.1.1.1"); member.setPort(8848); @@ -77,7 +78,7 @@ public void testSelf() { } @Test - public void testListNodes() throws NacosException { + void testListNodes() throws NacosException { Member member1 = new Member(); member1.setIp("1.1.1.1"); member1.setPort(8848); @@ -99,7 +100,7 @@ public void testListNodes() throws NacosException { } @Test - public void testSelfHealth() { + void testSelfHealth() { Member member = new Member(); member.setIp("1.1.1.1"); member.setPort(8848); @@ -112,7 +113,7 @@ public void testSelfHealth() { } @Test - public void testUpdateNodes() { + void testUpdateNodes() { Member member1 = new Member(); member1.setIp("1.1.1.1"); member1.setAddress("test"); @@ -126,15 +127,15 @@ public void testUpdateNodes() { when(serverMemberManager.update(any())).thenReturn(true); Boolean result = nacosClusterOperationService.updateNodes(members); verify(serverMemberManager, times(1)).update(any()); - assertEquals(true, result); + assertTrue(result); } @Test - public void testUpdateLookup() throws NacosException { + void testUpdateLookup() throws NacosException { LookupUpdateRequest lookupUpdateRequest = new LookupUpdateRequest(); lookupUpdateRequest.setType("test"); Boolean result = nacosClusterOperationService.updateLookup(lookupUpdateRequest); verify(serverMemberManager).switchLookup("test"); - assertEquals(true, result); + assertTrue(result); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/service/NamespaceOperationServiceTest.java b/core/src/test/java/com/alibaba/nacos/core/service/NamespaceOperationServiceTest.java index eba895eef19..6cb70e825bb 100644 --- a/core/src/test/java/com/alibaba/nacos/core/service/NamespaceOperationServiceTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/service/NamespaceOperationServiceTest.java @@ -23,17 +23,18 @@ import com.alibaba.nacos.core.namespace.model.NamespaceTypeEnum; import com.alibaba.nacos.core.namespace.model.TenantInfo; import com.alibaba.nacos.core.namespace.repository.NamespacePersistService; -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.util.Collections; import java.util.List; -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.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; @@ -47,15 +48,8 @@ * @author dongyafei * @date 2022/8/16 */ -@RunWith(MockitoJUnitRunner.class) -public class NamespaceOperationServiceTest { - - private NamespaceOperationService namespaceOperationService; - - private MockNamespaceInjector injector; - - @Mock - private NamespacePersistService namespacePersistService; +@ExtendWith(MockitoExtension.class) +class NamespaceOperationServiceTest { private static final String TEST_NAMESPACE_ID = "testId"; @@ -69,19 +63,26 @@ public class NamespaceOperationServiceTest { private static final String DEFAULT_KP = "1"; - @Before - public void setUp() throws Exception { + private NamespaceOperationService namespaceOperationService; + + private MockNamespaceInjector injector; + + @Mock + private NamespacePersistService namespacePersistService; + + @BeforeEach + void setUp() throws Exception { injector = new MockNamespaceInjector(); namespaceOperationService = new NamespaceOperationService(namespacePersistService); } - @After - public void tearDown() { + @AfterEach + void tearDown() { injector.doInjector = false; } @Test - public void testGetNamespaceList() { + void testGetNamespaceList() { TenantInfo tenantInfo = new TenantInfo(); tenantInfo.setTenantId(TEST_NAMESPACE_ID); tenantInfo.setTenantName(TEST_NAMESPACE_NAME); @@ -102,46 +103,47 @@ public void testGetNamespaceList() { assertEquals(1, namespaceB.getConfigCount()); } - @Test(expected = NacosApiException.class) - public void testGetNamespace() throws NacosException { - - TenantInfo tenantInfo = new TenantInfo(); - tenantInfo.setTenantId(TEST_NAMESPACE_ID); - tenantInfo.setTenantName(TEST_NAMESPACE_NAME); - tenantInfo.setTenantDesc(TEST_NAMESPACE_DESC); - when(namespacePersistService.findTenantByKp(DEFAULT_KP, TEST_NAMESPACE_ID)).thenReturn(tenantInfo); - when(namespacePersistService.findTenantByKp(DEFAULT_KP, "test_not_exist_id")).thenReturn(null); - Namespace namespaceAllInfo = new Namespace(TEST_NAMESPACE_ID, TEST_NAMESPACE_NAME, TEST_NAMESPACE_DESC, - DEFAULT_QUOTA, 1, NamespaceTypeEnum.GLOBAL.getType()); - Namespace namespace = namespaceOperationService.getNamespace(TEST_NAMESPACE_ID); - assertEquals(namespaceAllInfo.getNamespace(), namespace.getNamespace()); - assertEquals(namespaceAllInfo.getNamespaceShowName(), namespace.getNamespaceShowName()); - assertEquals(namespaceAllInfo.getNamespaceDesc(), namespace.getNamespaceDesc()); - assertEquals(namespaceAllInfo.getQuota(), namespace.getQuota()); - assertEquals(namespaceAllInfo.getConfigCount(), namespace.getConfigCount()); - - namespaceOperationService.getNamespace("test_not_exist_id"); + @Test + void testGetNamespace() throws NacosException { + assertThrows(NacosApiException.class, () -> { + + TenantInfo tenantInfo = new TenantInfo(); + tenantInfo.setTenantId(TEST_NAMESPACE_ID); + tenantInfo.setTenantName(TEST_NAMESPACE_NAME); + tenantInfo.setTenantDesc(TEST_NAMESPACE_DESC); + when(namespacePersistService.findTenantByKp(DEFAULT_KP, TEST_NAMESPACE_ID)).thenReturn(tenantInfo); + when(namespacePersistService.findTenantByKp(DEFAULT_KP, "test_not_exist_id")).thenReturn(null); + Namespace namespaceAllInfo = new Namespace(TEST_NAMESPACE_ID, TEST_NAMESPACE_NAME, TEST_NAMESPACE_DESC, DEFAULT_QUOTA, 1, + NamespaceTypeEnum.GLOBAL.getType()); + Namespace namespace = namespaceOperationService.getNamespace(TEST_NAMESPACE_ID); + assertEquals(namespaceAllInfo.getNamespace(), namespace.getNamespace()); + assertEquals(namespaceAllInfo.getNamespaceShowName(), namespace.getNamespaceShowName()); + assertEquals(namespaceAllInfo.getNamespaceDesc(), namespace.getNamespaceDesc()); + assertEquals(namespaceAllInfo.getQuota(), namespace.getQuota()); + assertEquals(namespaceAllInfo.getConfigCount(), namespace.getConfigCount()); + + namespaceOperationService.getNamespace("test_not_exist_id"); + + }); } @Test - public void testCreateNamespace() throws NacosException { + void testCreateNamespace() throws NacosException { when(namespacePersistService.tenantInfoCountByTenantId(anyString())).thenReturn(0); namespaceOperationService.createNamespace(TEST_NAMESPACE_ID, TEST_NAMESPACE_NAME, TEST_NAMESPACE_DESC); - verify(namespacePersistService) - .insertTenantInfoAtomic(eq(DEFAULT_KP), eq(TEST_NAMESPACE_ID), eq(TEST_NAMESPACE_NAME), - eq(TEST_NAMESPACE_DESC), any(), anyLong()); + verify(namespacePersistService).insertTenantInfoAtomic(eq(DEFAULT_KP), eq(TEST_NAMESPACE_ID), eq(TEST_NAMESPACE_NAME), + eq(TEST_NAMESPACE_DESC), any(), anyLong()); } @Test - public void testEditNamespace() { + void testEditNamespace() { namespaceOperationService.editNamespace(TEST_NAMESPACE_ID, TEST_NAMESPACE_NAME, TEST_NAMESPACE_DESC); - verify(namespacePersistService) - .updateTenantNameAtomic(DEFAULT_KP, TEST_NAMESPACE_ID, TEST_NAMESPACE_NAME, TEST_NAMESPACE_DESC); + verify(namespacePersistService).updateTenantNameAtomic(DEFAULT_KP, TEST_NAMESPACE_ID, TEST_NAMESPACE_NAME, TEST_NAMESPACE_DESC); } @Test - public void testRemoveNamespace() { + void testRemoveNamespace() { namespaceOperationService.removeNamespace(TEST_NAMESPACE_ID); verify(namespacePersistService).removeTenantInfoAtomic(DEFAULT_KP, TEST_NAMESPACE_ID); } diff --git a/core/src/test/java/com/alibaba/nacos/core/storage/FileKvStorageTest.java b/core/src/test/java/com/alibaba/nacos/core/storage/FileKvStorageTest.java deleted file mode 100644 index 956c7ffdc01..00000000000 --- a/core/src/test/java/com/alibaba/nacos/core/storage/FileKvStorageTest.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright 1999-2021 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.core.storage; - -import com.alibaba.nacos.core.exception.KvStorageException; -import com.alibaba.nacos.core.storage.kv.FileKvStorage; -import com.alibaba.nacos.core.storage.kv.KvStorage; -import org.apache.commons.io.FileUtils; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -/** - * {@link FileKvStorage} unit tests. - * - * @author chenglu - * @date 2021-06-10 18:27 - */ -public class FileKvStorageTest { - - private KvStorage kvStorage; - - private String baseDir; - - @Before - public void init() { - try { - baseDir = System.getProperty("user.home"); - String dir = baseDir + File.separator + "nacos_file_kv_storage_test_brotherluxcq"; - kvStorage = StorageFactory.createKvStorage(KvStorage.KvType.File, null, dir); - } catch (Exception e) { - e.printStackTrace(); - Assert.fail(); - } - } - - @AfterClass - public static void clean() { - String dir = System.getProperty("user.home") + File.separator + "nacos_file_kv_storage_test_brotherluxcq"; - String backupDir = System.getProperty("user.home") + File.separator + "nacos_file_kv_storage_test_backup_brotherluxcq"; - - try { - FileUtils.deleteDirectory(new File(dir)); - FileUtils.deleteDirectory(new File(backupDir)); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Test - public void testPutAndGetAndDelete() { - try { - byte[] key = "key".getBytes(); - byte[] value = "value".getBytes(); - kvStorage.put(key, value); - byte[] value1 = kvStorage.get(key); - Assert.assertArrayEquals(value, value1); - - Assert.assertNotNull(kvStorage.allKeys()); - - kvStorage.delete(key); - Assert.assertNull(kvStorage.get(key)); - - kvStorage.put(key, value); - kvStorage.shutdown(); - Assert.assertEquals(kvStorage.allKeys().size(), kvStorage.allKeys().size()); - } catch (Exception e) { - e.printStackTrace(); - Assert.fail(); - } - } - - @Test - public void testBatchPutAndGet() { - try { - List keys = Arrays.asList("key1".getBytes(), "key2".getBytes()); - List values = Arrays.asList("value1".getBytes(), "value2".getBytes()); - kvStorage.batchPut(keys, values); - - Map res = kvStorage.batchGet(keys); - Assert.assertNotNull(res); - - res.forEach((key, value) -> { - if (Arrays.equals(key, "key1".getBytes())) { - Assert.assertArrayEquals("value1".getBytes(), value); - } else if (Arrays.equals(key, "key2".getBytes())) { - Assert.assertArrayEquals("value2".getBytes(), value); - } else { - Assert.fail(); - } - }); - - kvStorage.batchDelete(keys); - Assert.assertEquals(0, kvStorage.batchGet(values).size()); - } catch (Exception e) { - e.printStackTrace(); - Assert.fail(); - } - } - - @Test - public void testSnapshot() { - String backupDir = baseDir + File.separator + "nacos_file_kv_storage_test_backup_brotherluxcq"; - try { - File file = new File(backupDir); - if (!file.exists()) { - boolean dirResult = file.mkdirs(); - if (!dirResult) { - return; - } - } - kvStorage.doSnapshot(backupDir); - } catch (KvStorageException e) { - e.printStackTrace(); - Assert.fail(); - } - - try { - kvStorage.snapshotLoad(backupDir); - byte[] key = "key".getBytes(); - byte[] value = kvStorage.get(key); - Assert.assertArrayEquals("value".getBytes(), value); - } catch (KvStorageException e) { - e.printStackTrace(); - Assert.fail(); - } - } -} diff --git a/core/src/test/java/com/alibaba/nacos/core/storage/MemoryKvStorageTest.java b/core/src/test/java/com/alibaba/nacos/core/storage/MemoryKvStorageTest.java deleted file mode 100644 index fd32a70f551..00000000000 --- a/core/src/test/java/com/alibaba/nacos/core/storage/MemoryKvStorageTest.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright 1999-2021 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.core.storage; - -import com.alibaba.nacos.core.storage.kv.KvStorage; -import com.alibaba.nacos.core.storage.kv.MemoryKvStorage; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -/** - * {@link MemoryKvStorage} unit tests. - * - * @author chenglu - * @date 2021-06-10 18:02 - */ -public class MemoryKvStorageTest { - private KvStorage kvStorage; - - @Before - public void init() { - try { - kvStorage = StorageFactory.createKvStorage(KvStorage.KvType.Memory, null, null); - } catch (Exception e) { - e.printStackTrace(); - Assert.fail(); - } - } - - @Test - public void testPutAndGetAndDelete() { - try { - byte[] key = "key".getBytes(); - byte[] value = "value".getBytes(); - kvStorage.put(key, value); - byte[] value1 = kvStorage.get(key); - Assert.assertArrayEquals(value, value1); - - Assert.assertNotNull(kvStorage.allKeys()); - - kvStorage.delete(key); - Assert.assertNull(kvStorage.get(key)); - - kvStorage.put(key, value); - kvStorage.shutdown(); - Assert.assertEquals(0, kvStorage.allKeys().size()); - } catch (Exception e) { - e.printStackTrace(); - Assert.fail(); - } - } - - @Test - public void testBatchPutAndGet() { - try { - List keys = Arrays.asList("key1".getBytes(), "key2".getBytes()); - List values = Arrays.asList("value1".getBytes(), "value2".getBytes()); - kvStorage.batchPut(keys, values); - - Map res = kvStorage.batchGet(keys); - Assert.assertNotNull(res); - - res.forEach((key, value) -> { - if (Arrays.equals(key, "key1".getBytes())) { - Assert.assertArrayEquals("value1".getBytes(), value); - } else if (Arrays.equals(key, "key2".getBytes())) { - Assert.assertArrayEquals("value2".getBytes(), value); - } else { - Assert.fail(); - } - }); - - kvStorage.batchDelete(keys); - Assert.assertEquals(0, kvStorage.batchGet(values).size()); - } catch (Exception e) { - e.printStackTrace(); - Assert.fail(); - } - } - - @Test - public void testSnapshot() { - try { - kvStorage.doSnapshot("/"); - } catch (Exception e) { - Assert.assertTrue(e instanceof UnsupportedOperationException); - } - - try { - kvStorage.snapshotLoad("/"); - } catch (Exception e) { - Assert.assertTrue(e instanceof UnsupportedOperationException); - } - } -} diff --git a/core/src/test/java/com/alibaba/nacos/core/storage/StorageFactoryTest.java b/core/src/test/java/com/alibaba/nacos/core/storage/StorageFactoryTest.java deleted file mode 100644 index 031d5c7fed4..00000000000 --- a/core/src/test/java/com/alibaba/nacos/core/storage/StorageFactoryTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 1999-2021 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.core.storage; - -import com.alibaba.nacos.core.storage.kv.FileKvStorage; -import com.alibaba.nacos.core.storage.kv.KvStorage; -import com.alibaba.nacos.core.storage.kv.MemoryKvStorage; -import org.junit.Assert; -import org.junit.Test; - -/** - * {@link StorageFactory} unit tests. - * - * @author chenglu - * @date 2021-06-10 17:55 - */ -public class StorageFactoryTest { - - @Test - public void testCreateKvStorage() { - try { - KvStorage kvStorage = StorageFactory.createKvStorage(KvStorage.KvType.Memory, "", "/"); - Assert.assertTrue(kvStorage instanceof MemoryKvStorage); - } catch (Exception e) { - e.printStackTrace(); - Assert.fail(); - } - - try { - KvStorage kvStorage = StorageFactory.createKvStorage(KvStorage.KvType.File, "", "/"); - Assert.assertTrue(kvStorage instanceof FileKvStorage); - } catch (Exception e) { - e.printStackTrace(); - Assert.fail(); - } - - try { - StorageFactory.createKvStorage(KvStorage.KvType.RocksDB, "", "/"); - } catch (Exception e) { - Assert.assertTrue(e instanceof IllegalArgumentException); - } - } -} diff --git a/core/src/test/java/com/alibaba/nacos/core/trace/NacosCombinedTraceSubscriberTest.java b/core/src/test/java/com/alibaba/nacos/core/trace/NacosCombinedTraceSubscriberTest.java index 80ec05fd6cd..073dedc8aa0 100644 --- a/core/src/test/java/com/alibaba/nacos/core/trace/NacosCombinedTraceSubscriberTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/trace/NacosCombinedTraceSubscriberTest.java @@ -32,12 +32,12 @@ import com.alibaba.nacos.common.trace.event.naming.UpdateServiceTraceEvent; import com.alibaba.nacos.plugin.trace.NacosTracePluginManager; import com.alibaba.nacos.plugin.trace.spi.NacosTraceSubscriber; -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 org.springframework.test.util.ReflectionTestUtils; import java.util.LinkedList; @@ -45,8 +45,8 @@ import java.util.Map; import java.util.concurrent.Executor; -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; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; @@ -56,8 +56,8 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class NacosCombinedTraceSubscriberTest { +@ExtendWith(MockitoExtension.class) +class NacosCombinedTraceSubscriberTest { @Mock private NacosTraceSubscriber mockServiceSubscriber; @@ -72,12 +72,11 @@ public class NacosCombinedTraceSubscriberTest { @SuppressWarnings("unchecked") private Map getTraceSubscribers() { - return (Map) ReflectionTestUtils.getField(NacosTracePluginManager.getInstance(), - "traceSubscribers"); + return (Map) ReflectionTestUtils.getField(NacosTracePluginManager.getInstance(), "traceSubscribers"); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { Map traceSubscribers = getTraceSubscribers(); traceSubscribers.put("instanceSubscriber", mockInstanceSubscriber); traceSubscribers.put("serviceSubscriber", mockServiceSubscriber); @@ -105,8 +104,8 @@ public void setUp() throws Exception { combinedTraceSubscriber = new NacosCombinedTraceSubscriber(NamingTraceEvent.class); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { Map traceSubscribers = getTraceSubscribers(); traceSubscribers.remove("serviceSubscriber"); traceSubscribers.remove("instanceSubscriber"); @@ -115,7 +114,7 @@ public void tearDown() throws Exception { } @Test - public void testSubscribeTypes() { + void testSubscribeTypes() { List> actual = combinedTraceSubscriber.subscribeTypes(); assertEquals(10, actual.size()); assertTrue(actual.contains(RegisterInstanceTraceEvent.class)); @@ -131,10 +130,9 @@ public void testSubscribeTypes() { } @Test - public void testOnEvent() { + void testOnEvent() { // Test RegisterInstanceTraceEvent. - RegisterInstanceTraceEvent registerInstanceTraceEvent = new RegisterInstanceTraceEvent(1L, "", true, "", "", "", - "", 1); + RegisterInstanceTraceEvent registerInstanceTraceEvent = new RegisterInstanceTraceEvent(1L, "", true, "", "", "", "", 1); doThrow(new RuntimeException("test")).when(mockInstanceSubscriber).onEvent(registerInstanceTraceEvent); combinedTraceSubscriber.onEvent(registerInstanceTraceEvent); verify(mockInstanceSubscriber, times(1)).onEvent(registerInstanceTraceEvent); @@ -148,8 +146,7 @@ public void testOnEvent() { verify(mockServiceSubscriber, never()).onEvent(deregisterInstanceTraceEvent); verify(mockOtherSubscriber, never()).onEvent(deregisterInstanceTraceEvent); // Test UpdateInstanceTraceEvent. - UpdateInstanceTraceEvent updateInstanceTraceEvent = new UpdateInstanceTraceEvent(1L, "", "", "", "", "", 123, - null); + UpdateInstanceTraceEvent updateInstanceTraceEvent = new UpdateInstanceTraceEvent(1L, "", "", "", "", "", 123, null); combinedTraceSubscriber.onEvent(updateInstanceTraceEvent); verify(mockInstanceSubscriber, times(1)).onEvent(updateInstanceTraceEvent); verify(mockServiceSubscriber, never()).onEvent(updateInstanceTraceEvent); @@ -173,8 +170,7 @@ public void testOnEvent() { verify(mockServiceSubscriber, times(1)).onEvent(subscribeServiceTraceEvent); verify(mockOtherSubscriber, never()).onEvent(subscribeServiceTraceEvent); // Test UnsubscribeServiceTraceEvent. - UnsubscribeServiceTraceEvent unsubscribeServiceTraceEvent = new UnsubscribeServiceTraceEvent(1L, "", "", "", - ""); + UnsubscribeServiceTraceEvent unsubscribeServiceTraceEvent = new UnsubscribeServiceTraceEvent(1L, "", "", "", ""); combinedTraceSubscriber.onEvent(unsubscribeServiceTraceEvent); verify(mockInstanceSubscriber, never()).onEvent(unsubscribeServiceTraceEvent); verify(mockServiceSubscriber, times(1)).onEvent(unsubscribeServiceTraceEvent); @@ -192,8 +188,7 @@ public void testOnEvent() { verify(mockServiceSubscriber, times(1)).onEvent(pushServiceTraceEvent); verify(mockOtherSubscriber, never()).onEvent(pushServiceTraceEvent); // Test HealthStateChangeTraceEvent. - HealthStateChangeTraceEvent healthStateChangeTraceEvent = new HealthStateChangeTraceEvent(1L, "", "", "", "", - 8867, true, ""); + HealthStateChangeTraceEvent healthStateChangeTraceEvent = new HealthStateChangeTraceEvent(1L, "", "", "", "", 8867, true, ""); combinedTraceSubscriber.onEvent(healthStateChangeTraceEvent); verify(mockInstanceSubscriber, never()).onEvent(healthStateChangeTraceEvent); verify(mockServiceSubscriber, never()).onEvent(healthStateChangeTraceEvent); @@ -207,7 +202,7 @@ public void testOnEvent() { } @Test - public void testOnEventWithExecutor() { + void testOnEventWithExecutor() { Executor executor = mock(Executor.class); doAnswer(invocationOnMock -> { invocationOnMock.getArgument(0, Runnable.class).run(); diff --git a/core/src/test/java/com/alibaba/nacos/core/utils/ClassUtilsTest.java b/core/src/test/java/com/alibaba/nacos/core/utils/ClassUtilsTest.java index 77144188ffe..6856cafeed0 100644 --- a/core/src/test/java/com/alibaba/nacos/core/utils/ClassUtilsTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/utils/ClassUtilsTest.java @@ -16,44 +16,45 @@ package com.alibaba.nacos.core.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** - * * {@link ClassUtils} unit tests. */ -public class ClassUtilsTest { +class ClassUtilsTest { @Test - public void testGeneric() { + void testGeneric() { Type type = new GenericType>() { }.getType(); - Assert.assertEquals("java.util.List", type.getTypeName()); - Assert.assertTrue(type instanceof ParameterizedType); + assertEquals("java.util.List", type.getTypeName()); + assertTrue(type instanceof ParameterizedType); } @Test - public void testFindClassByName() { + void testFindClassByName() { Class clazz = ClassUtils.findClassByName("java.lang.Integer"); - Assert.assertEquals("java.lang.Integer", clazz.getName()); + assertEquals("java.lang.Integer", clazz.getName()); } @Test - public void testGetName() { + void testGetName() { final String name = "java.lang.Integer"; Integer val = 1; - Assert.assertEquals(name, ClassUtils.getName(val)); - Assert.assertEquals(name, ClassUtils.getName(Integer.class)); + assertEquals(name, ClassUtils.getName(val)); + assertEquals(name, ClassUtils.getName(Integer.class)); - Assert.assertEquals(name, ClassUtils.getCanonicalName(val)); - Assert.assertEquals(name, ClassUtils.getCanonicalName(Integer.class)); + assertEquals(name, ClassUtils.getCanonicalName(val)); + assertEquals(name, ClassUtils.getCanonicalName(Integer.class)); - Assert.assertEquals("Integer", ClassUtils.getSimplaName(val)); - Assert.assertEquals("Integer", ClassUtils.getSimplaName(Integer.class)); + assertEquals("Integer", ClassUtils.getSimplaName(val)); + assertEquals("Integer", ClassUtils.getSimplaName(Integer.class)); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/utils/OverrideParameterRequestWrapperTest.java b/core/src/test/java/com/alibaba/nacos/core/utils/OverrideParameterRequestWrapperTest.java index 706f38734b5..cd45a89f329 100644 --- a/core/src/test/java/com/alibaba/nacos/core/utils/OverrideParameterRequestWrapperTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/utils/OverrideParameterRequestWrapperTest.java @@ -16,27 +16,28 @@ package com.alibaba.nacos.core.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * {@link OverrideParameterRequestWrapper} unit tests. * * @author chenglu * @date 2021-06-10 14:11 */ -public class OverrideParameterRequestWrapperTest { +class OverrideParameterRequestWrapperTest { @Test - public void testOverrideParameterRequestWrapper() { + void testOverrideParameterRequestWrapper() { MockHttpServletRequest httpServletRequest = new MockHttpServletRequest(); httpServletRequest.addParameter("test1", "value1"); OverrideParameterRequestWrapper wrapper = OverrideParameterRequestWrapper.buildRequest(httpServletRequest); String value1 = wrapper.getParameter("test1"); - Assert.assertEquals("value1", value1); + assertEquals("value1", value1); wrapper.addParameter("test2", "value2"); - Assert.assertEquals("value2", wrapper.getParameter("test2")); + assertEquals("value2", wrapper.getParameter("test2")); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/utils/RemoteUtilsTest.java b/core/src/test/java/com/alibaba/nacos/core/utils/RemoteUtilsTest.java index 59b48ed1d8d..1022fff2369 100644 --- a/core/src/test/java/com/alibaba/nacos/core/utils/RemoteUtilsTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/utils/RemoteUtilsTest.java @@ -16,8 +16,9 @@ package com.alibaba.nacos.core.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * {@link RemoteUtils} unit tests. @@ -25,35 +26,35 @@ * @author chenglu * @date 2021-06-10 13:17 */ -public class RemoteUtilsTest { +class RemoteUtilsTest { @Test - public void testGetRemoteExecutorTimesOfProcessors() { + void testGetRemoteExecutorTimesOfProcessors() { int defaultExpectVal = 1 << 4; int defaultVal = RemoteUtils.getRemoteExecutorTimesOfProcessors(); - Assert.assertEquals(defaultExpectVal, defaultVal); + assertEquals(defaultExpectVal, defaultVal); System.setProperty("remote.executor.times.of.processors", "10"); int val1 = RemoteUtils.getRemoteExecutorTimesOfProcessors(); - Assert.assertEquals(10, val1); + assertEquals(10, val1); System.setProperty("remote.executor.times.of.processors", "-1"); int val2 = RemoteUtils.getRemoteExecutorTimesOfProcessors(); - Assert.assertEquals(defaultExpectVal, val2); + assertEquals(defaultExpectVal, val2); } @Test - public void testGetRemoteExecutorQueueSize() { + void testGetRemoteExecutorQueueSize() { int defaultExpectVal = 1 << 14; int defaultVal = RemoteUtils.getRemoteExecutorQueueSize(); - Assert.assertEquals(defaultExpectVal, defaultVal); + assertEquals(defaultExpectVal, defaultVal); System.setProperty("remote.executor.queue.size", "10"); int val1 = RemoteUtils.getRemoteExecutorQueueSize(); - Assert.assertEquals(10, val1); + assertEquals(10, val1); System.setProperty("remote.executor.queue.size", "-1"); int val2 = RemoteUtils.getRemoteExecutorQueueSize(); - Assert.assertEquals(defaultExpectVal, val2); + assertEquals(defaultExpectVal, val2); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/utils/ReuseHttpServletRequestTest.java b/core/src/test/java/com/alibaba/nacos/core/utils/ReuseHttpServletRequestTest.java index 39e03db1697..8f8df49f7b4 100644 --- a/core/src/test/java/com/alibaba/nacos/core/utils/ReuseHttpServletRequestTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/utils/ReuseHttpServletRequestTest.java @@ -22,36 +22,37 @@ import org.springframework.mock.web.MockHttpServletRequest; import javax.servlet.ServletInputStream; - import java.io.BufferedReader; import java.io.IOException; import java.util.Map; -import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; /** * {@link ReuseHttpServletRequest} unit tests. + * * @author lynn.lqp * @date 2023/12/28 */ -public class ReuseHttpServletRequestTest { +class ReuseHttpServletRequestTest { + private MockHttpServletRequest target; - + private ReuseHttpServletRequest reuseHttpServletRequest; - + @BeforeEach - public void setUp() throws IOException { + void setUp() throws IOException { target = new MockHttpServletRequest(); target.setContentType("application/json"); target.setParameter("name", "test"); target.setParameter("value", "123"); reuseHttpServletRequest = new ReuseHttpServletRequest(target); } - + @Test - public void testConstructor() throws IOException { + void testConstructor() throws IOException { try { new ReuseHttpServletRequest(null); fail("IllegalArgumentException expected"); @@ -61,50 +62,50 @@ public void testConstructor() throws IOException { ReuseHttpServletRequest request = new ReuseHttpServletRequest(target); assertNotNull(request); } - + @Test - public void testGetBody() throws Exception { + void testGetBody() throws Exception { Object body = reuseHttpServletRequest.getBody(); assertNotNull(body); assertEquals("name=test&value=123&", body.toString()); - + target.setContentType(MediaType.MULTIPART_FORM_DATA); body = reuseHttpServletRequest.getBody(); assertNotNull(body); } - + @Test - public void testGetReader() throws IOException { + void testGetReader() throws IOException { BufferedReader reader = reuseHttpServletRequest.getReader(); assertNotNull(reader); } - + @Test - public void testGetParameterMap() { + void testGetParameterMap() { Map parameterMap = reuseHttpServletRequest.getParameterMap(); assertNotNull(parameterMap); assertEquals(2, parameterMap.size()); assertEquals("test", parameterMap.get("name")[0]); assertEquals("123", parameterMap.get("value")[0]); } - + @Test - public void testGetParameter() { + void testGetParameter() { String name = reuseHttpServletRequest.getParameter("name"); assertNotNull(name); assertEquals("test", name); } - + @Test - public void testGetParameterValues() { + void testGetParameterValues() { String[] values = reuseHttpServletRequest.getParameterValues("value"); assertNotNull(values); assertEquals(1, values.length); assertEquals("123", values[0]); } - + @Test - public void testGetInputStream() throws IOException { + void testGetInputStream() throws IOException { ServletInputStream inputStream = reuseHttpServletRequest.getInputStream(); assertNotNull(inputStream); int read = inputStream.read(); diff --git a/core/src/test/java/com/alibaba/nacos/core/utils/ReuseUploadFileHttpServletRequestTest.java b/core/src/test/java/com/alibaba/nacos/core/utils/ReuseUploadFileHttpServletRequestTest.java index a2b9bcc9a82..dbfb931462f 100644 --- a/core/src/test/java/com/alibaba/nacos/core/utils/ReuseUploadFileHttpServletRequestTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/utils/ReuseUploadFileHttpServletRequestTest.java @@ -22,51 +22,55 @@ import org.mockito.Mockito; import org.springframework.mock.web.MockMultipartHttpServletRequest; import org.springframework.web.multipart.MultipartException; + import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.when; + /** * {@link ReuseUploadFileHttpServletRequest} unit tests. + * * @author lynn.lqp * @date 2023/12/28 */ -public class ReuseUploadFileHttpServletRequestTest { - +class ReuseUploadFileHttpServletRequestTest { + private ReuseUploadFileHttpServletRequest reuseUploadFileHttpServletRequest; - + private MockMultipartHttpServletRequest mockMultipartHttpServletRequest; - + @BeforeEach - public void setUp() throws MultipartException { + void setUp() throws MultipartException { mockMultipartHttpServletRequest = Mockito.mock(MockMultipartHttpServletRequest.class); when(mockMultipartHttpServletRequest.getParameterMap()).thenReturn(new HashMap<>()); reuseUploadFileHttpServletRequest = new ReuseUploadFileHttpServletRequest(mockMultipartHttpServletRequest); } - + @Test - public void testGetParameterMapEmpty() { + void testGetParameterMapEmpty() { Map parameterMap = reuseUploadFileHttpServletRequest.getParameterMap(); assertEquals(0, parameterMap.size()); } - + @Test - public void testGetParameterEmpty() { + void testGetParameterEmpty() { assertNull(reuseUploadFileHttpServletRequest.getParameter("nonExistentParam")); } - + @Test - public void testGetParameterValuesEmpty() { + void testGetParameterValuesEmpty() { assertNull(reuseUploadFileHttpServletRequest.getParameterValues("nonExistentParam")); } - + @Test - public void testGetBodyWithoutFile() throws Exception { + void testGetBodyWithoutFile() throws Exception { Object body = reuseUploadFileHttpServletRequest.getBody(); assertEquals(HttpUtils.encodingParams(HttpUtils.translateParameterMap(new HashMap<>()), StandardCharsets.UTF_8.name()), body); } - + } diff --git a/core/src/test/java/com/alibaba/nacos/core/utils/StringPoolTest.java b/core/src/test/java/com/alibaba/nacos/core/utils/StringPoolTest.java index 315c6228130..f268119fad8 100644 --- a/core/src/test/java/com/alibaba/nacos/core/utils/StringPoolTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/utils/StringPoolTest.java @@ -16,8 +16,10 @@ package com.alibaba.nacos.core.utils; -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.assertNull; /** * {@link StringPool} unit tests. @@ -25,21 +27,21 @@ * @author chenglu * @date 2021-06-10 13:52 */ -public class StringPoolTest { +class StringPoolTest { @Test - public void testStringPool() { + void testStringPool() { String val1 = StringPool.get("test"); - Assert.assertEquals("test", val1); + assertEquals("test", val1); String val2 = StringPool.get(null); - Assert.assertEquals(null, val2); + assertNull(val2); long size1 = StringPool.size(); - Assert.assertEquals(1, size1); + assertEquals(1, size1); StringPool.remove("test"); long size2 = StringPool.size(); - Assert.assertEquals(0, size2); + assertEquals(0, size2); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/utils/SystemUtilsTest.java b/core/src/test/java/com/alibaba/nacos/core/utils/SystemUtilsTest.java index 96aeb5519b0..c2ccf9a5d92 100644 --- a/core/src/test/java/com/alibaba/nacos/core/utils/SystemUtilsTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/utils/SystemUtilsTest.java @@ -19,9 +19,8 @@ import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.utils.ApplicationUtils; import org.apache.commons.io.FileUtils; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; @@ -30,6 +29,9 @@ import static com.alibaba.nacos.sys.env.Constants.PREFER_HOSTNAME_OVER_IP_PROPERTY_NAME; import static com.alibaba.nacos.sys.env.Constants.STANDALONE_MODE_PROPERTY_NAME; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link ApplicationUtils} Test. @@ -37,7 +39,7 @@ * @author Mercy * @since 0.2.2 */ -public class SystemUtilsTest { +class SystemUtilsTest { private static final Random RANDOM = new Random(); @@ -45,44 +47,44 @@ public class SystemUtilsTest { private static boolean preferHostMode = RANDOM.nextBoolean(); - @BeforeClass - public static void init() { + @BeforeAll + static void init() { System.setProperty("nacos.standalone", String.valueOf(standaloneMode)); System.setProperty("nacos.preferHostnameOverIp", String.valueOf(preferHostMode)); } @Test - public void testStandaloneModeConstants() { + void testStandaloneModeConstants() { System.out.printf("System property \"%s\" = %s \n", "nacos.standalone", standaloneMode); if ("true".equalsIgnoreCase(System.getProperty("nacos.standalone"))) { - Assert.assertTrue(Boolean.getBoolean(STANDALONE_MODE_PROPERTY_NAME)); + assertTrue(Boolean.getBoolean(STANDALONE_MODE_PROPERTY_NAME)); } else { - Assert.assertFalse(Boolean.getBoolean(STANDALONE_MODE_PROPERTY_NAME)); + assertFalse(Boolean.getBoolean(STANDALONE_MODE_PROPERTY_NAME)); } - Assert.assertEquals(standaloneMode, Boolean.getBoolean(STANDALONE_MODE_PROPERTY_NAME)); + assertEquals(standaloneMode, Boolean.getBoolean(STANDALONE_MODE_PROPERTY_NAME)); } @Test - public void testPreferHostModeConstants() { + void testPreferHostModeConstants() { System.out.printf("System property \"%s\" = %s \n", "nacos.preferrHostnameOverIp", preferHostMode); if ("true".equalsIgnoreCase(System.getProperty("nacos.preferHostnameOverIp"))) { - Assert.assertTrue(Boolean.getBoolean(PREFER_HOSTNAME_OVER_IP_PROPERTY_NAME)); + assertTrue(Boolean.getBoolean(PREFER_HOSTNAME_OVER_IP_PROPERTY_NAME)); } else { - Assert.assertFalse(Boolean.getBoolean(PREFER_HOSTNAME_OVER_IP_PROPERTY_NAME)); + assertFalse(Boolean.getBoolean(PREFER_HOSTNAME_OVER_IP_PROPERTY_NAME)); } - Assert.assertEquals(preferHostMode, Boolean.getBoolean(PREFER_HOSTNAME_OVER_IP_PROPERTY_NAME)); + assertEquals(preferHostMode, Boolean.getBoolean(PREFER_HOSTNAME_OVER_IP_PROPERTY_NAME)); } @Test - public void testReadClusterConf() throws IOException { + void testReadClusterConf() throws IOException { FileUtils.forceMkdir(new File(EnvUtil.getConfPath())); String lineSeparator = System.getProperty("line.separator"); @@ -93,7 +95,7 @@ public void testReadClusterConf() throws IOException { * 192.168.1.1:8848 */ EnvUtil.writeClusterConf("#it is ip" + lineSeparator + "#example" + lineSeparator + "192.168.1.1:8848"); - Assert.assertEquals(EnvUtil.readClusterConf().get(0), "192.168.1.1:8848"); + assertEquals("192.168.1.1:8848", EnvUtil.readClusterConf().get(0)); /* * #it is ip @@ -101,12 +103,11 @@ public void testReadClusterConf() throws IOException { * # 192.168.1.1:8848 * 192.168.1.2:8848 # Instance A */ - EnvUtil.writeClusterConf( - "#it is ip" + lineSeparator + " #example" + lineSeparator + " # 192.168.1.1:8848" + lineSeparator - + " 192.168.1.2:8848 # Instance A " + lineSeparator + "192.168.1.3#:8848"); + EnvUtil.writeClusterConf("#it is ip" + lineSeparator + " #example" + lineSeparator + " # 192.168.1.1:8848" + lineSeparator + + " 192.168.1.2:8848 # Instance A " + lineSeparator + "192.168.1.3#:8848"); List instanceList = EnvUtil.readClusterConf(); - Assert.assertEquals(instanceList.get(0), "192.168.1.2:8848"); - Assert.assertEquals(instanceList.get(1), "192.168.1.3"); + assertEquals("192.168.1.2:8848", instanceList.get(0)); + assertEquals("192.168.1.3", instanceList.get(1)); } } diff --git a/core/src/test/java/com/alibaba/nacos/core/utils/WebUtilsTest.java b/core/src/test/java/com/alibaba/nacos/core/utils/WebUtilsTest.java index a6802afabd7..9bcedf09df5 100644 --- a/core/src/test/java/com/alibaba/nacos/core/utils/WebUtilsTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/utils/WebUtilsTest.java @@ -17,65 +17,97 @@ package com.alibaba.nacos.core.utils; import com.alibaba.nacos.common.constant.HttpHeaderConsts; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; import org.springframework.mock.web.MockHttpServletRequest; +import javax.servlet.http.HttpServletRequest; import java.nio.charset.StandardCharsets; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.eq; + /** * {@link WebUtils} unit tests. * * @author chenglu * @date 2021-06-10 13:33 */ -public class WebUtilsTest { +class WebUtilsTest { + + private static final String X_REAL_IP = "X-Real-IP"; + + private static final String X_FORWARDED_FOR = "X-Forwarded-For"; @Test - public void testRequired() { + void testRequired() { final String key = "key"; MockHttpServletRequest servletRequest = new MockHttpServletRequest(); try { WebUtils.required(servletRequest, key); } catch (Exception e) { - Assert.assertTrue(e instanceof IllegalArgumentException); + assertTrue(e instanceof IllegalArgumentException); } servletRequest.addParameter(key, "value"); String val = WebUtils.required(servletRequest, key); - Assert.assertEquals("value", val); + assertEquals("value", val); } @Test - public void testOptional() { + void testOptional() { final String key = "key"; MockHttpServletRequest servletRequest = new MockHttpServletRequest(); String val1 = WebUtils.optional(servletRequest, key, "value"); - Assert.assertEquals("value", val1); + assertEquals("value", val1); servletRequest.addParameter(key, "value1"); - Assert.assertEquals("value1", WebUtils.optional(servletRequest, key, "value")); + assertEquals("value1", WebUtils.optional(servletRequest, key, "value")); } @Test - public void testGetUserAgent() { + void testGetUserAgent() { MockHttpServletRequest servletRequest = new MockHttpServletRequest(); String userAgent = WebUtils.getUserAgent(servletRequest); - Assert.assertEquals("", userAgent); + assertEquals("", userAgent); servletRequest.addHeader(HttpHeaderConsts.CLIENT_VERSION_HEADER, "0"); - Assert.assertEquals("0", WebUtils.getUserAgent(servletRequest)); + assertEquals("0", WebUtils.getUserAgent(servletRequest)); servletRequest.addHeader(HttpHeaderConsts.USER_AGENT_HEADER, "1"); - Assert.assertEquals("1", WebUtils.getUserAgent(servletRequest)); + assertEquals("1", WebUtils.getUserAgent(servletRequest)); } @Test - public void testGetAcceptEncoding() { + void testGetAcceptEncoding() { MockHttpServletRequest servletRequest = new MockHttpServletRequest(); - Assert.assertEquals(StandardCharsets.UTF_8.name(), WebUtils.getAcceptEncoding(servletRequest)); + assertEquals(StandardCharsets.UTF_8.name(), WebUtils.getAcceptEncoding(servletRequest)); servletRequest.addHeader(HttpHeaderConsts.ACCEPT_ENCODING, "gzip, deflate, br"); - Assert.assertEquals("gzip", WebUtils.getAcceptEncoding(servletRequest)); + assertEquals("gzip", WebUtils.getAcceptEncoding(servletRequest)); + } + + @Test + void testGetRemoteIp() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + Mockito.when(request.getRemoteAddr()).thenReturn("127.0.0.1"); + assertEquals("127.0.0.1", WebUtils.getRemoteIp(request)); + + Mockito.when(request.getHeader(eq(X_REAL_IP))).thenReturn("127.0.0.2"); + assertEquals("127.0.0.2", WebUtils.getRemoteIp(request)); + + Mockito.when(request.getHeader(eq(X_FORWARDED_FOR))).thenReturn("127.0.0.3"); + assertEquals("127.0.0.3", WebUtils.getRemoteIp(request)); + + Mockito.when(request.getHeader(eq(X_FORWARDED_FOR))).thenReturn("127.0.0.3, 127.0.0.4"); + assertEquals("127.0.0.3", WebUtils.getRemoteIp(request)); + + Mockito.when(request.getHeader(eq(X_FORWARDED_FOR))).thenReturn(""); + assertEquals("127.0.0.2", WebUtils.getRemoteIp(request)); + + Mockito.when(request.getHeader(eq(X_REAL_IP))).thenReturn(""); + assertEquals("127.0.0.1", WebUtils.getRemoteIp(request)); } } diff --git a/core/src/test/resources/META-INF/services/com.alibaba.nacos.core.remote.tls.RpcServerSslContextRefresher b/core/src/test/resources/META-INF/services/com.alibaba.nacos.core.remote.tls.RpcServerSslContextRefresher new file mode 100644 index 00000000000..0c84c41b275 --- /dev/null +++ b/core/src/test/resources/META-INF/services/com.alibaba.nacos.core.remote.tls.RpcServerSslContextRefresher @@ -0,0 +1,18 @@ +# +# Copyright 1999-2021 Alibaba Group Holding Ltd. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +com.alibaba.nacos.core.remote.tls.RpcSdkServerSslContextRefresherTest +com.alibaba.nacos.core.remote.tls.RpcClusterServerSslContextRefresherTest diff --git a/core/src/test/resources/logback-test.xml b/core/src/test/resources/logback-test.xml new file mode 100644 index 00000000000..e726ab228a6 --- /dev/null +++ b/core/src/test/resources/logback-test.xml @@ -0,0 +1,19 @@ + + + + + \ No newline at end of file diff --git a/distribution/bin/startup.cmd b/distribution/bin/startup.cmd index 342c97cf5ce..805f2a02cc8 100755 --- a/distribution/bin/startup.cmd +++ b/distribution/bin/startup.cmd @@ -55,7 +55,8 @@ rem if nacos startup mode is standalone if %MODE% == "standalone" ( echo "nacos is starting with standalone" set "NACOS_OPTS=-Dnacos.standalone=true" - set "NACOS_JVM_OPTS=-Xms512m -Xmx512m -Xmn256m" + if "%CUSTOM_NACOS_MEMORY%"=="" ( set "CUSTOM_NACOS_MEMORY=-Xms512m -Xmx512m -Xmn256m" ) + set "NACOS_JVM_OPTS=%CUSTOM_NACOS_MEMORY%" ) rem if nacos startup mode is cluster @@ -64,8 +65,8 @@ if %MODE% == "cluster" ( if %EMBEDDED_STORAGE% == "embedded" ( set "NACOS_OPTS=-DembeddedStorage=true" ) - - set "NACOS_JVM_OPTS=-server -Xms2g -Xmx2g -Xmn1g -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=320m -XX:-OmitStackTraceInFastThrow -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=%BASE_DIR%\logs\java_heapdump.hprof -XX:-UseLargePages" + if "%CUSTOM_NACOS_MEMORY%"=="" ( set "CUSTOM_NACOS_MEMORY=-Xms2g -Xmx2g -Xmn1g -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=320m" ) + set "NACOS_JVM_OPTS=-server %CUSTOM_NACOS_MEMORY% -XX:-OmitStackTraceInFastThrow -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=%BASE_DIR%\logs\java_heapdump.hprof -XX:-UseLargePages" ) rem set nacos's functionMode diff --git a/distribution/bin/startup.sh b/distribution/bin/startup.sh index feb796f7de6..cfe2f486126 100644 --- a/distribution/bin/startup.sh +++ b/distribution/bin/startup.sh @@ -89,16 +89,15 @@ export CUSTOM_SEARCH_LOCATIONS=file:${BASE_DIR}/conf/ # JVM Configuration #=========================================================================================== if [[ "${MODE}" == "standalone" ]]; then - JAVA_OPT="${JAVA_OPT} -Xms512m -Xmx512m -Xmn256m" + JAVA_OPT="${JAVA_OPT} ${CUSTOM_NACOS_MEMORY:- -Xms512m -Xmx512m -Xmn256m}" JAVA_OPT="${JAVA_OPT} -Dnacos.standalone=true" else if [[ "${EMBEDDED_STORAGE}" == "embedded" ]]; then JAVA_OPT="${JAVA_OPT} -DembeddedStorage=true" fi - JAVA_OPT="${JAVA_OPT} -server -Xms2g -Xmx2g -Xmn1g -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=320m" + JAVA_OPT="${JAVA_OPT} -server ${CUSTOM_NACOS_MEMORY:- -Xms2g -Xmx2g -Xmn1g -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=320m}" JAVA_OPT="${JAVA_OPT} -XX:-OmitStackTraceInFastThrow -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${BASE_DIR}/logs/java_heapdump.hprof" JAVA_OPT="${JAVA_OPT} -XX:-UseLargePages" - fi if [[ "${FUNCTION_MODE}" == "config" ]]; then diff --git a/logger-adapter-impl/log4j2-adapter/src/test/java/com/alibaba/nacos/logger/adapter/log4j2/Log4J2NacosLoggingAdapterTest.java b/logger-adapter-impl/log4j2-adapter/src/test/java/com/alibaba/nacos/logger/adapter/log4j2/Log4J2NacosLoggingAdapterTest.java index 177e622ecdc..a39228b186c 100644 --- a/logger-adapter-impl/log4j2-adapter/src/test/java/com/alibaba/nacos/logger/adapter/log4j2/Log4J2NacosLoggingAdapterTest.java +++ b/logger-adapter-impl/log4j2-adapter/src/test/java/com/alibaba/nacos/logger/adapter/log4j2/Log4J2NacosLoggingAdapterTest.java @@ -22,13 +22,12 @@ import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.config.ConfigurationSource; import org.apache.logging.log4j.core.config.LoggerConfig; -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.beans.PropertyChangeListener; import java.io.IOException; @@ -39,17 +38,18 @@ import java.util.Map; import java.util.logging.Logger; -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.assertThrows; +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.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class Log4J2NacosLoggingAdapterTest { +@ExtendWith(MockitoExtension.class) +class Log4J2NacosLoggingAdapterTest { private static final String NACOS_LOGGER_PREFIX = "com.alibaba.nacos"; @@ -60,16 +60,16 @@ public class Log4J2NacosLoggingAdapterTest { Log4J2NacosLoggingAdapter log4J2NacosLoggingAdapter; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { log4J2NacosLoggingAdapter = new Log4J2NacosLoggingAdapter(); nacosLoggingProperties = new NacosLoggingProperties("classpath:nacos-log4j2.xml", System.getProperties()); LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); loggerContext.addPropertyChangeListener(propertyChangeListener); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); loggerContext.removePropertyChangeListener(propertyChangeListener); loggerContext.setConfigLocation(loggerContext.getConfigLocation()); @@ -78,25 +78,25 @@ public void tearDown() throws Exception { } @Test - public void testIsAdaptedLogger() { + void testIsAdaptedLogger() { assertTrue(log4J2NacosLoggingAdapter.isAdaptedLogger(org.apache.logging.slf4j.Log4jLogger.class)); assertFalse(log4J2NacosLoggingAdapter.isAdaptedLogger(Logger.class)); } @Test - public void testIsNeedReloadConfiguration() { + void testIsNeedReloadConfiguration() { assertTrue(log4J2NacosLoggingAdapter.isNeedReloadConfiguration()); log4J2NacosLoggingAdapter.loadConfiguration(nacosLoggingProperties); assertFalse(log4J2NacosLoggingAdapter.isNeedReloadConfiguration()); } @Test - public void testGetDefaultConfigLocation() { + void testGetDefaultConfigLocation() { assertEquals("classpath:nacos-log4j2.xml", log4J2NacosLoggingAdapter.getDefaultConfigLocation()); } @Test - public void testLoadConfiguration() { + void testLoadConfiguration() { LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); Configuration contextConfiguration = loggerContext.getConfiguration(); assertEquals(0, contextConfiguration.getLoggers().size()); @@ -109,12 +109,12 @@ public void testLoadConfiguration() { assertEquals(6, nacosClientLoggers.size()); for (Map.Entry loggerEntry : nacosClientLoggers.entrySet()) { String loggerName = loggerEntry.getKey(); - Assert.assertTrue(loggerName.startsWith(NACOS_LOGGER_PREFIX)); + assertTrue(loggerName.startsWith(NACOS_LOGGER_PREFIX)); } } @Test - public void testLoadConfigurationWithoutLocation() { + void testLoadConfigurationWithoutLocation() { System.setProperty("nacos.logging.default.config.enabled", "false"); nacosLoggingProperties = new NacosLoggingProperties("classpath:nacos-log4j2.xml", System.getProperties()); log4J2NacosLoggingAdapter = new Log4J2NacosLoggingAdapter(); @@ -122,27 +122,27 @@ public void testLoadConfigurationWithoutLocation() { verify(propertyChangeListener, never()).propertyChange(any()); } - @Test(expected = IllegalStateException.class) - public void testLoadConfigurationWithWrongLocation() { - System.setProperty("nacos.logging.config", "http://localhost"); - nacosLoggingProperties = new NacosLoggingProperties("classpath:nacos-log4j2.xml", System.getProperties()); - log4J2NacosLoggingAdapter = new Log4J2NacosLoggingAdapter(); - log4J2NacosLoggingAdapter.loadConfiguration(nacosLoggingProperties); - verify(propertyChangeListener, never()).propertyChange(any()); + @Test + void testLoadConfigurationWithWrongLocation() { + assertThrows(IllegalStateException.class, () -> { + System.setProperty("nacos.logging.config", "http://localhost"); + nacosLoggingProperties = new NacosLoggingProperties("classpath:nacos-log4j2.xml", System.getProperties()); + log4J2NacosLoggingAdapter = new Log4J2NacosLoggingAdapter(); + log4J2NacosLoggingAdapter.loadConfiguration(nacosLoggingProperties); + verify(propertyChangeListener, never()).propertyChange(any()); + }); } @Test - public void testGetConfigurationSourceForNonFileProtocol() + void testGetConfigurationSourceForNonFileProtocol() throws NoSuchMethodException, IOException, InvocationTargetException, IllegalAccessException { - Method getConfigurationSourceMethod = Log4J2NacosLoggingAdapter.class - .getDeclaredMethod("getConfigurationSource", URL.class); + Method getConfigurationSourceMethod = Log4J2NacosLoggingAdapter.class.getDeclaredMethod("getConfigurationSource", URL.class); getConfigurationSourceMethod.setAccessible(true); URL url = mock(URL.class); InputStream inputStream = mock(InputStream.class); when(url.openStream()).thenReturn(inputStream); when(url.getProtocol()).thenReturn("http"); - ConfigurationSource actual = (ConfigurationSource) getConfigurationSourceMethod - .invoke(log4J2NacosLoggingAdapter, url); + ConfigurationSource actual = (ConfigurationSource) getConfigurationSourceMethod.invoke(log4J2NacosLoggingAdapter, url); assertEquals(inputStream, actual.getInputStream()); assertEquals(url, actual.getURL()); } diff --git a/logger-adapter-impl/log4j2-adapter/src/test/java/com/alibaba/nacos/logger/adapter/log4j2/Log4j2NacosLoggingAdapterBuilderTest.java b/logger-adapter-impl/log4j2-adapter/src/test/java/com/alibaba/nacos/logger/adapter/log4j2/Log4j2NacosLoggingAdapterBuilderTest.java index a8db92239e9..88d985845dd 100644 --- a/logger-adapter-impl/log4j2-adapter/src/test/java/com/alibaba/nacos/logger/adapter/log4j2/Log4j2NacosLoggingAdapterBuilderTest.java +++ b/logger-adapter-impl/log4j2-adapter/src/test/java/com/alibaba/nacos/logger/adapter/log4j2/Log4j2NacosLoggingAdapterBuilderTest.java @@ -17,15 +17,15 @@ package com.alibaba.nacos.logger.adapter.log4j2; import com.alibaba.nacos.common.logging.NacosLoggingAdapter; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class Log4j2NacosLoggingAdapterBuilderTest { +class Log4j2NacosLoggingAdapterBuilderTest { @Test - public void build() { + void build() { Log4j2NacosLoggingAdapterBuilder builder = new Log4j2NacosLoggingAdapterBuilder(); NacosLoggingAdapter adapter = builder.build(); assertNotNull(adapter); diff --git a/logger-adapter-impl/log4j2-adapter/src/test/java/com/alibaba/nacos/logger/adapter/log4j2/NacosClientPropertiesLookupTest.java b/logger-adapter-impl/log4j2-adapter/src/test/java/com/alibaba/nacos/logger/adapter/log4j2/NacosClientPropertiesLookupTest.java index d193ac2d62c..d65de95b1ba 100644 --- a/logger-adapter-impl/log4j2-adapter/src/test/java/com/alibaba/nacos/logger/adapter/log4j2/NacosClientPropertiesLookupTest.java +++ b/logger-adapter-impl/log4j2-adapter/src/test/java/com/alibaba/nacos/logger/adapter/log4j2/NacosClientPropertiesLookupTest.java @@ -17,19 +17,20 @@ package com.alibaba.nacos.logger.adapter.log4j2; import com.alibaba.nacos.common.logging.NacosLoggingProperties; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class NacosClientPropertiesLookupTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class NacosClientPropertiesLookupTest { @Test - public void testLookUp() { + void testLookUp() { System.setProperty("test.nacos.logging.lookup", "true"); NacosLoggingProperties properties = new NacosLoggingProperties("", System.getProperties()); Log4j2NacosLoggingPropertiesHolder.setProperties(properties); NacosClientPropertiesLookup nacosClientPropertiesLookup = new NacosClientPropertiesLookup(); final String actual = nacosClientPropertiesLookup.lookup("test.nacos.logging.lookup"); - Assert.assertEquals("true", actual); + assertEquals("true", actual); } } diff --git a/logger-adapter-impl/logback-adapter-12/src/main/java/com/alibaba/nacos/logger/adapter/logback12/LogbackNacosLoggingAdapter.java b/logger-adapter-impl/logback-adapter-12/src/main/java/com/alibaba/nacos/logger/adapter/logback12/LogbackNacosLoggingAdapter.java index b6049362819..07d3f6106e5 100644 --- a/logger-adapter-impl/logback-adapter-12/src/main/java/com/alibaba/nacos/logger/adapter/logback12/LogbackNacosLoggingAdapter.java +++ b/logger-adapter-impl/logback-adapter-12/src/main/java/com/alibaba/nacos/logger/adapter/logback12/LogbackNacosLoggingAdapter.java @@ -109,7 +109,9 @@ private LoggerContext loadConfigurationOnStart(final String location) { configurator.setContext(loggerContext); if (StringUtils.isNotBlank(location)) { try { + boolean isPackagingDataEnabled = loggerContext.isPackagingDataEnabled(); configurator.configure(ResourceUtils.getResourceUrl(location)); + loggerContext.setPackagingDataEnabled(isPackagingDataEnabled); } catch (Exception e) { throw new IllegalStateException("Could not initialize Logback Nacos logging from " + location, e); } diff --git a/logger-adapter-impl/logback-adapter-12/src/test/java/com/alibaba/nacos/logger/adapter/logback12/LogbackNacosLoggingAdapterBuilderTest.java b/logger-adapter-impl/logback-adapter-12/src/test/java/com/alibaba/nacos/logger/adapter/logback12/LogbackNacosLoggingAdapterBuilderTest.java index 0325883ed21..1e401c8ac23 100644 --- a/logger-adapter-impl/logback-adapter-12/src/test/java/com/alibaba/nacos/logger/adapter/logback12/LogbackNacosLoggingAdapterBuilderTest.java +++ b/logger-adapter-impl/logback-adapter-12/src/test/java/com/alibaba/nacos/logger/adapter/logback12/LogbackNacosLoggingAdapterBuilderTest.java @@ -17,15 +17,15 @@ package com.alibaba.nacos.logger.adapter.logback12; import com.alibaba.nacos.common.logging.NacosLoggingAdapter; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class LogbackNacosLoggingAdapterBuilderTest { +class LogbackNacosLoggingAdapterBuilderTest { @Test - public void build() { + void build() { LogbackNacosLoggingAdapterBuilder builder = new LogbackNacosLoggingAdapterBuilder(); NacosLoggingAdapter adapter = builder.build(); assertNotNull(adapter); diff --git a/logger-adapter-impl/logback-adapter-12/src/test/java/com/alibaba/nacos/logger/adapter/logback12/LogbackNacosLoggingAdapterTest.java b/logger-adapter-impl/logback-adapter-12/src/test/java/com/alibaba/nacos/logger/adapter/logback12/LogbackNacosLoggingAdapterTest.java index 26e78daa5c1..7266dac6cc8 100644 --- a/logger-adapter-impl/logback-adapter-12/src/test/java/com/alibaba/nacos/logger/adapter/logback12/LogbackNacosLoggingAdapterTest.java +++ b/logger-adapter-impl/logback-adapter-12/src/test/java/com/alibaba/nacos/logger/adapter/logback12/LogbackNacosLoggingAdapterTest.java @@ -22,12 +22,12 @@ import ch.qos.logback.classic.spi.LoggerContextListener; import ch.qos.logback.core.CoreConstants; import com.alibaba.nacos.common.logging.NacosLoggingProperties; -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 org.slf4j.ILoggerFactory; import org.slf4j.LoggerFactory; import org.slf4j.impl.StaticLoggerBinder; @@ -35,14 +35,15 @@ import java.lang.reflect.Field; import java.util.Properties; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class LogbackNacosLoggingAdapterTest { LogbackNacosLoggingAdapter logbackNacosLoggingAdapter; @@ -54,8 +55,8 @@ public class LogbackNacosLoggingAdapterTest { NacosLoggingProperties loggingProperties; - @Before - public void setUp() throws NoSuchFieldException, IllegalAccessException { + @BeforeEach + void setUp() throws NoSuchFieldException, IllegalAccessException { logbackNacosLoggingAdapter = new LogbackNacosLoggingAdapter(); ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); if (loggerFactory instanceof LoggerContext) { @@ -70,8 +71,8 @@ public void setUp() throws NoSuchFieldException, IllegalAccessException { loggingProperties = new NacosLoggingProperties("classpath:nacos-logback12.xml", new Properties()); } - @After - public void tearDown() throws NoSuchFieldException, IllegalAccessException { + @AfterEach + void tearDown() throws NoSuchFieldException, IllegalAccessException { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); loggerContext.removeListener(loggerContextListener); if (null != cachedLoggerFactory) { @@ -89,7 +90,7 @@ public void setLoggerFactory(ILoggerFactory loggerFactory) throws NoSuchFieldExc } @Test - public void testLoadConfigurationSuccess() { + void testLoadConfigurationSuccess() { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); loggerContext.putObject(CoreConstants.RECONFIGURE_ON_CHANGE_TASK, new ReconfigureOnChangeTask()); logbackNacosLoggingAdapter.loadConfiguration(loggingProperties); @@ -122,30 +123,32 @@ public void testLoadConfigurationSuccess() { } @Test - public void testIsAdaptedLogger() { + void testIsAdaptedLogger() { assertTrue(logbackNacosLoggingAdapter.isAdaptedLogger(Logger.class)); assertFalse(logbackNacosLoggingAdapter.isAdaptedLogger(java.util.logging.Logger.class)); } - @Test(expected = IllegalStateException.class) - public void testLoadConfigurationFailure() { - System.setProperty("nacos.logging.config", "http://localhost"); - loggingProperties = new NacosLoggingProperties("classpath:nacos-logback12.xml", System.getProperties()); - logbackNacosLoggingAdapter.loadConfiguration(loggingProperties); + @Test + void testLoadConfigurationFailure() { + assertThrows(IllegalStateException.class, () -> { + System.setProperty("nacos.logging.config", "http://localhost"); + loggingProperties = new NacosLoggingProperties("classpath:nacos-logback12.xml", System.getProperties()); + logbackNacosLoggingAdapter.loadConfiguration(loggingProperties); + }); } @Test - public void testIsNeedReloadConfiguration() { + void testIsNeedReloadConfiguration() { assertFalse(logbackNacosLoggingAdapter.isNeedReloadConfiguration()); } @Test - public void testGetDefaultConfigLocation() { + void testGetDefaultConfigLocation() { assertEquals("classpath:nacos-logback12.xml", logbackNacosLoggingAdapter.getDefaultConfigLocation()); } @Test - public void testLoadConfigurationReload() { + void testLoadConfigurationReload() { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); loggerContext.putObject(CoreConstants.RECONFIGURE_ON_CHANGE_TASK, new ReconfigureOnChangeTask()); logbackNacosLoggingAdapter.loadConfiguration(loggingProperties); @@ -160,7 +163,7 @@ public void testLoadConfigurationReload() { } @Test - public void testLoadConfigurationStart() { + void testLoadConfigurationStart() { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); loggerContext.putObject(CoreConstants.RECONFIGURE_ON_CHANGE_TASK, new ReconfigureOnChangeTask()); logbackNacosLoggingAdapter.loadConfiguration(loggingProperties); @@ -175,7 +178,7 @@ public void testLoadConfigurationStart() { } @Test - public void testLoadConfigurationStop() { + void testLoadConfigurationStop() { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); loggerContext.putObject(CoreConstants.RECONFIGURE_ON_CHANGE_TASK, new ReconfigureOnChangeTask()); logbackNacosLoggingAdapter.loadConfiguration(loggingProperties); diff --git a/logger-adapter-impl/logback-adapter-12/src/test/java/com/alibaba/nacos/logger/adapter/logback12/NacosClientPropertyActionTest.java b/logger-adapter-impl/logback-adapter-12/src/test/java/com/alibaba/nacos/logger/adapter/logback12/NacosClientPropertyActionTest.java index 597027ca75c..daf42d0b5e9 100644 --- a/logger-adapter-impl/logback-adapter-12/src/test/java/com/alibaba/nacos/logger/adapter/logback12/NacosClientPropertyActionTest.java +++ b/logger-adapter-impl/logback-adapter-12/src/test/java/com/alibaba/nacos/logger/adapter/logback12/NacosClientPropertyActionTest.java @@ -22,19 +22,19 @@ import ch.qos.logback.core.status.ErrorStatus; import ch.qos.logback.core.status.Status; import com.alibaba.nacos.common.logging.NacosLoggingProperties; -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 org.mockito.Mockito; import org.xml.sax.Attributes; import java.util.List; import java.util.Properties; -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 NacosClientPropertyActionTest { +class NacosClientPropertyActionTest { ContextBase context; @@ -42,20 +42,20 @@ public class NacosClientPropertyActionTest { private Properties properties; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { context = new ContextBase(); properties = new Properties(); loggingProperties = new NacosLoggingProperties("classpath:test.xml", properties); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { context.stop(); } @Test - public void testLookUpVar() throws ActionException { + void testLookUpVar() throws ActionException { properties.setProperty("test.nacos.logging.action.lookup", "true"); @@ -78,7 +78,7 @@ public void testLookUpVar() throws ActionException { } @Test - public void testBeginWithoutName() throws ActionException { + void testBeginWithoutName() throws ActionException { final InterpretationContext interpretationContext = new InterpretationContext(context, null); final Attributes mockAttr = Mockito.mock(AttributesForTest.class); Mockito.when(mockAttr.getValue(Mockito.eq("name"))).thenReturn(""); @@ -91,8 +91,7 @@ public void testBeginWithoutName() throws ActionException { List statusList = context.getStatusManager().getCopyOfStatusList(); assertEquals(1, statusList.size()); assertTrue(statusList.get(0) instanceof ErrorStatus); - assertEquals("The \"name\" and \"source\" attributes of must be set", - statusList.get(0).getMessage()); + assertEquals("The \"name\" and \"source\" attributes of must be set", statusList.get(0).getMessage()); } static class AttributesForTest implements Attributes { diff --git a/logger-adapter-impl/logback-adapter-12/src/test/java/com/alibaba/nacos/logger/adapter/logback12/NacosLogbackConfiguratorAdapterV1Test.java b/logger-adapter-impl/logback-adapter-12/src/test/java/com/alibaba/nacos/logger/adapter/logback12/NacosLogbackConfiguratorAdapterV1Test.java index ef9df73b07c..a5ae2679bee 100644 --- a/logger-adapter-impl/logback-adapter-12/src/test/java/com/alibaba/nacos/logger/adapter/logback12/NacosLogbackConfiguratorAdapterV1Test.java +++ b/logger-adapter-impl/logback-adapter-12/src/test/java/com/alibaba/nacos/logger/adapter/logback12/NacosLogbackConfiguratorAdapterV1Test.java @@ -20,12 +20,12 @@ import ch.qos.logback.core.joran.spi.JoranException; import ch.qos.logback.core.status.ErrorStatus; import ch.qos.logback.core.status.Status; -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.IOException; import java.io.InputStream; @@ -33,14 +33,18 @@ import java.net.URLConnection; import java.util.List; -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; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class NacosLogbackConfiguratorAdapterV1Test { +@ExtendWith(MockitoExtension.class) +class NacosLogbackConfiguratorAdapterV1Test { + + ContextBase context; + + NacosLogbackConfiguratorAdapterV1 nacosLogbackConfiguratorAdapter; @Mock private URL url; @@ -51,12 +55,8 @@ public class NacosLogbackConfiguratorAdapterV1Test { @Mock private InputStream inputStream; - ContextBase context; - - NacosLogbackConfiguratorAdapterV1 nacosLogbackConfiguratorAdapter; - - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { nacosLogbackConfiguratorAdapter = new NacosLogbackConfiguratorAdapterV1(); context = new ContextBase(); nacosLogbackConfiguratorAdapter.setContext(context); @@ -64,13 +64,13 @@ public void setUp() throws Exception { when(urlConnection.getInputStream()).thenReturn(inputStream); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { context.stop(); } @Test - public void testConfigureWithError() throws Exception { + void testConfigureWithError() throws Exception { doThrow(new IOException("test")).when(inputStream).close(); try { nacosLogbackConfiguratorAdapter.configure(url); diff --git a/logger-adapter-impl/pom.xml b/logger-adapter-impl/pom.xml index 6f5222ad5fc..d63a78ac229 100644 --- a/logger-adapter-impl/pom.xml +++ b/logger-adapter-impl/pom.xml @@ -38,6 +38,7 @@ com.alibaba.nacos nacos-common + true @@ -94,4 +95,4 @@ - \ No newline at end of file + diff --git a/naming/src/main/java/com/alibaba/nacos/naming/cluster/ServerStatusManager.java b/naming/src/main/java/com/alibaba/nacos/naming/cluster/ServerStatusManager.java index 1020b7bbd00..c86992073be 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/cluster/ServerStatusManager.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/cluster/ServerStatusManager.java @@ -16,14 +16,15 @@ package com.alibaba.nacos.naming.cluster; -import com.alibaba.nacos.naming.consistency.ConsistencyService; +import com.alibaba.nacos.common.utils.StringUtils; +import com.alibaba.nacos.core.distributed.ProtocolManager; +import com.alibaba.nacos.naming.constants.Constants; import com.alibaba.nacos.naming.misc.GlobalExecutor; import com.alibaba.nacos.naming.misc.SwitchDomain; -import com.alibaba.nacos.common.utils.StringUtils; +import com.alipay.sofa.jraft.RouteTable; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; -import javax.annotation.Resource; import java.util.Optional; /** @@ -35,14 +36,14 @@ @Service public class ServerStatusManager { - @Resource(name = "persistentConsistencyServiceDelegate") - private ConsistencyService consistencyService; + private final ProtocolManager protocolManager; private final SwitchDomain switchDomain; private ServerStatus serverStatus = ServerStatus.STARTING; - public ServerStatusManager(SwitchDomain switchDomain) { + public ServerStatusManager(ProtocolManager protocolManager, SwitchDomain switchDomain) { + this.protocolManager = protocolManager; this.switchDomain = switchDomain; } @@ -58,19 +59,30 @@ private void refreshServerStatus() { return; } - if (consistencyService.isAvailable()) { + if (hasLeader()) { serverStatus = ServerStatus.UP; } else { serverStatus = ServerStatus.DOWN; } } + private boolean hasLeader() { + if (protocolManager.getCpProtocol() == null) { + return false; + } + return null != RouteTable.getInstance().selectLeader(Constants.NAMING_PERSISTENT_SERVICE_GROUP); + } + public ServerStatus getServerStatus() { return serverStatus; } public Optional getErrorMsg() { - return consistencyService.getErrorMsg(); + if (hasLeader()) { + return Optional.empty(); + } + return Optional.of("No leader for raft group " + Constants.NAMING_PERSISTENT_SERVICE_GROUP + + ", please see logs `alipay-jraft.log` or `naming-raft.log` to see details."); } public class ServerStatusUpdater implements Runnable { diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/ConsistencyService.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/ConsistencyService.java deleted file mode 100644 index b242d9d6aa6..00000000000 --- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/ConsistencyService.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.naming.consistency; - -import com.alibaba.nacos.api.exception.NacosException; -import com.alibaba.nacos.naming.pojo.Record; - -import java.util.Optional; - -/** - * Consistence service for all implementations to derive. - * - *

    We announce this consistency service to decouple the specific consistency implementation with business logic. - * User should not be aware of what consistency protocol is being used. - * - *

    In this way, we also provide space for user to extend the underlying consistency protocols, as long as they obey - * our consistency baseline. - * - * @author nkorange - * @since 1.0.0 - */ -public interface ConsistencyService { - - /** - * Put a data related to a key to Nacos cluster. - * - * @param key key of data, this key should be globally unique - * @param value value of data - * @throws NacosException nacos exception - */ - void put(String key, Record value) throws NacosException; - - /** - * Remove a data from Nacos cluster. - * - * @param key key of data - * @throws NacosException nacos exception - */ - void remove(String key) throws NacosException; - - /** - * Get a data from Nacos cluster. - * - * @param key key of data - * @return data related to the key - * @throws NacosException nacos exception - */ - Datum get(String key) throws NacosException; - - /** - * Listen for changes of a data. - * - * @param key key of data - * @param listener callback of data change - * @throws NacosException nacos exception - */ - void listen(String key, RecordListener listener) throws NacosException; - - /** - * Cancel listening of a data. - * - * @param key key of data - * @param listener callback of data change - * @throws NacosException nacos exception - */ - void unListen(String key, RecordListener listener) throws NacosException; - - /** - * Get the error message of the consistency protocol. - * - * @return the consistency protocol error message. - */ - Optional getErrorMsg(); - - /** - * Tell the status of this consistency service. - * - * @return true if available - */ - boolean isAvailable(); -} \ No newline at end of file diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/RecordListener.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/RecordListener.java deleted file mode 100644 index 9a3b45ecdd1..00000000000 --- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/RecordListener.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.naming.consistency; - -import com.alibaba.nacos.naming.pojo.Record; - -/** - * Data listener public interface. - * - * @author nacos - */ -public interface RecordListener { - - /** - * Determine if the listener was registered with this key. - * - * @param key candidate key - * @return true if the listener was registered with this key - */ - boolean interests(String key); - - /** - * Determine if the listener is to be removed by matching the 'key'. - * - * @param key key to match - * @return true if match success - */ - boolean matchUnlistenKey(String key); - - /** - * Action to do if data of target key has changed. - * - * @param key target key - * @param value data of the key - * @throws Exception exception - */ - void onChange(String key, T value) throws Exception; - - /** - * Action to do if data of target key has been removed. - * - * @param key target key - * @throws Exception exception - */ - void onDelete(String key) throws Exception; -} diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/ValueChangeEvent.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/ValueChangeEvent.java deleted file mode 100644 index f05729bffec..00000000000 --- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/ValueChangeEvent.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.naming.consistency; - -import com.alibaba.nacos.common.notify.Event; -import com.alibaba.nacos.consistency.DataOperation; -import com.alibaba.nacos.naming.pojo.Record; - -/** - * The value changes events. //TODO Recipients need to implement the ability to receive batch events - * - * @author liaochuntao - */ -public class ValueChangeEvent extends Event { - - private final String key; - - private final Record value; - - private final DataOperation action; - - public ValueChangeEvent(String key, Record value, DataOperation action) { - this.key = key; - this.value = value; - this.action = action; - } - - public String getKey() { - return key; - } - - public Record getValue() { - return value; - } - - public DataOperation getAction() { - return action; - } - - public static ValueChangeEventBuilder builder() { - return new ValueChangeEventBuilder(); - } - - public static final class ValueChangeEventBuilder { - - private String key; - - private Record value; - - private DataOperation action; - - private ValueChangeEventBuilder() { - } - - public ValueChangeEventBuilder key(String key) { - this.key = key; - return this; - } - - public ValueChangeEventBuilder value(Record value) { - this.value = value; - return this; - } - - public ValueChangeEventBuilder action(DataOperation action) { - this.action = action; - return this; - } - - public ValueChangeEvent build() { - return new ValueChangeEvent(key, value, action); - } - } -} diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/PersistentConsistencyServiceDelegateImpl.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/PersistentConsistencyServiceDelegateImpl.java deleted file mode 100644 index 55c26613bf6..00000000000 --- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/PersistentConsistencyServiceDelegateImpl.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.naming.consistency.persistent; - -import com.alibaba.nacos.api.exception.NacosException; -import com.alibaba.nacos.core.distributed.ProtocolManager; -import com.alibaba.nacos.naming.consistency.Datum; -import com.alibaba.nacos.naming.consistency.RecordListener; -import com.alibaba.nacos.naming.consistency.persistent.impl.BasePersistentServiceProcessor; -import com.alibaba.nacos.naming.consistency.persistent.impl.PersistentServiceProcessor; -import com.alibaba.nacos.naming.consistency.persistent.impl.StandalonePersistentServiceProcessor; -import com.alibaba.nacos.naming.pojo.Record; -import com.alibaba.nacos.sys.env.EnvUtil; -import org.springframework.context.annotation.DependsOn; -import org.springframework.stereotype.Component; - -import java.util.Optional; - -/** - * Persistent consistency service delegate. - * - * @author xiweng.yy - */ -@DependsOn("ProtocolManager") -@Component("persistentConsistencyServiceDelegate") -public class PersistentConsistencyServiceDelegateImpl implements PersistentConsistencyService { - - private final BasePersistentServiceProcessor persistentServiceProcessor; - - public PersistentConsistencyServiceDelegateImpl(ProtocolManager protocolManager) throws Exception { - this.persistentServiceProcessor = createPersistentServiceProcessor(protocolManager); - } - - @Override - public void put(String key, Record value) throws NacosException { - persistentServiceProcessor.put(key, value); - } - - @Override - public void remove(String key) throws NacosException { - persistentServiceProcessor.remove(key); - } - - @Override - public Datum get(String key) throws NacosException { - return persistentServiceProcessor.get(key); - } - - @Override - public void listen(String key, RecordListener listener) throws NacosException { - persistentServiceProcessor.listen(key, listener); - } - - @Override - public void unListen(String key, RecordListener listener) throws NacosException { - persistentServiceProcessor.unListen(key, listener); - } - - @Override - public boolean isAvailable() { - return persistentServiceProcessor.isAvailable(); - } - - @Override - public Optional getErrorMsg() { - return persistentServiceProcessor.getErrorMsg(); - } - - private BasePersistentServiceProcessor createPersistentServiceProcessor(ProtocolManager protocolManager) - throws Exception { - final BasePersistentServiceProcessor processor = - EnvUtil.getStandaloneMode() ? new StandalonePersistentServiceProcessor() - : new PersistentServiceProcessor(protocolManager); - processor.afterConstruct(); - return processor; - } -} diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/PersistentNotifier.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/PersistentNotifier.java deleted file mode 100644 index 1356c53af3d..00000000000 --- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/PersistentNotifier.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.naming.consistency.persistent; - -import com.alibaba.nacos.common.notify.Event; -import com.alibaba.nacos.common.notify.listener.Subscriber; -import com.alibaba.nacos.common.utils.ConcurrentHashSet; -import com.alibaba.nacos.consistency.DataOperation; -import com.alibaba.nacos.naming.consistency.RecordListener; -import com.alibaba.nacos.naming.consistency.ValueChangeEvent; -import com.alibaba.nacos.naming.misc.Loggers; -import com.alibaba.nacos.naming.pojo.Record; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Function; - -/** - * persistent notifier, It is responsible for notifying interested listeners of all write changes to the data. - * - * @author liaochuntao - */ -public final class PersistentNotifier extends Subscriber { - - private final Map> listenerMap = new ConcurrentHashMap<>(32); - - private final Function find; - - public PersistentNotifier(Function find) { - this.find = find; - } - - /** - * register listener with key. - * - * @param key key - * @param listener {@link RecordListener} - */ - public void registerListener(final String key, final RecordListener listener) { - listenerMap.computeIfAbsent(key, s -> new ConcurrentHashSet<>()).add(listener); - } - - /** - * deregister listener by key. - * - * @param key key - * @param listener {@link RecordListener} - */ - public void deregisterListener(final String key, final RecordListener listener) { - if (!listenerMap.containsKey(key)) { - return; - } - listenerMap.get(key).remove(listener); - } - - /** - * deregister all listener by key. - * - * @param key key - */ - public void deregisterAllListener(final String key) { - listenerMap.remove(key); - } - - public Map> getListeners() { - return listenerMap; - } - - /** - * notify value to listener with {@link DataOperation} and key. - * - * @param key key - * @param action {@link DataOperation} - * @param value value - * @param type - */ - public void notify(final String key, final DataOperation action, final T value) { - - if (!listenerMap.containsKey(key)) { - return; - } - - for (RecordListener listener : listenerMap.get(key)) { - try { - if (action == DataOperation.CHANGE) { - listener.onChange(key, value); - continue; - } - if (action == DataOperation.DELETE) { - listener.onDelete(key); - } - } catch (Throwable e) { - Loggers.RAFT.error("[NACOS-RAFT] error while notifying listener of key: {}", key, e); - } - } - } - - @Override - public void onEvent(ValueChangeEvent event) { - notify(event.getKey(), event.getAction(), find.apply(event.getKey())); - } - - @Override - public Class subscribeType() { - return ValueChangeEvent.class; - } -} diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/BasePersistentServiceProcessor.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/BasePersistentServiceProcessor.java deleted file mode 100644 index ab4b721067e..00000000000 --- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/BasePersistentServiceProcessor.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.naming.consistency.persistent.impl; - -import com.alibaba.nacos.api.exception.NacosException; -import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; -import com.alibaba.nacos.common.notify.NotifyCenter; -import com.alibaba.nacos.common.utils.ByteUtils; -import com.alibaba.nacos.common.utils.TypeUtils; -import com.alibaba.nacos.consistency.DataOperation; -import com.alibaba.nacos.consistency.SerializeFactory; -import com.alibaba.nacos.consistency.Serializer; -import com.alibaba.nacos.consistency.cp.RequestProcessor4CP; -import com.alibaba.nacos.consistency.entity.ReadRequest; -import com.alibaba.nacos.consistency.entity.Response; -import com.alibaba.nacos.consistency.entity.WriteRequest; -import com.alibaba.nacos.consistency.snapshot.SnapshotOperation; -import com.alibaba.nacos.core.exception.KvStorageException; -import com.alibaba.nacos.core.storage.kv.KvStorage; -import com.alibaba.nacos.naming.consistency.Datum; -import com.alibaba.nacos.naming.consistency.KeyBuilder; -import com.alibaba.nacos.naming.consistency.RecordListener; -import com.alibaba.nacos.naming.consistency.ValueChangeEvent; -import com.alibaba.nacos.naming.consistency.persistent.PersistentConsistencyService; -import com.alibaba.nacos.naming.consistency.persistent.PersistentNotifier; -import com.alibaba.nacos.naming.constants.Constants; -import com.alibaba.nacos.naming.misc.Loggers; -import com.alibaba.nacos.naming.misc.UtilsAndCommons; -import com.alibaba.nacos.naming.pojo.Record; -import com.google.protobuf.ByteString; - -import java.lang.reflect.Type; -import java.nio.file.Paths; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -/** - * New service data persistence handler. - * - * @author liaochuntao - */ -public abstract class BasePersistentServiceProcessor extends RequestProcessor4CP - implements PersistentConsistencyService { - - enum Op { - /** - * write ops. - */ - Write("Write"), - - /** - * read ops. - */ - Read("Read"), - - /** - * delete ops. - */ - Delete("Delete"); - - protected final String desc; - - Op(String desc) { - this.desc = desc; - } - } - - protected final KvStorage kvStorage; - - protected final Serializer serializer; - - /** - * Whether an unrecoverable error occurred. - */ - protected volatile boolean hasError = false; - - protected volatile String jRaftErrorMsg; - - /** - * If use old raft, should not notify listener even new listener add. - */ - protected volatile boolean startNotify = false; - - /** - * During snapshot processing, the processing of other requests needs to be paused. - */ - protected final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); - - protected final ReentrantReadWriteLock.ReadLock readLock = lock.readLock(); - - protected final PersistentNotifier notifier; - - protected final int queueMaxSize = 16384; - - protected final int priority = 10; - - public BasePersistentServiceProcessor() throws Exception { - this.kvStorage = new NamingKvStorage(Paths.get(UtilsAndCommons.DATA_BASE_DIR, "data").toString()); - this.serializer = SerializeFactory.getSerializer("JSON"); - this.notifier = new PersistentNotifier(key -> { - try { - byte[] data = kvStorage.get(ByteUtils.toBytes(key)); - Datum datum = serializer.deserialize(data, getDatumTypeFromKey(key)); - return null != datum ? datum.value : null; - } catch (KvStorageException ex) { - throw new NacosRuntimeException(ex.getErrCode(), ex.getErrMsg()); - } catch (Exception e) { - throw new NacosRuntimeException(NacosException.SERVER_ERROR, e.getMessage()); - } - }); - } - - @SuppressWarnings("unchecked") - public void afterConstruct() { - NotifyCenter.registerToPublisher(ValueChangeEvent.class, queueMaxSize); - } - - @Override - public Response onRequest(ReadRequest request) { - final Lock lock = readLock; - lock.lock(); - try { - final List keys = serializer - .deserialize(request.getData().toByteArray(), TypeUtils.parameterize(List.class, byte[].class)); - final Map result = kvStorage.batchGet(keys); - final BatchReadResponse response = new BatchReadResponse(); - result.forEach(response::append); - return Response.newBuilder().setSuccess(true).setData(ByteString.copyFrom(serializer.serialize(response))) - .build(); - } catch (KvStorageException e) { - return Response.newBuilder().setSuccess(false).setErrMsg(e.getErrMsg()).build(); - } catch (Exception e) { - Loggers.RAFT.warn("On read request failed, ", e); - return Response.newBuilder().setSuccess(false).setErrMsg(e.getMessage()).build(); - } finally { - lock.unlock(); - } - } - - @Override - public Response onApply(WriteRequest request) { - final byte[] data = request.getData().toByteArray(); - final Lock lock = readLock; - lock.lock(); - try { - final BatchWriteRequest bwRequest = serializer.deserialize(data, BatchWriteRequest.class); - final Op op = Op.valueOf(request.getOperation()); - switch (op) { - case Write: - kvStorage.batchPut(bwRequest.getKeys(), bwRequest.getValues()); - break; - case Delete: - kvStorage.batchDelete(bwRequest.getKeys()); - break; - default: - return Response.newBuilder().setSuccess(false).setErrMsg("unsupport operation : " + op).build(); - } - publishValueChangeEvent(op, bwRequest); - return Response.newBuilder().setSuccess(true).build(); - } catch (KvStorageException e) { - return Response.newBuilder().setSuccess(false).setErrMsg(e.getErrMsg()).build(); - } catch (Exception e) { - Loggers.RAFT.warn("On apply write request failed, ", e); - return Response.newBuilder().setSuccess(false).setErrMsg(e.getMessage()).build(); - } finally { - lock.unlock(); - } - } - - private void publishValueChangeEvent(final Op op, final BatchWriteRequest request) { - final List keys = request.getKeys(); - final List values = request.getValues(); - for (int i = 0; i < keys.size(); i++) { - final String key = new String(keys.get(i)); - // Ignore old 1.x version data - if (!KeyBuilder.matchSwitchKey(key)) { - continue; - } - final Datum datum = serializer.deserialize(values.get(i), getDatumTypeFromKey(key)); - final Record value = null != datum ? datum.value : null; - final ValueChangeEvent event = ValueChangeEvent.builder().key(key).value(value) - .action(Op.Delete.equals(op) ? DataOperation.DELETE : DataOperation.CHANGE).build(); - NotifyCenter.publishEvent(event); - } - } - - @Override - public String group() { - return Constants.NAMING_PERSISTENT_SERVICE_GROUP; - } - - @Override - public List loadSnapshotOperate() { - return Collections.singletonList(new NamingSnapshotOperation(this.kvStorage, lock, serializer)); - } - - @Override - public void onError(Throwable error) { - super.onError(error); - hasError = true; - jRaftErrorMsg = error.getMessage(); - } - - protected Type getDatumTypeFromKey(String key) { - return TypeUtils.parameterize(Datum.class, getClassOfRecordFromKey(key)); - } - - protected Class getClassOfRecordFromKey(String key) { - if (KeyBuilder.matchSwitchKey(key)) { - return com.alibaba.nacos.naming.misc.SwitchDomain.class; - } - return Record.class; - } - - protected void notifierDatumIfAbsent(String key, RecordListener listener) throws NacosException { - if (KeyBuilder.SERVICE_META_KEY_PREFIX.equals(key)) { - notifierAllServiceMeta(listener); - } else { - Datum datum = get(key); - if (null != datum) { - notifierDatum(key, datum, listener); - } - } - } - - /** - * This notify should only notify once during startup. - */ - private void notifierAllServiceMeta(RecordListener listener) throws NacosException { - for (byte[] each : kvStorage.allKeys()) { - String key = new String(each); - if (listener.interests(key)) { - Datum datum = get(key); - if (null != datum) { - notifierDatum(key, datum, listener); - } - } - } - } - - private void notifierDatum(String key, Datum datum, RecordListener listener) { - try { - listener.onChange(key, datum.value); - } catch (Exception e) { - Loggers.RAFT.error("NACOS-RAFT failed to notify listener", e); - } - } -} diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/NamingKvStorage.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/NamingKvStorage.java deleted file mode 100644 index a3b0c0f769b..00000000000 --- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/NamingKvStorage.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.naming.consistency.persistent.impl; - -import com.alibaba.nacos.core.exception.ErrorCode; -import com.alibaba.nacos.core.exception.KvStorageException; -import com.alibaba.nacos.core.storage.StorageFactory; -import com.alibaba.nacos.core.storage.kv.KvStorage; -import com.alibaba.nacos.core.storage.kv.MemoryKvStorage; -import com.alibaba.nacos.sys.utils.TimerContext; -import com.alibaba.nacos.naming.misc.Loggers; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Kv storage implementation for naming. - * - * @author xiweng.yy - */ -public class NamingKvStorage extends MemoryKvStorage { - - private static final String LOAD_SNAPSHOT = NamingKvStorage.class.getSimpleName() + ".snapshotLoad"; - - private static final String LABEL = "naming-persistent"; - - private final String baseDir; - - private final KvStorage baseDirStorage; - - public NamingKvStorage(final String baseDir) throws Exception { - this.baseDir = baseDir; - this.baseDirStorage = StorageFactory.createKvStorage(KvStorage.KvType.File, LABEL, baseDir); - } - - @Override - public byte[] get(byte[] key) throws KvStorageException { - // First get the data from the memory Cache - byte[] result = super.get(key); - if (null == result) { - try { - KvStorage storage = getStorage(); - result = null == storage ? null : storage.get(key); - if (null != result) { - super.put(key, result); - } - } catch (Exception e) { - throw new KvStorageException(ErrorCode.KVStorageWriteError.getCode(), - "Get data failed, key: " + new String(key) + ", detail: " + e.getMessage(), e); - } - } - return result; - } - - @Override - public Map batchGet(List keys) throws KvStorageException { - Map result = new HashMap<>(keys.size()); - for (byte[] key : keys) { - byte[] val = get(key); - if (val != null) { - result.put(key, val); - } - } - return result; - } - - @Override - public void put(byte[] key, byte[] value) throws KvStorageException { - try { - KvStorage storage = getStorage(); - storage.put(key, value); - } catch (Exception e) { - throw new KvStorageException(ErrorCode.KVStorageWriteError.getCode(), - "Put data failed, key: " + new String(key) + ", detail: " + e.getMessage(), e); - } - // after actual storage put success, put it in memory, memory put should success all the time - super.put(key, value); - } - - @Override - public void batchPut(List keys, List values) throws KvStorageException { - if (keys.size() != values.size()) { - throw new KvStorageException(ErrorCode.KVStorageBatchWriteError, - "key's size must be equal to value's size"); - } - int size = keys.size(); - for (int i = 0; i < size; i++) { - put(keys.get(i), values.get(i)); - } - } - - @Override - public void delete(byte[] key) throws KvStorageException { - try { - KvStorage storage = getStorage(); - if (null != storage) { - storage.delete(key); - } - } catch (Exception e) { - throw new KvStorageException(ErrorCode.KVStorageDeleteError.getCode(), - "Delete data failed, key: " + new String(key) + ", detail: " + e.getMessage(), e); - } - // after actual storage delete success, put it in memory, memory delete should success all the time - super.delete(key); - } - - @Override - public void batchDelete(List keys) throws KvStorageException { - for (byte[] each : keys) { - delete(each); - } - } - - @Override - public void doSnapshot(String backupPath) throws KvStorageException { - baseDirStorage.doSnapshot(backupPath); - } - - @Override - public void snapshotLoad(String path) throws KvStorageException { - TimerContext.start(LOAD_SNAPSHOT); - try { - baseDirStorage.snapshotLoad(path); - loadSnapshotFromActualStorage(baseDirStorage); - } finally { - TimerContext.end(LOAD_SNAPSHOT, Loggers.RAFT); - } - } - - private void loadSnapshotFromActualStorage(KvStorage actualStorage) throws KvStorageException { - for (byte[] each : actualStorage.allKeys()) { - byte[] datum = actualStorage.get(each); - super.put(each, datum); - } - } - - @Override - public List allKeys() throws KvStorageException { - return super.allKeys(); - } - - @Override - public void shutdown() { - baseDirStorage.shutdown(); - super.shutdown(); - } - - private KvStorage getStorage() throws Exception { - return baseDirStorage; - } -} diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/OldDataOperation.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/OldDataOperation.java new file mode 100644 index 00000000000..8249ca42e1c --- /dev/null +++ b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/OldDataOperation.java @@ -0,0 +1,50 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.naming.consistency.persistent.impl; + +/** + * Adapter old version data operation {@link com.alibaba.nacos.naming.consistency.persistent.impl.BasePersistentServiceProcessor.Op}. + * + * @author xiweng.yy + */ +public enum OldDataOperation { + + /** + * write ops. + */ + Write("Write"), + + /** + * read ops. + */ + Read("Read"), + + /** + * delete ops. + */ + Delete("Delete"); + + private final String desc; + + OldDataOperation(String desc) { + this.desc = desc; + } + + public String getDesc() { + return desc; + } +} diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/PersistentServiceProcessor.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/PersistentServiceProcessor.java deleted file mode 100644 index f8768506ac8..00000000000 --- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/PersistentServiceProcessor.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.naming.consistency.persistent.impl; - -import com.alibaba.nacos.api.exception.NacosException; -import com.alibaba.nacos.common.notify.NotifyCenter; -import com.alibaba.nacos.common.utils.ByteUtils; -import com.alibaba.nacos.common.utils.StringUtils; -import com.alibaba.nacos.consistency.ProtocolMetaData; -import com.alibaba.nacos.consistency.cp.CPProtocol; -import com.alibaba.nacos.consistency.cp.MetadataKey; -import com.alibaba.nacos.consistency.entity.ReadRequest; -import com.alibaba.nacos.consistency.entity.Response; -import com.alibaba.nacos.consistency.entity.WriteRequest; -import com.alibaba.nacos.core.distributed.ProtocolManager; -import com.alibaba.nacos.core.exception.ErrorCode; -import com.alibaba.nacos.naming.consistency.Datum; -import com.alibaba.nacos.naming.consistency.RecordListener; -import com.alibaba.nacos.naming.constants.Constants; -import com.alibaba.nacos.naming.misc.Loggers; -import com.alibaba.nacos.naming.pojo.Record; -import com.alibaba.nacos.sys.env.EnvUtil; -import com.google.protobuf.ByteString; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; - -/** - * In cluster mode, start the Raft protocol. - * - * @author liaochuntao - */ -@SuppressWarnings("PMD.ServiceOrDaoClassShouldEndWithImplRule") -public class PersistentServiceProcessor extends BasePersistentServiceProcessor { - - private final CPProtocol protocol; - - /** - * Is there a leader node currently. - */ - private volatile boolean hasLeader = false; - - public PersistentServiceProcessor(ProtocolManager protocolManager) throws Exception { - this.protocol = protocolManager.getCpProtocol(); - } - - @Override - public void afterConstruct() { - super.afterConstruct(); - String raftGroup = Constants.NAMING_PERSISTENT_SERVICE_GROUP; - this.protocol.protocolMetaData().subscribe(raftGroup, MetadataKey.LEADER_META_DATA, o -> { - if (!(o instanceof ProtocolMetaData.ValueItem)) { - return; - } - Object leader = ((ProtocolMetaData.ValueItem) o).getData(); - hasLeader = StringUtils.isNotBlank(String.valueOf(leader)); - Loggers.RAFT.info("Raft group {} has leader {}", raftGroup, leader); - }); - this.protocol.addRequestProcessors(Collections.singletonList(this)); - // If you choose to use the new RAFT protocol directly, there will be no compatible logical execution - if (EnvUtil.getProperty(Constants.NACOS_NAMING_USE_NEW_RAFT_FIRST, Boolean.class, false)) { - NotifyCenter.registerSubscriber(notifier); - waitLeader(); - startNotify = true; - } - } - - private void waitLeader() { - while (!hasLeader && !hasError) { - Loggers.RAFT.info("Waiting Jraft leader vote ..."); - try { - TimeUnit.MILLISECONDS.sleep(500); - } catch (InterruptedException ignored) { - } - } - } - - @Override - public void put(String key, Record value) throws NacosException { - final BatchWriteRequest req = new BatchWriteRequest(); - Datum datum = Datum.createDatum(key, value); - req.append(ByteUtils.toBytes(key), serializer.serialize(datum)); - final WriteRequest request = WriteRequest.newBuilder().setData(ByteString.copyFrom(serializer.serialize(req))) - .setGroup(Constants.NAMING_PERSISTENT_SERVICE_GROUP).setOperation(Op.Write.desc).build(); - try { - protocol.write(request); - } catch (Exception e) { - throw new NacosException(ErrorCode.ProtoSubmitError.getCode(), e.getMessage()); - } - } - - @Override - public void remove(String key) throws NacosException { - final BatchWriteRequest req = new BatchWriteRequest(); - req.append(ByteUtils.toBytes(key), ByteUtils.EMPTY); - final WriteRequest request = WriteRequest.newBuilder().setData(ByteString.copyFrom(serializer.serialize(req))) - .setGroup(Constants.NAMING_PERSISTENT_SERVICE_GROUP).setOperation(Op.Delete.desc).build(); - try { - protocol.write(request); - } catch (Exception e) { - throw new NacosException(ErrorCode.ProtoSubmitError.getCode(), e.getMessage()); - } - } - - @Override - public Datum get(String key) throws NacosException { - final List keys = new ArrayList<>(1); - keys.add(ByteUtils.toBytes(key)); - final ReadRequest req = ReadRequest.newBuilder().setGroup(Constants.NAMING_PERSISTENT_SERVICE_GROUP) - .setData(ByteString.copyFrom(serializer.serialize(keys))).build(); - try { - Response resp = protocol.getData(req); - if (resp.getSuccess()) { - BatchReadResponse response = serializer - .deserialize(resp.getData().toByteArray(), BatchReadResponse.class); - final List rValues = response.getValues(); - return rValues.isEmpty() ? null : serializer.deserialize(rValues.get(0), getDatumTypeFromKey(key)); - } - throw new NacosException(ErrorCode.ProtoReadError.getCode(), resp.getErrMsg()); - } catch (Throwable e) { - throw new NacosException(ErrorCode.ProtoReadError.getCode(), e.getMessage()); - } - } - - @Override - public void listen(String key, RecordListener listener) throws NacosException { - notifier.registerListener(key, listener); - if (startNotify) { - notifierDatumIfAbsent(key, listener); - } - } - - @Override - public void unListen(String key, RecordListener listener) throws NacosException { - notifier.deregisterListener(key, listener); - } - - @Override - public boolean isAvailable() { - return hasLeader && !hasError; - } - - @Override - public Optional getErrorMsg() { - String errorMsg; - if (hasLeader && hasError) { - errorMsg = "The raft peer is in error: " + jRaftErrorMsg; - } else if (hasLeader && !hasError) { - errorMsg = null; - } else if (!hasLeader && hasError) { - errorMsg = "Could not find leader! And the raft peer is in error: " + jRaftErrorMsg; - } else { - errorMsg = "Could not find leader!"; - } - return Optional.ofNullable(errorMsg); - } -} diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/StandalonePersistentServiceProcessor.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/StandalonePersistentServiceProcessor.java deleted file mode 100644 index 47af6ea0b0f..00000000000 --- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/StandalonePersistentServiceProcessor.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.naming.consistency.persistent.impl; - -import com.alibaba.nacos.api.exception.NacosException; -import com.alibaba.nacos.common.utils.ByteUtils; -import com.alibaba.nacos.consistency.entity.ReadRequest; -import com.alibaba.nacos.consistency.entity.Response; -import com.alibaba.nacos.consistency.entity.WriteRequest; -import com.alibaba.nacos.core.exception.ErrorCode; -import com.alibaba.nacos.naming.consistency.Datum; -import com.alibaba.nacos.naming.consistency.RecordListener; -import com.alibaba.nacos.naming.constants.Constants; -import com.alibaba.nacos.naming.pojo.Record; -import com.google.protobuf.ByteString; - -import java.util.Collections; -import java.util.List; -import java.util.Optional; - -/** - * Persistent service manipulation layer in stand-alone mode. - * - * @author liaochuntao - */ -@SuppressWarnings("PMD.ServiceOrDaoClassShouldEndWithImplRule") -public class StandalonePersistentServiceProcessor extends BasePersistentServiceProcessor { - - public StandalonePersistentServiceProcessor() throws Exception { - } - - @Override - public void put(String key, Record value) throws NacosException { - final BatchWriteRequest req = new BatchWriteRequest(); - Datum datum = Datum.createDatum(key, value); - req.append(ByteUtils.toBytes(key), serializer.serialize(datum)); - final WriteRequest request = WriteRequest.newBuilder().setData(ByteString.copyFrom(serializer.serialize(req))) - .setGroup(Constants.NAMING_PERSISTENT_SERVICE_GROUP).setOperation(Op.Write.desc).build(); - try { - onApply(request); - } catch (Exception e) { - throw new NacosException(ErrorCode.ProtoSubmitError.getCode(), e.getMessage()); - } - } - - @Override - public void remove(String key) throws NacosException { - final BatchWriteRequest req = new BatchWriteRequest(); - req.append(ByteUtils.toBytes(key), ByteUtils.EMPTY); - final WriteRequest request = WriteRequest.newBuilder().setData(ByteString.copyFrom(serializer.serialize(req))) - .setGroup(Constants.NAMING_PERSISTENT_SERVICE_GROUP).setOperation(Op.Delete.desc).build(); - try { - onApply(request); - } catch (Exception e) { - throw new NacosException(ErrorCode.ProtoSubmitError.getCode(), e.getMessage()); - } - } - - @Override - public Datum get(String key) throws NacosException { - final List keys = Collections.singletonList(ByteUtils.toBytes(key)); - final ReadRequest req = ReadRequest.newBuilder().setGroup(Constants.NAMING_PERSISTENT_SERVICE_GROUP) - .setData(ByteString.copyFrom(serializer.serialize(keys))).build(); - try { - final Response resp = onRequest(req); - if (resp.getSuccess()) { - BatchReadResponse response = serializer - .deserialize(resp.getData().toByteArray(), BatchReadResponse.class); - final List rValues = response.getValues(); - return rValues.isEmpty() ? null : serializer.deserialize(rValues.get(0), getDatumTypeFromKey(key)); - } - throw new NacosException(ErrorCode.ProtoReadError.getCode(), resp.getErrMsg()); - } catch (Throwable e) { - throw new NacosException(ErrorCode.ProtoReadError.getCode(), e.getMessage()); - } - } - - @Override - public void listen(String key, RecordListener listener) throws NacosException { - notifier.registerListener(key, listener); - if (startNotify) { - notifierDatumIfAbsent(key, listener); - } - } - - @Override - public void unListen(String key, RecordListener listener) throws NacosException { - notifier.deregisterListener(key, listener); - } - - @Override - public boolean isAvailable() { - return !hasError; - } - - @Override - public Optional getErrorMsg() { - String errorMsg; - if (hasError) { - errorMsg = "The raft peer is in error: " + jRaftErrorMsg; - } else { - errorMsg = null; - } - return Optional.ofNullable(errorMsg); - } -} diff --git a/naming/src/main/java/com/alibaba/nacos/naming/controllers/InstanceController.java b/naming/src/main/java/com/alibaba/nacos/naming/controllers/InstanceController.java index 1f58e22d6ce..7e4a9e5dc9d 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/controllers/InstanceController.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/controllers/InstanceController.java @@ -51,6 +51,7 @@ import com.alibaba.nacos.naming.pojo.instance.BeatInfoInstanceBuilder; import com.alibaba.nacos.naming.pojo.instance.HttpRequestInstanceBuilder; import com.alibaba.nacos.naming.pojo.instance.InstanceExtensionHandler; +import com.alibaba.nacos.naming.utils.NamingRequestUtil; import com.alibaba.nacos.naming.web.CanDistro; import com.alibaba.nacos.plugin.auth.constant.ActionTypes; import com.fasterxml.jackson.core.type.TypeReference; @@ -120,7 +121,8 @@ public String register(HttpServletRequest request) throws Exception { .setDefaultInstanceEphemeral(switchDomain.isDefaultInstanceEphemeral()).setRequest(request).build(); getInstanceOperator().registerInstance(namespaceId, serviceName, instance); - NotifyCenter.publishEvent(new RegisterInstanceTraceEvent(System.currentTimeMillis(), "", false, namespaceId, + NotifyCenter.publishEvent(new RegisterInstanceTraceEvent(System.currentTimeMillis(), + NamingRequestUtil.getSourceIpForHttpRequest(request), false, namespaceId, NamingUtils.getGroupName(serviceName), NamingUtils.getServiceName(serviceName), instance.getIp(), instance.getPort())); return "ok"; @@ -145,9 +147,10 @@ public String deregister(HttpServletRequest request) throws Exception { NamingUtils.checkServiceNameFormat(serviceName); getInstanceOperator().removeInstance(namespaceId, serviceName, instance); - NotifyCenter.publishEvent(new DeregisterInstanceTraceEvent(System.currentTimeMillis(), "", false, - DeregisterInstanceReason.REQUEST, namespaceId, NamingUtils.getGroupName(serviceName), - NamingUtils.getServiceName(serviceName), instance.getIp(), instance.getPort())); + NotifyCenter.publishEvent(new DeregisterInstanceTraceEvent(System.currentTimeMillis(), + NamingRequestUtil.getSourceIpForHttpRequest(request), false, DeregisterInstanceReason.REQUEST, + namespaceId, NamingUtils.getGroupName(serviceName), NamingUtils.getServiceName(serviceName), + instance.getIp(), instance.getPort())); return "ok"; } @@ -169,7 +172,8 @@ public String update(HttpServletRequest request) throws Exception { Instance instance = HttpRequestInstanceBuilder.newBuilder() .setDefaultInstanceEphemeral(switchDomain.isDefaultInstanceEphemeral()).setRequest(request).build(); getInstanceOperator().updateInstance(namespaceId, serviceName, instance); - NotifyCenter.publishEvent(new UpdateInstanceTraceEvent(System.currentTimeMillis(), "", namespaceId, + NotifyCenter.publishEvent(new UpdateInstanceTraceEvent(System.currentTimeMillis(), + NamingRequestUtil.getSourceIpForHttpRequest(request), namespaceId, NamingUtils.getGroupName(serviceName), NamingUtils.getServiceName(serviceName), instance.getIp(), instance.getPort(), instance.getMetadata())); return "ok"; @@ -267,7 +271,6 @@ private List parseBatchInstances(String instances) { return Collections.emptyList(); } - /** * Patch instance. * diff --git a/naming/src/main/java/com/alibaba/nacos/naming/controllers/v2/InstanceControllerV2.java b/naming/src/main/java/com/alibaba/nacos/naming/controllers/v2/InstanceControllerV2.java index 4a444fde983..a57df409dee 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/controllers/v2/InstanceControllerV2.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/controllers/v2/InstanceControllerV2.java @@ -56,6 +56,7 @@ import com.alibaba.nacos.naming.pojo.InstanceOperationInfo; import com.alibaba.nacos.naming.pojo.Subscriber; import com.alibaba.nacos.naming.pojo.instance.BeatInfoInstanceBuilder; +import com.alibaba.nacos.naming.utils.NamingRequestUtil; import com.alibaba.nacos.naming.web.CanDistro; import com.alibaba.nacos.plugin.auth.constant.ActionTypes; import com.fasterxml.jackson.core.type.TypeReference; @@ -115,9 +116,9 @@ public Result register(InstanceForm instanceForm) throws NacosException instanceServiceV2.registerInstance(instanceForm.getNamespaceId(), buildCompositeServiceName(instanceForm), instance); NotifyCenter.publishEvent( - new RegisterInstanceTraceEvent(System.currentTimeMillis(), "", false, instanceForm.getNamespaceId(), - instanceForm.getGroupName(), instanceForm.getServiceName(), instance.getIp(), - instance.getPort())); + new RegisterInstanceTraceEvent(System.currentTimeMillis(), NamingRequestUtil.getSourceIp(), false, + instanceForm.getNamespaceId(), instanceForm.getGroupName(), instanceForm.getServiceName(), + instance.getIp(), instance.getPort())); return Result.success("ok"); } @@ -136,9 +137,10 @@ public Result deregister(InstanceForm instanceForm) throws NacosExceptio Instance instance = buildInstance(instanceForm); instanceServiceV2.removeInstance(instanceForm.getNamespaceId(), buildCompositeServiceName(instanceForm), instance); - NotifyCenter.publishEvent(new DeregisterInstanceTraceEvent(System.currentTimeMillis(), "", false, - DeregisterInstanceReason.REQUEST, instanceForm.getNamespaceId(), instanceForm.getGroupName(), - instanceForm.getServiceName(), instance.getIp(), instance.getPort())); + NotifyCenter.publishEvent( + new DeregisterInstanceTraceEvent(System.currentTimeMillis(), NamingRequestUtil.getSourceIp(), false, + DeregisterInstanceReason.REQUEST, instanceForm.getNamespaceId(), instanceForm.getGroupName(), + instanceForm.getServiceName(), instance.getIp(), instance.getPort())); return Result.success("ok"); } @@ -158,9 +160,9 @@ public Result update(InstanceForm instanceForm) throws NacosException { instanceServiceV2.updateInstance(instanceForm.getNamespaceId(), buildCompositeServiceName(instanceForm), instance); NotifyCenter.publishEvent( - new UpdateInstanceTraceEvent(System.currentTimeMillis(), "", instanceForm.getNamespaceId(), - instanceForm.getGroupName(), instanceForm.getServiceName(), instance.getIp(), - instance.getPort(), instance.getMetadata())); + new UpdateInstanceTraceEvent(System.currentTimeMillis(), NamingRequestUtil.getSourceIp(), + instanceForm.getNamespaceId(), instanceForm.getGroupName(), instanceForm.getServiceName(), + instance.getIp(), instance.getPort(), instance.getMetadata())); return Result.success("ok"); } @@ -231,7 +233,6 @@ private List parseBatchInstances(String instances) { return Collections.emptyList(); } - /** * Patch instance. * @@ -463,4 +464,5 @@ private String buildCompositeServiceName(InstanceForm instanceForm) { private String buildCompositeServiceName(InstanceMetadataBatchOperationForm form) { return NamingUtils.getGroupedName(form.getServiceName(), form.getGroupName()); } + } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/core/InstanceOperatorClientImpl.java b/naming/src/main/java/com/alibaba/nacos/naming/core/InstanceOperatorClientImpl.java index 1e632dc2217..fc5d9be4ac2 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/core/InstanceOperatorClientImpl.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/core/InstanceOperatorClientImpl.java @@ -130,8 +130,8 @@ public void updateInstance(String namespaceId, String serviceName, Instance inst throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.INSTANCE_ERROR, "service not found, namespace: " + namespaceId + ", service: " + service); } - String metadataId = InstancePublishInfo - .genMetadataId(instance.getIp(), instance.getPort(), instance.getClusterName()); + String metadataId = InstancePublishInfo.genMetadataId(instance.getIp(), instance.getPort(), + instance.getClusterName()); metadataOperateService.updateInstanceMetadata(service, metadataId, buildMetadata(instance)); } @@ -149,8 +149,8 @@ public void patchInstance(String namespaceId, String serviceName, InstancePatchO Service service = getService(namespaceId, serviceName, true); Instance instance = getInstance(namespaceId, serviceName, patchObject.getCluster(), patchObject.getIp(), patchObject.getPort()); - String metadataId = InstancePublishInfo - .genMetadataId(instance.getIp(), instance.getPort(), instance.getClusterName()); + String metadataId = InstancePublishInfo.genMetadataId(instance.getIp(), instance.getPort(), + instance.getClusterName()); Optional instanceMetadata = metadataManager.getInstanceMetadata(service, metadataId); InstanceMetadata newMetadata = instanceMetadata.map(this::cloneMetadata).orElseGet(InstanceMetadata::new); mergeMetadata(newMetadata, patchObject); @@ -189,8 +189,8 @@ public ServiceInfo listInstance(String namespaceId, String serviceName, Subscrib } ServiceInfo serviceInfo = serviceStorage.getData(service); ServiceMetadata serviceMetadata = metadataManager.getServiceMetadata(service).orElse(null); - ServiceInfo result = ServiceUtil - .selectInstancesWithHealthyProtection(serviceInfo, serviceMetadata, cluster, healthOnly, true, subscriber.getIp()); + ServiceInfo result = ServiceUtil.selectInstancesWithHealthyProtection(serviceInfo, serviceMetadata, cluster, + healthOnly, true, subscriber.getIp()); // adapt for v1.x sdk result.setName(NamingUtils.getGroupedName(result.getName(), result.getGroupName())); return result; @@ -329,12 +329,8 @@ private List findBatchUpdateInstance(InstanceOperationInfo instanceOpe private void createIpPortClientIfAbsent(String clientId) { if (!clientManager.contains(clientId)) { - ClientAttributes clientAttributes; - if (ClientAttributesFilter.threadLocalClientAttributes.get() != null) { - clientAttributes = ClientAttributesFilter.threadLocalClientAttributes.get(); - } else { - clientAttributes = new ClientAttributes(); - } + ClientAttributes clientAttributes = ClientAttributesFilter.getCurrentClientAttributes() + .orElse(new ClientAttributes()); clientManager.clientConnected(clientId, clientAttributes); } } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/core/v2/pojo/Service.java b/naming/src/main/java/com/alibaba/nacos/naming/core/v2/pojo/Service.java index 93971aff0cb..711edd80c67 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/core/v2/pojo/Service.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/core/v2/pojo/Service.java @@ -16,6 +16,7 @@ package com.alibaba.nacos.naming.core.v2.pojo; +import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.naming.utils.NamingUtils; import java.io.Serializable; @@ -95,6 +96,11 @@ public void incrementRevision() { public String getGroupedServiceName() { return NamingUtils.getGroupedName(name, group); } + + public String getNameSpaceGroupedServiceName() { + //do not String.intern + return namespace + Constants.SERVICE_INFO_SPLITER + NamingUtils.getGroupedName(name, group); + } @Override public boolean equals(Object o) { diff --git a/naming/src/main/java/com/alibaba/nacos/naming/exception/ResponseExceptionHandler.java b/naming/src/main/java/com/alibaba/nacos/naming/exception/ResponseExceptionHandler.java index fcb801a6fb8..53373a76d26 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/exception/ResponseExceptionHandler.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/exception/ResponseExceptionHandler.java @@ -42,10 +42,10 @@ public class ResponseExceptionHandler { */ @ExceptionHandler(NacosException.class) public ResponseEntity handleNacosException(NacosException e) { - Loggers.SRV_LOG.error("got exception. {}", e.getErrMsg(), ExceptionUtil.getAllExceptionMsg(e)); + Loggers.SRV_LOG.error("got exception. {}", ExceptionUtil.getAllExceptionMsg(e)); return ResponseEntity.status(e.getErrCode()).body(e.getMessage()); } - + /** * Handle {@link com.alibaba.nacos.api.exception.runtime.NacosRuntimeException}. * @@ -54,7 +54,7 @@ public ResponseEntity handleNacosException(NacosException e) { */ @ExceptionHandler(NacosRuntimeException.class) public ResponseEntity handleNacosRuntimeException(NacosRuntimeException e) { - Loggers.SRV_LOG.error("got exception. {}", e.getMessage(), ExceptionUtil.getAllExceptionMsg(e)); + Loggers.SRV_LOG.error("got exception. {}", ExceptionUtil.getAllExceptionMsg(e)); return ResponseEntity.status(e.getErrCode()).body(e.getMessage()); } @@ -66,7 +66,7 @@ public ResponseEntity handleNacosRuntimeException(NacosRuntimeException */ @ExceptionHandler(IllegalArgumentException.class) public ResponseEntity handleParameterError(IllegalArgumentException ex) { - Loggers.SRV_LOG.error("got exception. {}", ex.getMessage(), ExceptionUtil.getAllExceptionMsg(ex)); + Loggers.SRV_LOG.error("got exception. {}", ExceptionUtil.getAllExceptionMsg(ex)); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage()); } @@ -78,7 +78,7 @@ public ResponseEntity handleParameterError(IllegalArgumentException ex) */ @ExceptionHandler(MissingServletRequestParameterException.class) public ResponseEntity handleMissingParams(MissingServletRequestParameterException ex) { - Loggers.SRV_LOG.error("got exception.", ExceptionUtil.getAllExceptionMsg(ex)); + Loggers.SRV_LOG.error("got exception. {}", ExceptionUtil.getAllExceptionMsg(ex)); String name = ex.getParameterName(); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Parameter '" + name + "' is missing"); } @@ -91,7 +91,7 @@ public ResponseEntity handleMissingParams(MissingServletRequestParameter */ @ExceptionHandler(Exception.class) public ResponseEntity handleException(Exception e) { - Loggers.SRV_LOG.error("got exception.", ExceptionUtil.getAllExceptionMsg(e)); + Loggers.SRV_LOG.error("got exception. {}", ExceptionUtil.getAllExceptionMsg(e)); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ExceptionUtil.getAllExceptionMsg(e)); } } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/TcpHealthCheckProcessor.java b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/TcpHealthCheckProcessor.java index 36e39b08355..c9994cb3ee8 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/TcpHealthCheckProcessor.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/TcpHealthCheckProcessor.java @@ -102,7 +102,7 @@ public void process(HealthCheckTaskV2 task, Service service, ClusterMetadata met // TODO handle marked(white list) logic like v1.x. if (!instance.tryStartCheck()) { SRV_LOG.warn("[HEALTH-CHECK-V2] tcp check started before last one finished, service: {} : {} : {}:{}", - service.getGroupedServiceName(), instance.getCluster(), instance.getIp(), instance.getPort()); + service.getNameSpaceGroupedServiceName(), instance.getCluster(), instance.getIp(), instance.getPort()); healthCheckCommon .reEvaluateCheckRT(task.getCheckRtNormalized() * 2, task, switchDomain.getTcpHealthParams()); return; @@ -287,7 +287,7 @@ public void finishCheck(boolean success, boolean now, long rt, String msg) { @Override public String toString() { - return service.getGroupedServiceName() + ":" + instance.getCluster() + ":" + instance.getIp() + ":" + return service.getNameSpaceGroupedServiceName() + ":" + instance.getCluster() + ":" + instance.getIp() + ":" + instance.getPort(); } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/NamingSnapshotOperation.java b/naming/src/main/java/com/alibaba/nacos/naming/misc/SwitchDomainSnapshotOperation.java similarity index 51% rename from naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/NamingSnapshotOperation.java rename to naming/src/main/java/com/alibaba/nacos/naming/misc/SwitchDomainSnapshotOperation.java index eb812b90c16..10d704ec39c 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/NamingSnapshotOperation.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/misc/SwitchDomainSnapshotOperation.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2018 Alibaba Group Holding Ltd. + * Copyright 1999-2023 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,56 +14,40 @@ * limitations under the License. */ -package com.alibaba.nacos.naming.consistency.persistent.impl; +package com.alibaba.nacos.naming.misc; -import com.alibaba.nacos.common.notify.NotifyCenter; -import com.alibaba.nacos.common.utils.TypeUtils; -import com.alibaba.nacos.consistency.DataOperation; import com.alibaba.nacos.consistency.Serializer; import com.alibaba.nacos.consistency.snapshot.LocalFileMeta; import com.alibaba.nacos.consistency.snapshot.Reader; import com.alibaba.nacos.consistency.snapshot.Writer; -import com.alibaba.nacos.core.exception.KvStorageException; -import com.alibaba.nacos.core.storage.kv.KvStorage; -import com.alibaba.nacos.naming.consistency.Datum; -import com.alibaba.nacos.naming.consistency.KeyBuilder; -import com.alibaba.nacos.naming.consistency.ValueChangeEvent; -import com.alibaba.nacos.naming.misc.Loggers; -import com.alibaba.nacos.naming.misc.SwitchDomain; -import com.alibaba.nacos.naming.pojo.Record; +import com.alibaba.nacos.naming.consistency.persistent.impl.AbstractSnapshotOperation; import com.alibaba.nacos.sys.utils.DiskUtils; import com.alipay.sofa.jraft.util.CRC64; -import java.lang.reflect.Type; import java.nio.file.Paths; -import java.util.List; import java.util.Objects; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.zip.Checksum; /** - * Snapshot processing of persistent service data for accelerated Raft protocol recovery and data synchronization. + * Switch Domain snapshot operation. * - * @author liaochuntao * @author xiweng.yy */ -public class NamingSnapshotOperation extends AbstractSnapshotOperation { - - private static final String NAMING_SNAPSHOT_SAVE = NamingSnapshotOperation.class.getSimpleName() + ".SAVE"; - - private static final String NAMING_SNAPSHOT_LOAD = NamingSnapshotOperation.class.getSimpleName() + ".LOAD"; +public class SwitchDomainSnapshotOperation extends AbstractSnapshotOperation { private final String snapshotDir = "naming_persistent"; private final String snapshotArchive = "naming_persistent.zip"; - private final KvStorage storage; - + private final SwitchManager switchManager; + private final Serializer serializer; - public NamingSnapshotOperation(KvStorage storage, ReentrantReadWriteLock lock, Serializer serializer) { + public SwitchDomainSnapshotOperation(ReentrantReadWriteLock lock, SwitchManager switchManager, + Serializer serializer) { super(lock); - this.storage = storage; + this.switchManager = switchManager; this.serializer = serializer; } @@ -74,7 +58,7 @@ protected boolean writeSnapshot(Writer writer) throws Exception { DiskUtils.deleteDirectory(parentPath); DiskUtils.forceMkdir(parentPath); - storage.doSnapshot(parentPath); + this.switchManager.dumpSnapshot(parentPath); final String outputFile = Paths.get(writePath, snapshotArchive).toString(); final Checksum checksum = new CRC64(); DiskUtils.compress(writePath, snapshotDir, outputFile, checksum); @@ -98,56 +82,19 @@ protected boolean readSnapshot(Reader reader) throws Exception { } } final String loadPath = Paths.get(readerPath, snapshotDir).toString(); - storage.snapshotLoad(loadPath); - // publish value change - publishValueChangeEvent(); Loggers.RAFT.info("snapshot load from : {}", loadPath); + this.switchManager.loadSnapshot(loadPath); DiskUtils.deleteDirectory(loadPath); return true; } - - /** - * publish value change event. - * - * @throws KvStorageException throw to invoker - */ - private void publishValueChangeEvent() throws KvStorageException { - List keys = storage.allKeys(); - for (int i = 0; i < keys.size(); i++) { - String key = new String(keys.get(i)); - // Ignore old 1.x version data - if (!KeyBuilder.matchSwitchKey(key)) { - continue; - } - Datum datum = serializer.deserialize(storage.get(keys.get(i)), getDatumTypeFromKey(key)); - Record value = (datum != null) ? datum.value : null; - // report for refreshing SwitchDomain message - if (value != null) { - ValueChangeEvent event = ValueChangeEvent.builder().key(key).value(value) - .action(DataOperation.CHANGE).build(); - NotifyCenter.publishEvent(event); - } - } - } - - private Type getDatumTypeFromKey(String key) { - return TypeUtils.parameterize(Datum.class, getClassOfRecordFromKey(key)); - } - - private Class getClassOfRecordFromKey(String key) { - if (KeyBuilder.matchSwitchKey(key)) { - return SwitchDomain.class; - } - return Record.class; - } @Override protected String getSnapshotSaveTag() { - return NAMING_SNAPSHOT_SAVE; + return SwitchDomainSnapshotOperation.class.getSimpleName() + ".SAVE"; } @Override protected String getSnapshotLoadTag() { - return NAMING_SNAPSHOT_LOAD; + return SwitchDomainSnapshotOperation.class.getSimpleName() + ".LOAD"; } } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/misc/SwitchManager.java b/naming/src/main/java/com/alibaba/nacos/naming/misc/SwitchManager.java index ce50b721121..080bcaa2a4e 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/misc/SwitchManager.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/misc/SwitchManager.java @@ -18,23 +18,43 @@ import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.exception.NacosException; +import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; +import com.alibaba.nacos.common.utils.ByteUtils; import com.alibaba.nacos.common.utils.ConvertUtils; import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.common.utils.StringUtils; -import com.alibaba.nacos.naming.consistency.ConsistencyService; +import com.alibaba.nacos.common.utils.TypeUtils; +import com.alibaba.nacos.consistency.SerializeFactory; +import com.alibaba.nacos.consistency.Serializer; +import com.alibaba.nacos.consistency.cp.RequestProcessor4CP; +import com.alibaba.nacos.consistency.entity.ReadRequest; +import com.alibaba.nacos.consistency.entity.Response; +import com.alibaba.nacos.consistency.entity.WriteRequest; +import com.alibaba.nacos.consistency.snapshot.SnapshotOperation; +import com.alibaba.nacos.core.distributed.ProtocolManager; +import com.alibaba.nacos.core.exception.ErrorCode; import com.alibaba.nacos.naming.consistency.Datum; import com.alibaba.nacos.naming.consistency.KeyBuilder; -import com.alibaba.nacos.naming.consistency.RecordListener; -import org.springframework.beans.factory.annotation.Autowired; +import com.alibaba.nacos.naming.consistency.persistent.impl.BatchReadResponse; +import com.alibaba.nacos.naming.consistency.persistent.impl.BatchWriteRequest; +import com.alibaba.nacos.naming.consistency.persistent.impl.OldDataOperation; +import com.alibaba.nacos.naming.pojo.Record; +import com.alibaba.nacos.sys.utils.DiskUtils; +import com.google.protobuf.ByteString; +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; -import javax.annotation.Resource; +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Type; +import java.nio.file.Paths; import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.locks.ReentrantLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; /** * Switch manager. @@ -43,27 +63,36 @@ * @since 1.0.0 */ @Component -public class SwitchManager implements RecordListener { +public class SwitchManager extends RequestProcessor4CP { - @Autowired - private SwitchDomain switchDomain; + private final SwitchDomain switchDomain; - @Resource(name = "persistentConsistencyServiceDelegate") - private ConsistencyService consistencyService; + private final ProtocolManager protocolManager; - ReentrantLock lock = new ReentrantLock(); + private final ReentrantReadWriteLock raftLock; - /** - * Init switch manager. - */ - @PostConstruct - public void init() { - + private final ReentrantLock requestLock; + + private final Serializer serializer; + + private final SwitchDomainSnapshotOperation snapshotOperation; + + private final File dataFile; + + public SwitchManager(SwitchDomain switchDomain, ProtocolManager protocolManager) { + this.switchDomain = switchDomain; + this.protocolManager = protocolManager; + this.raftLock = new ReentrantReadWriteLock(); + this.requestLock = new ReentrantLock(); + this.serializer = SerializeFactory.getSerializer("JSON"); + this.snapshotOperation = new SwitchDomainSnapshotOperation(this.raftLock, this, this.serializer); + this.dataFile = Paths.get(UtilsAndCommons.DATA_BASE_DIR, "data", KeyBuilder.getSwitchDomainKey()).toFile(); try { - consistencyService.listen(KeyBuilder.getSwitchDomainKey(), this); - } catch (NacosException e) { - Loggers.SRV_LOG.error("listen switch service failed.", e); + DiskUtils.forceMkdir(this.dataFile.getParent()); + } catch (IOException e) { + Loggers.RAFT.error("Init Switch Domain directory failed: ", e); } + protocolManager.getCpProtocol().addRequestProcessors(Collections.singletonList(this)); } /** @@ -76,22 +105,15 @@ public void init() { */ public void update(String entry, String value, boolean debug) throws Exception { - lock.lock(); + this.requestLock.lock(); try { - Datum datum = consistencyService.get(KeyBuilder.getSwitchDomainKey()); - SwitchDomain switchDomain; - - if (datum != null && datum.value != null) { - switchDomain = (SwitchDomain) datum.value; - } else { - switchDomain = this.switchDomain.clone(); - } + SwitchDomain tempSwitchDomain = this.switchDomain.clone(); if (SwitchEntry.BATCH.equals(entry)) { //batch update SwitchDomain dom = JacksonUtils.toObj(value, SwitchDomain.class); - dom.setEnableStandalone(switchDomain.isEnableStandalone()); + dom.setEnableStandalone(tempSwitchDomain.isEnableStandalone()); if (dom.getHttpHealthParams().getMin() < SwitchDomain.HttpHealthParams.MIN_MIN || dom.getTcpHealthParams().getMin() < SwitchDomain.HttpHealthParams.MIN_MIN) { @@ -110,7 +132,7 @@ public void update(String entry, String value, boolean debug) throws Exception { throw new IllegalArgumentException("malformed factor"); } - switchDomain = dom; + tempSwitchDomain = dom; } if (entry.equals(SwitchEntry.DISTRO_THRESHOLD)) { @@ -118,12 +140,12 @@ public void update(String entry, String value, boolean debug) throws Exception { if (threshold <= 0) { throw new IllegalArgumentException("distroThreshold can not be zero or negative: " + threshold); } - switchDomain.setDistroThreshold(threshold); + tempSwitchDomain.setDistroThreshold(threshold); } if (entry.equals(SwitchEntry.CLIENT_BEAT_INTERVAL)) { long clientBeatInterval = Long.parseLong(value); - switchDomain.setClientBeatInterval(clientBeatInterval); + tempSwitchDomain.setClientBeatInterval(clientBeatInterval); } if (entry.equals(SwitchEntry.PUSH_VERSION)) { @@ -137,13 +159,13 @@ public void update(String entry, String value, boolean debug) throws Exception { } if (StringUtils.equals(SwitchEntry.CLIENT_JAVA, type)) { - switchDomain.setPushJavaVersion(version); + tempSwitchDomain.setPushJavaVersion(version); } else if (StringUtils.equals(SwitchEntry.CLIENT_PYTHON, type)) { - switchDomain.setPushPythonVersion(version); + tempSwitchDomain.setPushPythonVersion(version); } else if (StringUtils.equals(SwitchEntry.CLIENT_C, type)) { - switchDomain.setPushCVersion(version); + tempSwitchDomain.setPushCVersion(version); } else if (StringUtils.equals(SwitchEntry.CLIENT_GO, type)) { - switchDomain.setPushGoVersion(version); + tempSwitchDomain.setPushGoVersion(version); } else { throw new IllegalArgumentException("unsupported client type: " + type); } @@ -156,7 +178,7 @@ public void update(String entry, String value, boolean debug) throws Exception { throw new IllegalArgumentException("min cache time for http or tcp is too small(<10000)"); } - switchDomain.setDefaultPushCacheMillis(cacheMillis); + tempSwitchDomain.setDefaultPushCacheMillis(cacheMillis); } // extremely careful while modifying this, cause it will affect all clients without pushing enabled @@ -167,27 +189,27 @@ public void update(String entry, String value, boolean debug) throws Exception { throw new IllegalArgumentException("min default cache time is too small(<1000)"); } - switchDomain.setDefaultCacheMillis(cacheMillis); + tempSwitchDomain.setDefaultCacheMillis(cacheMillis); } if (entry.equals(SwitchEntry.MASTERS)) { List masters = Arrays.asList(value.split(",")); - switchDomain.setMasters(masters); + tempSwitchDomain.setMasters(masters); } if (entry.equals(SwitchEntry.DISTRO)) { boolean enabled = Boolean.parseBoolean(value); - switchDomain.setDistroEnabled(enabled); + tempSwitchDomain.setDistroEnabled(enabled); } if (entry.equals(SwitchEntry.CHECK)) { boolean enabled = Boolean.parseBoolean(value); - switchDomain.setHealthCheckEnabled(enabled); + tempSwitchDomain.setHealthCheckEnabled(enabled); } if (entry.equals(SwitchEntry.PUSH_ENABLED)) { boolean enabled = Boolean.parseBoolean(value); - switchDomain.setPushEnabled(enabled); + tempSwitchDomain.setPushEnabled(enabled); } if (entry.equals(SwitchEntry.SERVICE_STATUS_SYNC_PERIOD)) { @@ -197,7 +219,7 @@ public void update(String entry, String value, boolean debug) throws Exception { throw new IllegalArgumentException("serviceStatusSynchronizationPeriodMillis is too small(<5000)"); } - switchDomain.setServiceStatusSynchronizationPeriodMillis(millis); + tempSwitchDomain.setServiceStatusSynchronizationPeriodMillis(millis); } if (entry.equals(SwitchEntry.SERVER_STATUS_SYNC_PERIOD)) { @@ -207,25 +229,25 @@ public void update(String entry, String value, boolean debug) throws Exception { throw new IllegalArgumentException("serverStatusSynchronizationPeriodMillis is too small(<15000)"); } - switchDomain.setServerStatusSynchronizationPeriodMillis(millis); + tempSwitchDomain.setServerStatusSynchronizationPeriodMillis(millis); } if (entry.equals(SwitchEntry.HEALTH_CHECK_TIMES)) { int times = Integer.parseInt(value); - switchDomain.setCheckTimes(times); + tempSwitchDomain.setCheckTimes(times); } if (entry.equals(SwitchEntry.DISABLE_ADD_IP)) { boolean disableAddIp = Boolean.parseBoolean(value); - switchDomain.setDisableAddIP(disableAddIp); + tempSwitchDomain.setDisableAddIP(disableAddIp); } if (entry.equals(SwitchEntry.SEND_BEAT_ONLY)) { boolean sendBeatOnly = Boolean.parseBoolean(value); - switchDomain.setSendBeatOnly(sendBeatOnly); + tempSwitchDomain.setSendBeatOnly(sendBeatOnly); } if (entry.equals(SwitchEntry.LIMITED_URL_MAP)) { @@ -253,14 +275,14 @@ public void update(String entry, String value, boolean debug) throws Exception { } - switchDomain.setLimitedUrlMap(limitedUrlMap); + tempSwitchDomain.setLimitedUrlMap(limitedUrlMap); } } if (entry.equals(SwitchEntry.ENABLE_STANDALONE)) { if (!StringUtils.isNotEmpty(value)) { - switchDomain.setEnableStandalone(Boolean.parseBoolean(value)); + tempSwitchDomain.setEnableStandalone(Boolean.parseBoolean(value)); } } @@ -269,33 +291,33 @@ public void update(String entry, String value, boolean debug) throws Exception { if (Constants.NULL_STRING.equals(status)) { status = StringUtils.EMPTY; } - switchDomain.setOverriddenServerStatus(status); + tempSwitchDomain.setOverriddenServerStatus(status); } if (entry.equals(SwitchEntry.DEFAULT_INSTANCE_EPHEMERAL)) { - switchDomain.setDefaultInstanceEphemeral(Boolean.parseBoolean(value)); + tempSwitchDomain.setDefaultInstanceEphemeral(Boolean.parseBoolean(value)); } if (entry.equals(SwitchEntry.DISTRO_SERVER_EXPIRED_MILLIS)) { - switchDomain.setDistroServerExpiredMillis(Long.parseLong(value)); + tempSwitchDomain.setDistroServerExpiredMillis(Long.parseLong(value)); } if (entry.equals(SwitchEntry.LIGHT_BEAT_ENABLED)) { - switchDomain.setLightBeatEnabled(ConvertUtils.toBoolean(value)); + tempSwitchDomain.setLightBeatEnabled(ConvertUtils.toBoolean(value)); } if (entry.equals(SwitchEntry.AUTO_CHANGE_HEALTH_CHECK_ENABLED)) { - switchDomain.setAutoChangeHealthCheckEnabled(ConvertUtils.toBoolean(value)); + tempSwitchDomain.setAutoChangeHealthCheckEnabled(ConvertUtils.toBoolean(value)); } if (debug) { - update(switchDomain); + update(tempSwitchDomain); } else { - consistencyService.put(KeyBuilder.getSwitchDomainKey(), switchDomain); + updateWithConsistency(tempSwitchDomain); } } finally { - lock.unlock(); + this.requestLock.unlock(); } } @@ -340,27 +362,145 @@ public void update(SwitchDomain newSwitchDomain) { switchDomain.setLightBeatEnabled(newSwitchDomain.isLightBeatEnabled()); } + private void updateWithConsistency(SwitchDomain tempSwitchDomain) throws NacosException { + try { + final BatchWriteRequest req = new BatchWriteRequest(); + String switchDomainKey = KeyBuilder.getSwitchDomainKey(); + Datum datum = Datum.createDatum(switchDomainKey, tempSwitchDomain); + req.append(ByteUtils.toBytes(switchDomainKey), serializer.serialize(datum)); + WriteRequest operationLog = WriteRequest.newBuilder().setGroup(group()) + .setOperation(OldDataOperation.Write.getDesc()).setData(ByteString.copyFrom(serializer.serialize(req))) + .build(); + protocolManager.getCpProtocol().write(operationLog); + } catch (Exception e) { + Loggers.RAFT.error("Submit switch domain failed: ", e); + throw new NacosException(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage()); + } + } + public SwitchDomain getSwitchDomain() { return switchDomain; } @Override - public boolean interests(String key) { - return KeyBuilder.matchSwitchKey(key); + public List loadSnapshotOperate() { + return Collections.singletonList(snapshotOperation); + } + + /** + * Load Snapshot from snapshot dir. + * + * @param snapshotPath snapshot dir + */ + public void loadSnapshot(String snapshotPath) { + this.raftLock.writeLock().lock(); + try { + File srcDir = Paths.get(snapshotPath).toFile(); + // If snapshot path is non-exist, means snapshot is empty + if (srcDir.exists()) { + // First clean up the local file information, before the file copy + String baseDir = this.dataFile.getParent(); + DiskUtils.deleteDirThenMkdir(baseDir); + File descDir = Paths.get(baseDir).toFile(); + DiskUtils.copyDirectory(srcDir, descDir); + if (!this.dataFile.exists()) { + return; + } + byte[] snapshotData = DiskUtils.readFileBytes(this.dataFile); + final Datum datum = serializer.deserialize(snapshotData, getDatumType()); + final Record value = null != datum ? datum.value : null; + if (!(value instanceof SwitchDomain)) { + return; + } + update((SwitchDomain) value); + } + } catch (IOException e) { + throw new NacosRuntimeException(ErrorCode.IOCopyDirError.getCode(), e); + } finally { + this.raftLock.writeLock().unlock(); + } + } + + /** + * Dump data from data dir to snapshot dir. + * + * @param backupPath snapshot dir + */ + public void dumpSnapshot(String backupPath) { + this.raftLock.writeLock().lock(); + try { + File srcDir = Paths.get(this.dataFile.getParent()).toFile(); + File descDir = Paths.get(backupPath).toFile(); + DiskUtils.copyDirectory(srcDir, descDir); + } catch (IOException e) { + throw new NacosRuntimeException(ErrorCode.IOCopyDirError.getCode(), e); + } finally { + this.raftLock.writeLock().unlock(); + } } @Override - public boolean matchUnlistenKey(String key) { - return KeyBuilder.matchSwitchKey(key); + public Response onRequest(ReadRequest request) { + this.raftLock.readLock().lock(); + try { + final List keys = serializer.deserialize(request.getData().toByteArray(), + TypeUtils.parameterize(List.class, byte[].class)); + if (isNotSwitchDomainKey(keys)) { + return Response.newBuilder().setSuccess(false).setErrMsg("not switch domain key").build(); + } + Datum datum = Datum.createDatum(KeyBuilder.getSwitchDomainKey(), switchDomain); + final BatchReadResponse response = new BatchReadResponse(); + response.append(ByteUtils.toBytes(KeyBuilder.getSwitchDomainKey()), serializer.serialize(datum)); + return Response.newBuilder().setSuccess(true).setData(ByteString.copyFrom(serializer.serialize(response))) + .build(); + } catch (Exception e) { + Loggers.RAFT.warn("On read switch domain failed, ", e); + return Response.newBuilder().setSuccess(false).setErrMsg(e.getMessage()).build(); + } finally { + this.raftLock.readLock().unlock(); + } } @Override - public void onChange(String key, SwitchDomain domain) throws Exception { - update(domain); + public Response onApply(WriteRequest log) { + this.raftLock.writeLock().lock(); + try { + BatchWriteRequest bwRequest = serializer.deserialize(log.getData().toByteArray(), BatchWriteRequest.class); + if (isNotSwitchDomainKey(bwRequest.getKeys())) { + return Response.newBuilder().setSuccess(false).setErrMsg("not switch domain key").build(); + } + final Datum datum = serializer.deserialize(bwRequest.getValues().get(0), getDatumType()); + final Record value = null != datum ? datum.value : null; + if (!(value instanceof SwitchDomain)) { + return Response.newBuilder().setSuccess(false).setErrMsg("datum is not switch domain").build(); + } + DiskUtils.touch(dataFile); + DiskUtils.writeFile(dataFile, bwRequest.getValues().get(0), false); + SwitchDomain switchDomain = (SwitchDomain) value; + update(switchDomain); + return Response.newBuilder().setSuccess(true).build(); + } catch (Exception e) { + Loggers.RAFT.warn("On apply switch domain failed, ", e); + return Response.newBuilder().setSuccess(false).setErrMsg(e.getMessage()).build(); + } finally { + this.raftLock.writeLock().unlock(); + } } @Override - public void onDelete(String key) throws Exception { + public String group() { + return com.alibaba.nacos.naming.constants.Constants.NAMING_PERSISTENT_SERVICE_GROUP; + } + + private boolean isNotSwitchDomainKey(List keys) { + if (1 != keys.size()) { + return false; + } + String keyString = new String(keys.get(0)); + return !KeyBuilder.getSwitchDomainKey().equals(keyString); + } + private Type getDatumType() { + return TypeUtils.parameterize(Datum.class, SwitchDomain.class); } } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/remote/rpc/handler/InstanceRequestHandler.java b/naming/src/main/java/com/alibaba/nacos/naming/remote/rpc/handler/InstanceRequestHandler.java index 208e5a3a611..6e00188ef94 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/remote/rpc/handler/InstanceRequestHandler.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/remote/rpc/handler/InstanceRequestHandler.java @@ -33,6 +33,7 @@ import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.naming.core.v2.service.impl.EphemeralClientOperationServiceImpl; import com.alibaba.nacos.naming.utils.InstanceUtil; +import com.alibaba.nacos.naming.utils.NamingRequestUtil; import com.alibaba.nacos.plugin.auth.constant.ActionTypes; import org.springframework.stereotype.Component; @@ -55,8 +56,8 @@ public InstanceRequestHandler(EphemeralClientOperationServiceImpl clientOperatio @Secured(action = ActionTypes.WRITE) @ExtractorManager.Extractor(rpcExtractor = InstanceRequestParamExtractor.class) public InstanceResponse handle(InstanceRequest request, RequestMeta meta) throws NacosException { - Service service = Service - .newService(request.getNamespace(), request.getGroupName(), request.getServiceName(), true); + Service service = Service.newService(request.getNamespace(), request.getGroupName(), request.getServiceName(), + true); InstanceUtil.setInstanceIdIfEmpty(request.getInstance(), service.getGroupedServiceName()); switch (request.getType()) { case NamingRemoteConstants.REGISTER_INSTANCE: @@ -73,16 +74,17 @@ private InstanceResponse registerInstance(Service service, InstanceRequest reque throws NacosException { clientOperationService.registerInstance(service, request.getInstance(), meta.getConnectionId()); NotifyCenter.publishEvent(new RegisterInstanceTraceEvent(System.currentTimeMillis(), - meta.getClientIp(), true, service.getNamespace(), service.getGroup(), service.getName(), - request.getInstance().getIp(), request.getInstance().getPort())); + NamingRequestUtil.getSourceIpForGrpcRequest(meta), true, service.getNamespace(), service.getGroup(), + service.getName(), request.getInstance().getIp(), request.getInstance().getPort())); return new InstanceResponse(NamingRemoteConstants.REGISTER_INSTANCE); } private InstanceResponse deregisterInstance(Service service, InstanceRequest request, RequestMeta meta) { clientOperationService.deregisterInstance(service, request.getInstance(), meta.getConnectionId()); NotifyCenter.publishEvent(new DeregisterInstanceTraceEvent(System.currentTimeMillis(), - meta.getClientIp(), true, DeregisterInstanceReason.REQUEST, service.getNamespace(), - service.getGroup(), service.getName(), request.getInstance().getIp(), request.getInstance().getPort())); + NamingRequestUtil.getSourceIpForGrpcRequest(meta), true, DeregisterInstanceReason.REQUEST, + service.getNamespace(), service.getGroup(), service.getName(), request.getInstance().getIp(), + request.getInstance().getPort())); return new InstanceResponse(NamingRemoteConstants.DE_REGISTER_INSTANCE); } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/remote/rpc/handler/PersistentInstanceRequestHandler.java b/naming/src/main/java/com/alibaba/nacos/naming/remote/rpc/handler/PersistentInstanceRequestHandler.java index 3d862219afd..9fac1f5ddcc 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/remote/rpc/handler/PersistentInstanceRequestHandler.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/remote/rpc/handler/PersistentInstanceRequestHandler.java @@ -35,6 +35,7 @@ import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.naming.core.v2.service.impl.PersistentClientOperationServiceImpl; import com.alibaba.nacos.naming.utils.InstanceUtil; +import com.alibaba.nacos.naming.utils.NamingRequestUtil; import com.alibaba.nacos.plugin.auth.constant.ActionTypes; import org.springframework.stereotype.Component; @@ -45,13 +46,13 @@ */ @Component public class PersistentInstanceRequestHandler extends RequestHandler { - + private final PersistentClientOperationServiceImpl clientOperationService; - + public PersistentInstanceRequestHandler(PersistentClientOperationServiceImpl clientOperationService) { this.clientOperationService = clientOperationService; } - + @Override @TpsControl(pointName = "RemoteNamingInstanceRegisterDeregister", name = "RemoteNamingInstanceRegisterDeregister") @Secured(action = ActionTypes.WRITE) @@ -75,8 +76,9 @@ private InstanceResponse registerInstance(Service service, PersistentInstanceReq Instance instance = request.getInstance(); String clientId = IpPortBasedClient.getClientId(instance.toInetAddr(), false); clientOperationService.registerInstance(service, instance, clientId); - NotifyCenter.publishEvent(new RegisterInstanceTraceEvent(System.currentTimeMillis(), meta.getClientIp(), true, - service.getNamespace(), service.getGroup(), service.getName(), instance.getIp(), instance.getPort())); + NotifyCenter.publishEvent(new RegisterInstanceTraceEvent(System.currentTimeMillis(), + NamingRequestUtil.getSourceIpForGrpcRequest(meta), true, service.getNamespace(), service.getGroup(), + service.getName(), instance.getIp(), instance.getPort())); return new InstanceResponse(NamingRemoteConstants.REGISTER_INSTANCE); } @@ -84,9 +86,9 @@ private InstanceResponse deregisterInstance(Service service, PersistentInstanceR Instance instance = request.getInstance(); String clientId = IpPortBasedClient.getClientId(instance.toInetAddr(), false); clientOperationService.deregisterInstance(service, instance, clientId); - NotifyCenter.publishEvent(new DeregisterInstanceTraceEvent(System.currentTimeMillis(), meta.getClientIp(), true, - DeregisterInstanceReason.REQUEST, service.getNamespace(), service.getGroup(), service.getName(), - instance.getIp(), instance.getPort())); + NotifyCenter.publishEvent(new DeregisterInstanceTraceEvent(System.currentTimeMillis(), + NamingRequestUtil.getSourceIpForGrpcRequest(meta), true, DeregisterInstanceReason.REQUEST, + service.getNamespace(), service.getGroup(), service.getName(), instance.getIp(), instance.getPort())); return new InstanceResponse(NamingRemoteConstants.DE_REGISTER_INSTANCE); } } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/remote/rpc/handler/ServiceQueryRequestHandler.java b/naming/src/main/java/com/alibaba/nacos/naming/remote/rpc/handler/ServiceQueryRequestHandler.java index aece0393d34..8b1df3c8d80 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/remote/rpc/handler/ServiceQueryRequestHandler.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/remote/rpc/handler/ServiceQueryRequestHandler.java @@ -30,6 +30,7 @@ import com.alibaba.nacos.naming.core.v2.metadata.NamingMetadataManager; import com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata; import com.alibaba.nacos.naming.core.v2.pojo.Service; +import com.alibaba.nacos.naming.utils.NamingRequestUtil; import com.alibaba.nacos.naming.utils.ServiceUtil; import com.alibaba.nacos.plugin.auth.constant.ActionTypes; import org.springframework.stereotype.Component; @@ -65,7 +66,7 @@ public QueryServiceResponse handle(ServiceQueryRequest request, RequestMeta meta ServiceInfo result = serviceStorage.getData(service); ServiceMetadata serviceMetadata = metadataManager.getServiceMetadata(service).orElse(null); result = ServiceUtil.selectInstancesWithHealthyProtection(result, serviceMetadata, cluster, healthyOnly, true, - meta.getClientIp()); + NamingRequestUtil.getSourceIpForGrpcRequest(meta)); return QueryServiceResponse.buildSuccessResponse(result); } } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/remote/rpc/handler/SubscribeServiceRequestHandler.java b/naming/src/main/java/com/alibaba/nacos/naming/remote/rpc/handler/SubscribeServiceRequestHandler.java index f4822140598..bd90a895c28 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/remote/rpc/handler/SubscribeServiceRequestHandler.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/remote/rpc/handler/SubscribeServiceRequestHandler.java @@ -27,6 +27,7 @@ import com.alibaba.nacos.common.notify.NotifyCenter; import com.alibaba.nacos.common.trace.event.naming.SubscribeServiceTraceEvent; import com.alibaba.nacos.common.trace.event.naming.UnsubscribeServiceTraceEvent; +import com.alibaba.nacos.core.context.RequestContextHolder; import com.alibaba.nacos.core.control.TpsControl; import com.alibaba.nacos.core.paramcheck.ExtractorManager; import com.alibaba.nacos.core.paramcheck.impl.SubscribeServiceRequestParamExtractor; @@ -36,6 +37,7 @@ import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.naming.core.v2.service.impl.EphemeralClientOperationServiceImpl; import com.alibaba.nacos.naming.pojo.Subscriber; +import com.alibaba.nacos.naming.utils.NamingRequestUtil; import com.alibaba.nacos.naming.utils.ServiceUtil; import com.alibaba.nacos.plugin.auth.constant.ActionTypes; import org.springframework.stereotype.Component; @@ -70,22 +72,24 @@ public SubscribeServiceResponse handle(SubscribeServiceRequest request, RequestM String namespaceId = request.getNamespace(); String serviceName = request.getServiceName(); String groupName = request.getGroupName(); - String app = request.getHeader("app", "unknown"); + String app = RequestContextHolder.getContext().getBasicContext().getApp(); String groupedServiceName = NamingUtils.getGroupedName(serviceName, groupName); Service service = Service.newService(namespaceId, groupName, serviceName, true); Subscriber subscriber = new Subscriber(meta.getClientIp(), meta.getClientVersion(), app, meta.getClientIp(), namespaceId, groupedServiceName, 0, request.getClusters()); ServiceInfo serviceInfo = ServiceUtil.selectInstancesWithHealthyProtection(serviceStorage.getData(service), - metadataManager.getServiceMetadata(service).orElse(null), subscriber.getCluster(), false, - true, subscriber.getIp()); + metadataManager.getServiceMetadata(service).orElse(null), subscriber.getCluster(), false, true, + subscriber.getIp()); if (request.isSubscribe()) { clientOperationService.subscribeService(service, subscriber, meta.getConnectionId()); NotifyCenter.publishEvent(new SubscribeServiceTraceEvent(System.currentTimeMillis(), - meta.getClientIp(), service.getNamespace(), service.getGroup(), service.getName())); + NamingRequestUtil.getSourceIpForGrpcRequest(meta), service.getNamespace(), service.getGroup(), + service.getName())); } else { clientOperationService.unsubscribeService(service, subscriber, meta.getConnectionId()); NotifyCenter.publishEvent(new UnsubscribeServiceTraceEvent(System.currentTimeMillis(), - meta.getClientIp(), service.getNamespace(), service.getGroup(), service.getName())); + NamingRequestUtil.getSourceIpForGrpcRequest(meta), service.getNamespace(), service.getGroup(), + service.getName())); } return new SubscribeServiceResponse(ResponseCode.SUCCESS.getCode(), "success", serviceInfo); } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/utils/NamingRequestUtil.java b/naming/src/main/java/com/alibaba/nacos/naming/utils/NamingRequestUtil.java new file mode 100644 index 00000000000..feed51b4e3b --- /dev/null +++ b/naming/src/main/java/com/alibaba/nacos/naming/utils/NamingRequestUtil.java @@ -0,0 +1,77 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.naming.utils; + +import com.alibaba.nacos.api.remote.request.RequestMeta; +import com.alibaba.nacos.common.utils.StringUtils; +import com.alibaba.nacos.core.context.RequestContextHolder; +import com.alibaba.nacos.core.context.addition.AddressContext; +import com.alibaba.nacos.core.utils.WebUtils; + +import javax.servlet.http.HttpServletRequest; + +/** + * Naming request util. + * + * @author xiweng.yy + */ +public class NamingRequestUtil { + + /** + * Get source ip from request context. + * + * @return source ip, null if not found + */ + public static String getSourceIp() { + AddressContext addressContext = RequestContextHolder.getContext().getBasicContext().getAddressContext(); + String sourceIp = addressContext.getSourceIp(); + if (StringUtils.isBlank(sourceIp)) { + sourceIp = addressContext.getRemoteIp(); + } + return sourceIp; + } + + /** + * Get source ip from request context first, if it can't found, get from http request. + * + * @param httpServletRequest http request + * @return source ip, null if not found + */ + public static String getSourceIpForHttpRequest(HttpServletRequest httpServletRequest) { + String sourceIp = getSourceIp(); + // If can't get from request context, get from http request. + if (StringUtils.isBlank(sourceIp)) { + sourceIp = WebUtils.getRemoteIp(httpServletRequest); + } + return sourceIp; + } + + /** + * Get source ip from request context first, if it can't found, get from http request. + * + * @param meta grpc request meta + * @return source ip, null if not found + */ + public static String getSourceIpForGrpcRequest(RequestMeta meta) { + String sourceIp = getSourceIp(); + // If can't get from request context, get from grpc request meta. + if (StringUtils.isBlank(sourceIp)) { + sourceIp = meta.getClientIp(); + } + return sourceIp; + } +} diff --git a/naming/src/main/java/com/alibaba/nacos/naming/web/ClientAttributesFilter.java b/naming/src/main/java/com/alibaba/nacos/naming/web/ClientAttributesFilter.java index 8a3638bc23a..99a91f33bd3 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/web/ClientAttributesFilter.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/web/ClientAttributesFilter.java @@ -20,6 +20,7 @@ import com.alibaba.nacos.common.utils.HttpMethod; import com.alibaba.nacos.common.utils.InternetAddressUtil; import com.alibaba.nacos.common.utils.StringUtils; +import com.alibaba.nacos.core.context.RequestContextHolder; import com.alibaba.nacos.core.utils.WebUtils; import com.alibaba.nacos.naming.core.v2.client.ClientAttributes; import com.alibaba.nacos.naming.core.v2.client.impl.IpPortBasedClient; @@ -35,6 +36,7 @@ import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import java.io.IOException; +import java.util.Optional; /** *

    @@ -56,7 +58,14 @@ public class ClientAttributesFilter implements Filter { @Autowired private ClientManager clientManager; - public static ThreadLocal threadLocalClientAttributes = new ThreadLocal<>(); + public static Optional getCurrentClientAttributes() { + Object clientAttributes = RequestContextHolder.getContext() + .getExtensionContext(ClientAttributes.class.getSimpleName()); + if (clientAttributes instanceof ClientAttributes) { + return Optional.of((ClientAttributes) clientAttributes); + } + return Optional.empty(); + } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) @@ -65,38 +74,32 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo String uri = request.getRequestURI(); String method = request.getMethod(); try { - try { - if (isRegisterInstanceUri(uri, method)) { - //register - ClientAttributes requestClientAttributes = getClientAttributes(request); - threadLocalClientAttributes.set(requestClientAttributes); - } else if (isBeatUri(uri, method)) { - //beat - String ip = WebUtils.optional(request, IP, StringUtils.EMPTY); - int port = Integer.parseInt(WebUtils.optional(request, PORT, ZERO)); - String clientId = IpPortBasedClient - .getClientId(ip + InternetAddressUtil.IP_PORT_SPLITER + port, true); - IpPortBasedClient client = (IpPortBasedClient) clientManager.getClient(clientId); - if (client != null) { - ClientAttributes requestClientAttributes = getClientAttributes(request); - //update clientAttributes,when client version attributes is null,then update. - if (canUpdateClientAttributes(client, requestClientAttributes)) { - client.setAttributes(requestClientAttributes); - } + if (isRegisterInstanceUri(uri, method)) { + //register + ClientAttributes attributes = getClientAttributes(); + RequestContextHolder.getContext() + .addExtensionContext(ClientAttributes.class.getSimpleName(), attributes); + } else if (isBeatUri(uri, method)) { + //beat + String ip = WebUtils.optional(request, IP, StringUtils.EMPTY); + int port = Integer.parseInt(WebUtils.optional(request, PORT, ZERO)); + String clientId = IpPortBasedClient.getClientId(ip + InternetAddressUtil.IP_PORT_SPLITER + port, true); + IpPortBasedClient client = (IpPortBasedClient) clientManager.getClient(clientId); + if (client != null) { + ClientAttributes requestClientAttributes = getClientAttributes(); + //update clientAttributes,when client version attributes is null,then update. + if (canUpdateClientAttributes(client, requestClientAttributes)) { + client.setAttributes(requestClientAttributes); } } - } catch (Exception e) { - Loggers.SRV_LOG.error("handler client attributes error", e); - } - try { - filterChain.doFilter(request, servletResponse); - } catch (ServletException e) { - throw new RuntimeException(e); - } - } finally { - if (threadLocalClientAttributes.get() != null) { - threadLocalClientAttributes.remove(); } + } catch (Exception e) { + Loggers.SRV_LOG.error("handler client attributes error", e); + } + try { + filterChain.doFilter(request, servletResponse); + } catch (ServletException e) { + throw new RuntimeException(e); } } @@ -104,19 +107,18 @@ private boolean isBeatUri(String uri, String httpMethod) { return ((UtilsAndCommons.NACOS_SERVER_CONTEXT + UtilsAndCommons.NACOS_NAMING_CONTEXT + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT + BEAT_URI).equals(uri) || ( UtilsAndCommons.NACOS_SERVER_CONTEXT + UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 - + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT + BEAT_URI).equals(uri)) && HttpMethod.PUT - .equals(httpMethod); + + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT + BEAT_URI).equals(uri)) + && HttpMethod.PUT.equals(httpMethod); } private boolean isRegisterInstanceUri(String uri, String httpMethod) { return ((UtilsAndCommons.NACOS_SERVER_CONTEXT + UtilsAndCommons.NACOS_NAMING_CONTEXT + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT).equals(uri) || (UtilsAndCommons.NACOS_SERVER_CONTEXT - + UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT) - .equals(uri)) && HttpMethod.POST.equals(httpMethod); + + UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT).equals(uri)) && HttpMethod.POST.equals(httpMethod); } - private static boolean canUpdateClientAttributes(IpPortBasedClient client, - ClientAttributes requestClientAttributes) { + private boolean canUpdateClientAttributes(IpPortBasedClient client, ClientAttributes requestClientAttributes) { if (requestClientAttributes.getClientAttribute(HttpHeaderConsts.CLIENT_VERSION_HEADER) == null) { return false; } @@ -127,10 +129,10 @@ private static boolean canUpdateClientAttributes(IpPortBasedClient client, return true; } - public static ClientAttributes getClientAttributes(HttpServletRequest request) { - String version = request.getHeader(HttpHeaderConsts.CLIENT_VERSION_HEADER); - String app = request.getHeader(HttpHeaderConsts.APP_FILED); - String clientIp = request.getRemoteAddr(); + private ClientAttributes getClientAttributes() { + String version = RequestContextHolder.getContext().getBasicContext().getUserAgent(); + String app = RequestContextHolder.getContext().getBasicContext().getApp(); + String clientIp = RequestContextHolder.getContext().getBasicContext().getAddressContext().getSourceIp(); ClientAttributes clientAttributes = new ClientAttributes(); if (version != null) { clientAttributes.addClientAttribute(HttpHeaderConsts.CLIENT_VERSION_HEADER, version); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/BaseTest.java b/naming/src/test/java/com/alibaba/nacos/naming/BaseTest.java index 130254596fc..cbd2d011db4 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/BaseTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/BaseTest.java @@ -21,13 +21,11 @@ import com.alibaba.nacos.naming.push.UdpPushService; import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.utils.ApplicationUtils; -import org.junit.Before; -import org.junit.Rule; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Spy; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.mock.env.MockEnvironment; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; @@ -36,7 +34,7 @@ import static org.mockito.Mockito.doReturn; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public abstract class BaseTest { protected static final String TEST_CLUSTER_NAME = "test-cluster"; @@ -55,9 +53,6 @@ public abstract class BaseTest { + "\"port\":9870,\"weight\":2.0,\"healthy\":true,\"enabled\":true,\"ephemeral\":true" + ",\"clusterName\":\"clusterName\",\"serviceName\":\"serviceName\",\"metadata\":{}}]"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Spy protected ConfigurableApplicationContext context; @@ -73,14 +68,13 @@ public abstract class BaseTest { @Spy protected MockEnvironment environment; - @Before + @BeforeEach public void before() { EnvUtil.setEnvironment(environment); ApplicationUtils.injectContext(context); } - protected MockHttpServletRequestBuilder convert(Object simpleOb, MockHttpServletRequestBuilder builder) - throws IllegalAccessException { + protected MockHttpServletRequestBuilder convert(Object simpleOb, MockHttpServletRequestBuilder builder) throws IllegalAccessException { Field[] declaredFields = simpleOb.getClass().getDeclaredFields(); for (Field declaredField : declaredFields) { declaredField.setAccessible(true); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/ability/NamingAbilityInitializerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/ability/NamingAbilityInitializerTest.java index bdd8516a8ba..a5a5a6cf96d 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/ability/NamingAbilityInitializerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/ability/NamingAbilityInitializerTest.java @@ -17,15 +17,15 @@ package com.alibaba.nacos.naming.ability; import com.alibaba.nacos.api.ability.ServerAbilities; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class NamingAbilityInitializerTest { +class NamingAbilityInitializerTest { @Test - public void testInitialize() { + void testInitialize() { NamingAbilityInitializer initializer = new NamingAbilityInitializer(); ServerAbilities abilities = new ServerAbilities(); assertFalse(abilities.getNamingAbility().isSupportJraft()); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/cluster/ServerStatusManagerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/cluster/ServerStatusManagerTest.java index 8c7a13dd520..9ebc8660304 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/cluster/ServerStatusManagerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/cluster/ServerStatusManagerTest.java @@ -18,103 +18,121 @@ package com.alibaba.nacos.naming.cluster; -import com.alibaba.nacos.naming.consistency.ConsistencyService; +import com.alibaba.nacos.consistency.cp.CPProtocol; +import com.alibaba.nacos.core.distributed.ProtocolManager; +import com.alibaba.nacos.naming.constants.Constants; import com.alibaba.nacos.naming.misc.GlobalExecutor; import com.alibaba.nacos.naming.misc.SwitchDomain; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import com.alipay.sofa.jraft.RouteTable; +import com.alipay.sofa.jraft.entity.PeerId; +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.junit.jupiter.MockitoExtension; import org.springframework.mock.env.MockEnvironment; -import java.lang.reflect.Field; import java.util.Optional; +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.mockStatic; import static org.mockito.Mockito.when; -public class ServerStatusManagerTest { +@ExtendWith(MockitoExtension.class) +class ServerStatusManagerTest { - @Before - public void setUp() { + @Mock + SwitchDomain switchDomain; + + @Mock + ProtocolManager protocolManager; + + @Mock + CPProtocol cpProtocol; + + @BeforeEach + void setUp() { EnvUtil.setEnvironment(new MockEnvironment()); } @Test - public void testInit() { + void testInit() { try (MockedStatic mocked = mockStatic(GlobalExecutor.class)) { - ServerStatusManager serverStatusManager = new ServerStatusManager(mock(SwitchDomain.class)); + ServerStatusManager serverStatusManager = new ServerStatusManager(protocolManager, switchDomain); serverStatusManager.init(); mocked.verify(() -> GlobalExecutor.registerServerStatusUpdater(any())); } } @Test - public void testGetServerStatus() { - ServerStatusManager serverStatusManager = new ServerStatusManager(mock(SwitchDomain.class)); + void testGetServerStatus() { + ServerStatusManager serverStatusManager = new ServerStatusManager(protocolManager, switchDomain); ServerStatus serverStatus = serverStatusManager.getServerStatus(); - Assert.assertEquals(ServerStatus.STARTING, serverStatus); + assertEquals(ServerStatus.STARTING, serverStatus); } @Test - public void testGetErrorMsg() throws NoSuchFieldException, IllegalAccessException { - ServerStatusManager serverStatusManager = new ServerStatusManager(mock(SwitchDomain.class)); - Field field = ServerStatusManager.class.getDeclaredField("consistencyService"); - field.setAccessible(true); - ConsistencyService consistencyService = mock(ConsistencyService.class); - when(consistencyService.getErrorMsg()).thenReturn(Optional.empty()); - field.set(serverStatusManager, consistencyService); + void testGetErrorMsg() { + ServerStatusManager serverStatusManager = new ServerStatusManager(protocolManager, switchDomain); Optional errorMsg = serverStatusManager.getErrorMsg(); - Assert.assertFalse(errorMsg.isPresent()); + assertTrue(errorMsg.isPresent()); } @Test - public void testUpdaterFromSwitch() { - SwitchDomain switchDomain = mock(SwitchDomain.class); + void testUpdaterFromSwitch() { String expect = ServerStatus.DOWN.toString(); when(switchDomain.getOverriddenServerStatus()).thenReturn(expect); - ServerStatusManager serverStatusManager = new ServerStatusManager(switchDomain); + ServerStatusManager serverStatusManager = new ServerStatusManager(protocolManager, switchDomain); ServerStatusManager.ServerStatusUpdater updater = serverStatusManager.new ServerStatusUpdater(); //then updater.run(); //then ServerStatus serverStatus = serverStatusManager.getServerStatus(); - Assert.assertEquals(expect, serverStatus.toString()); + assertEquals(expect, serverStatus.toString()); + } + + @Test + void testUpdaterFromConsistency1() { + try (MockedStatic mocked = mockStatic(RouteTable.class)) { + RouteTable mockTable = mock(RouteTable.class); + when(mockTable.selectLeader(Constants.NAMING_PERSISTENT_SERVICE_GROUP)).thenReturn(new PeerId()); + mocked.when(RouteTable::getInstance).thenReturn(mockTable); + when(protocolManager.getCpProtocol()).thenReturn(cpProtocol); + ServerStatusManager serverStatusManager = new ServerStatusManager(protocolManager, switchDomain); + ServerStatusManager.ServerStatusUpdater updater = serverStatusManager.new ServerStatusUpdater(); + //then + updater.run(); + //then + assertEquals(ServerStatus.UP, serverStatusManager.getServerStatus()); + assertFalse(serverStatusManager.getErrorMsg().isPresent()); + } } @Test - public void testUpdaterFromConsistency1() throws NoSuchFieldException, IllegalAccessException { - SwitchDomain switchDomain = mock(SwitchDomain.class); - ServerStatusManager serverStatusManager = new ServerStatusManager(switchDomain); - Field field = ServerStatusManager.class.getDeclaredField("consistencyService"); - field.setAccessible(true); - ConsistencyService consistencyService = mock(ConsistencyService.class); - when(consistencyService.isAvailable()).thenReturn(true); - field.set(serverStatusManager, consistencyService); + void testUpdaterFromConsistency2() { + when(protocolManager.getCpProtocol()).thenReturn(cpProtocol); + ServerStatusManager serverStatusManager = new ServerStatusManager(protocolManager, switchDomain); ServerStatusManager.ServerStatusUpdater updater = serverStatusManager.new ServerStatusUpdater(); //then updater.run(); //then - Assert.assertEquals(ServerStatus.UP, serverStatusManager.getServerStatus()); + assertEquals(ServerStatus.DOWN, serverStatusManager.getServerStatus()); } @Test - public void testUpdaterFromConsistency2() throws NoSuchFieldException, IllegalAccessException { - SwitchDomain switchDomain = mock(SwitchDomain.class); - ServerStatusManager serverStatusManager = new ServerStatusManager(switchDomain); - Field field = ServerStatusManager.class.getDeclaredField("consistencyService"); - field.setAccessible(true); - ConsistencyService consistencyService = mock(ConsistencyService.class); - when(consistencyService.isAvailable()).thenReturn(false); - field.set(serverStatusManager, consistencyService); + void testUpdaterFromConsistency3() { + ServerStatusManager serverStatusManager = new ServerStatusManager(protocolManager, switchDomain); ServerStatusManager.ServerStatusUpdater updater = serverStatusManager.new ServerStatusUpdater(); //then updater.run(); //then - Assert.assertEquals(ServerStatus.DOWN, serverStatusManager.getServerStatus()); + assertEquals(ServerStatus.DOWN, serverStatusManager.getServerStatus()); } } \ No newline at end of file diff --git a/naming/src/test/java/com/alibaba/nacos/naming/cluster/remote/request/AbstractClusterRequestTest.java b/naming/src/test/java/com/alibaba/nacos/naming/cluster/remote/request/AbstractClusterRequestTest.java index c87c20d7cee..b5fd92fbb64 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/cluster/remote/request/AbstractClusterRequestTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/cluster/remote/request/AbstractClusterRequestTest.java @@ -19,14 +19,14 @@ package com.alibaba.nacos.naming.cluster.remote.request; import com.alibaba.nacos.core.cluster.remote.request.AbstractClusterRequest; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class AbstractClusterRequestTest { +class AbstractClusterRequestTest { @Test - public void getModule() { + void getModule() { AbstractClusterRequest request = new AbstractClusterRequest() { }; String actual = request.getModule(); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/cluster/remote/request/DistroDataRequestTest.java b/naming/src/test/java/com/alibaba/nacos/naming/cluster/remote/request/DistroDataRequestTest.java index 80e8b9c2d42..d53188952aa 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/cluster/remote/request/DistroDataRequestTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/cluster/remote/request/DistroDataRequestTest.java @@ -20,28 +20,28 @@ import com.alibaba.nacos.consistency.DataOperation; import com.alibaba.nacos.core.distributed.distro.entity.DistroData; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.mock; -public class DistroDataRequestTest { +class DistroDataRequestTest { @Test - public void testConstructor1() { + void testConstructor1() { DistroDataRequest req = new DistroDataRequest(); assertNotNull(req); } @Test - public void testConstructor2() { + void testConstructor2() { DistroDataRequest req = new DistroDataRequest(mock(DistroData.class), mock(DataOperation.class)); assertNotNull(req); } @Test - public void testGetterAndSetter() { + void testGetterAndSetter() { DistroData distroData = mock(DistroData.class); DataOperation dataOperation = mock(DataOperation.class); DistroDataRequest req = new DistroDataRequest(); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/cluster/remote/response/DistroDataResponseTest.java b/naming/src/test/java/com/alibaba/nacos/naming/cluster/remote/response/DistroDataResponseTest.java index 944d1a2047a..49d8913b33e 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/cluster/remote/response/DistroDataResponseTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/cluster/remote/response/DistroDataResponseTest.java @@ -19,15 +19,15 @@ package com.alibaba.nacos.naming.cluster.remote.response; import com.alibaba.nacos.core.distributed.distro.entity.DistroData; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; -public class DistroDataResponseTest { +class DistroDataResponseTest { @Test - public void test() { + void test() { DistroDataResponse distroDataResponse = new DistroDataResponse(); DistroData distroData = mock(DistroData.class); distroDataResponse.setDistroData(distroData); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/cluster/transport/JacksonSerializerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/cluster/transport/JacksonSerializerTest.java index 730beaad6da..20fd5564e61 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/cluster/transport/JacksonSerializerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/cluster/transport/JacksonSerializerTest.java @@ -18,26 +18,26 @@ import com.alibaba.nacos.common.utils.ByteUtils; import com.alibaba.nacos.naming.misc.SwitchDomain; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -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 JacksonSerializerTest { +class JacksonSerializerTest { private Serializer serializer; private SwitchDomain switchDomain; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { serializer = new JacksonSerializer(); switchDomain = new SwitchDomain(); } @Test - public void testSerialize() { + void testSerialize() { String actual = new String(serializer.serialize(switchDomain)); assertTrue(actual.contains("\"defaultPushCacheMillis\":10000")); assertTrue(actual.contains("\"clientBeatInterval\":5000")); @@ -47,7 +47,7 @@ public void testSerialize() { @Test @SuppressWarnings("checkstyle:linelength") - public void testDeserialize() { + void testDeserialize() { String example = "{\"adWeightMap\":{},\"defaultPushCacheMillis\":10000,\"clientBeatInterval\":5000,\"defaultCacheMillis\":3000,\"distroThreshold\":0.7,\"healthCheckEnabled\":true,\"autoChangeHealthCheckEnabled\":true,\"distroEnabled\":true,\"enableStandalone\":true,\"pushEnabled\":true,\"checkTimes\":3,\"httpHealthParams\":{\"max\":5000,\"min\":500,\"factor\":0.85},\"tcpHealthParams\":{\"max\":5000,\"min\":1000,\"factor\":0.75},\"mysqlHealthParams\":{\"max\":3000,\"min\":2000,\"factor\":0.65},\"incrementalList\":[],\"serverStatusSynchronizationPeriodMillis\":2000,\"serviceStatusSynchronizationPeriodMillis\":5000,\"disableAddIP\":false,\"sendBeatOnly\":false,\"lightBeatEnabled\":true,\"doubleWriteEnabled\":true,\"limitedUrlMap\":{},\"distroServerExpiredMillis\":10000,\"pushGoVersion\":\"0.1.0\",\"pushJavaVersion\":\"0.1.0\",\"pushPythonVersion\":\"0.4.3\",\"pushCVersion\":\"1.0.12\",\"pushCSharpVersion\":\"0.9.0\",\"enableAuthentication\":false,\"defaultInstanceEphemeral\":true,\"healthCheckWhiteList\":[],\"name\":\"00-00---000-NACOS_SWITCH_DOMAIN-000---00-00\"}"; SwitchDomain actual = serializer.deserialize(ByteUtils.toBytes(example), SwitchDomain.class); assertEquals(10000, actual.getDefaultPushCacheMillis()); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/consistency/ephemeral/distro/v2/DistroClientComponentRegistryTest.java b/naming/src/test/java/com/alibaba/nacos/naming/consistency/ephemeral/distro/v2/DistroClientComponentRegistryTest.java index 6249d38403a..aa32427efb9 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/consistency/ephemeral/distro/v2/DistroClientComponentRegistryTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/consistency/ephemeral/distro/v2/DistroClientComponentRegistryTest.java @@ -26,16 +26,16 @@ import com.alibaba.nacos.core.distributed.distro.component.DistroTransportAgent; import com.alibaba.nacos.core.distributed.distro.task.DistroTaskEngineHolder; import com.alibaba.nacos.naming.core.v2.client.manager.ClientManagerDelegate; -import junit.framework.TestCase; -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; -@RunWith(MockitoJUnitRunner.class) -public class DistroClientComponentRegistryTest extends TestCase { +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@ExtendWith(MockitoExtension.class) +class DistroClientComponentRegistryTest { private DistroClientComponentRegistry distroClientComponentRegistry; @@ -56,30 +56,29 @@ public class DistroClientComponentRegistryTest extends TestCase { private DistroComponentHolder componentHolder; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { componentHolder = new DistroComponentHolder(); - distroClientComponentRegistry = new DistroClientComponentRegistry(serverMemberManager, distroProtocol, - componentHolder, taskEngineHolder, clientManager, clusterRpcClientProxy); + distroClientComponentRegistry = new DistroClientComponentRegistry(serverMemberManager, distroProtocol, componentHolder, + taskEngineHolder, clientManager, clusterRpcClientProxy); } @Test - public void testDoRegister() { + void testDoRegister() { distroClientComponentRegistry.doRegister(); DistroDataStorage dataStorage = componentHolder.findDataStorage(DistroClientDataProcessor.TYPE); - Assert.assertNotNull(dataStorage); + assertNotNull(dataStorage); DistroDataProcessor dataProcessor = componentHolder.findDataProcessor(DistroClientDataProcessor.TYPE); - Assert.assertNotNull(dataProcessor); + assertNotNull(dataProcessor); - DistroFailedTaskHandler failedTaskHandler = componentHolder - .findFailedTaskHandler(DistroClientDataProcessor.TYPE); - Assert.assertNotNull(failedTaskHandler); + DistroFailedTaskHandler failedTaskHandler = componentHolder.findFailedTaskHandler(DistroClientDataProcessor.TYPE); + assertNotNull(failedTaskHandler); DistroTransportAgent transportAgent = componentHolder.findTransportAgent(DistroClientDataProcessor.TYPE); - Assert.assertNotNull(transportAgent); + assertNotNull(transportAgent); } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/consistency/ephemeral/distro/v2/DistroClientDataProcessorTest.java b/naming/src/test/java/com/alibaba/nacos/naming/consistency/ephemeral/distro/v2/DistroClientDataProcessorTest.java index bafa8d1f229..d6ed20cf113 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/consistency/ephemeral/distro/v2/DistroClientDataProcessorTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/consistency/ephemeral/distro/v2/DistroClientDataProcessorTest.java @@ -37,22 +37,24 @@ import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.utils.ApplicationUtils; -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 org.springframework.context.ConfigurableApplicationContext; import java.util.Arrays; import java.util.Collections; import java.util.List; -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; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; @@ -62,8 +64,10 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class DistroClientDataProcessorTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class DistroClientDataProcessorTest { private static final String CLIENT_ID = "11111_1.1.1.1_3306"; @@ -91,8 +95,8 @@ public class DistroClientDataProcessorTest { private DistroClientDataProcessor distroClientDataProcessor; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { distroClientDataProcessor = new DistroClientDataProcessor(clientManager, distroProtocol); EnvUtil.setIsStandalone(false); client = new ConnectionBasedClient(CLIENT_ID, true, 0L); @@ -122,25 +126,25 @@ private ClientSyncData mockClientSyncData() { return result; } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { NotifyCenter.deregisterSubscriber(distroClientDataProcessor); } @Test - public void testFinishInitial() { + void testFinishInitial() { assertFalse(distroClientDataProcessor.isFinishInitial()); distroClientDataProcessor.finishInitial(); assertTrue(distroClientDataProcessor.isFinishInitial()); } @Test - public void processType() { + void processType() { assertEquals(DistroClientDataProcessor.TYPE, distroClientDataProcessor.processType()); } @Test - public void testOnEventForStandalone() { + void testOnEventForStandalone() { EnvUtil.setIsStandalone(true); distroClientDataProcessor.onEvent(new ClientEvent.ClientVerifyFailedEvent(CLIENT_ID, MOCK_TARGET_SERVER)); verify(distroProtocol, never()).syncToTarget(any(), any(), anyString(), anyLong()); @@ -148,7 +152,7 @@ public void testOnEventForStandalone() { } @Test - public void testOnClientVerifyFailedEventWithoutClient() { + void testOnClientVerifyFailedEventWithoutClient() { when(clientManager.getClient(CLIENT_ID)).thenReturn(null); distroClientDataProcessor.onEvent(new ClientEvent.ClientVerifyFailedEvent(CLIENT_ID, MOCK_TARGET_SERVER)); verify(distroProtocol, never()).syncToTarget(any(), any(), anyString(), anyLong()); @@ -156,7 +160,7 @@ public void testOnClientVerifyFailedEventWithoutClient() { } @Test - public void testOnClientVerifyFailedEventWithPersistentClient() { + void testOnClientVerifyFailedEventWithPersistentClient() { client = mock(Client.class); when(client.isEphemeral()).thenReturn(false); when(clientManager.getClient(CLIENT_ID)).thenReturn(client); @@ -166,7 +170,7 @@ public void testOnClientVerifyFailedEventWithPersistentClient() { } @Test - public void testOnClientVerifyFailedEventWithoutResponsible() { + void testOnClientVerifyFailedEventWithoutResponsible() { when(clientManager.isResponsibleClient(client)).thenReturn(false); distroClientDataProcessor.onEvent(new ClientEvent.ClientVerifyFailedEvent(CLIENT_ID, MOCK_TARGET_SERVER)); verify(distroProtocol, never()).syncToTarget(any(), any(), anyString(), anyLong()); @@ -174,21 +178,21 @@ public void testOnClientVerifyFailedEventWithoutResponsible() { } @Test - public void testOnClientVerifyFailedEventSuccess() { + void testOnClientVerifyFailedEventSuccess() { distroClientDataProcessor.onEvent(new ClientEvent.ClientVerifyFailedEvent(CLIENT_ID, MOCK_TARGET_SERVER)); verify(distroProtocol).syncToTarget(any(), eq(DataOperation.ADD), eq(MOCK_TARGET_SERVER), eq(0L)); verify(distroProtocol, never()).sync(any(), any()); } @Test - public void testOnClientChangedEventWithoutClient() { + void testOnClientChangedEventWithoutClient() { distroClientDataProcessor.onEvent(new ClientEvent.ClientChangedEvent(null)); verify(distroProtocol, never()).syncToTarget(any(), any(), anyString(), anyLong()); verify(distroProtocol, never()).sync(any(), any()); } @Test - public void testOnClientChangedEventWithPersistentClient() { + void testOnClientChangedEventWithPersistentClient() { client = mock(Client.class); when(client.isEphemeral()).thenReturn(false); distroClientDataProcessor.onEvent(new ClientEvent.ClientChangedEvent(client)); @@ -197,7 +201,7 @@ public void testOnClientChangedEventWithPersistentClient() { } @Test - public void testOnClientChangedEventWithoutResponsible() { + void testOnClientChangedEventWithoutResponsible() { when(clientManager.isResponsibleClient(client)).thenReturn(false); distroClientDataProcessor.onEvent(new ClientEvent.ClientChangedEvent(client)); verify(distroProtocol, never()).syncToTarget(any(), any(), anyString(), anyLong()); @@ -205,28 +209,28 @@ public void testOnClientChangedEventWithoutResponsible() { } @Test - public void testOnClientChangedEventSuccess() { + void testOnClientChangedEventSuccess() { distroClientDataProcessor.onEvent(new ClientEvent.ClientChangedEvent(client)); verify(distroProtocol, never()).syncToTarget(any(), any(), anyString(), anyLong()); verify(distroProtocol).sync(any(), eq(DataOperation.CHANGE)); } @Test - public void testOnClientDisconnectEventSuccess() { + void testOnClientDisconnectEventSuccess() { distroClientDataProcessor.onEvent(new ClientEvent.ClientDisconnectEvent(client, true)); verify(distroProtocol, never()).syncToTarget(any(), any(), anyString(), anyLong()); verify(distroProtocol).sync(any(), eq(DataOperation.DELETE)); } @Test - public void testProcessDataForDeleteClient() { + void testProcessDataForDeleteClient() { distroData.setType(DataOperation.DELETE); distroClientDataProcessor.processData(distroData); verify(clientManager).clientDisconnected(CLIENT_ID); } @Test - public void testProcessDataForChangeClient() { + void testProcessDataForChangeClient() { distroData.setType(DataOperation.CHANGE); assertEquals(0L, client.getRevision()); assertEquals(0, client.getAllPublishedService().size()); @@ -235,13 +239,13 @@ public void testProcessDataForChangeClient() { assertEquals(1L, client.getRevision()); assertEquals(1, client.getAllPublishedService().size()); } - + @Test - public void testProcessDataForBatch() { + void testProcessDataForBatch() { // swap tmp Serializer mock = Mockito.mock(Serializer.class); when(applicationContext.getBean(Serializer.class)).thenReturn(mock); - + // single instance => batch instances => batch instances => single instance // single ClientSyncData syncData = createSingleForBatchTest(1); @@ -255,9 +259,9 @@ public void testProcessDataForBatch() { Service service = Service.newService("batchData", "batchData", "batchData"); Service singleton = ServiceManager.getInstance().getSingleton(service); InstancePublishInfo info = client.getInstancePublishInfo(ServiceManager.getInstance().getSingleton(singleton)); - assertEquals(info.getIp(), "127.0.0.1"); - assertEquals(info.getPort(), 8080); - + assertEquals("127.0.0.1", info.getIp()); + assertEquals(8080, info.getPort()); + // batch data = new DistroData(); syncData = createBatchForBatchTest(2); @@ -270,12 +274,12 @@ public void testProcessDataForBatch() { info = client.getInstancePublishInfo(ServiceManager.getInstance().getSingleton(singleton)); assertTrue(info instanceof BatchInstancePublishInfo); BatchInstancePublishInfo batchInfo = (BatchInstancePublishInfo) info; - assertEquals(batchInfo.getInstancePublishInfos().size(), 2); + assertEquals(2, batchInfo.getInstancePublishInfos().size()); for (InstancePublishInfo instancePublishInfo : batchInfo.getInstancePublishInfos()) { - assertEquals(instancePublishInfo.getIp(), "127.0.0.1"); + assertEquals("127.0.0.1", instancePublishInfo.getIp()); assertTrue(instancePublishInfo.getPort() == 8080 || instancePublishInfo.getPort() == 8081); } - + // batch data = new DistroData(); syncData = createBatchForBatchTest(3); @@ -288,12 +292,12 @@ public void testProcessDataForBatch() { info = client.getInstancePublishInfo(ServiceManager.getInstance().getSingleton(singleton)); assertTrue(info instanceof BatchInstancePublishInfo); batchInfo = (BatchInstancePublishInfo) info; - assertEquals(batchInfo.getInstancePublishInfos().size(), 2); + assertEquals(2, batchInfo.getInstancePublishInfos().size()); for (InstancePublishInfo instancePublishInfo : batchInfo.getInstancePublishInfos()) { - assertEquals(instancePublishInfo.getIp(), "127.0.0.1"); + assertEquals("127.0.0.1", instancePublishInfo.getIp()); assertTrue(instancePublishInfo.getPort() == 8080 || instancePublishInfo.getPort() == 8081); } - + // single syncData = createSingleForBatchTest(4); data = new DistroData(); @@ -304,10 +308,10 @@ public void testProcessDataForBatch() { assertEquals(4L, client.getRevision()); assertEquals(1, client.getAllPublishedService().size()); info = client.getInstancePublishInfo(ServiceManager.getInstance().getSingleton(singleton)); - assertEquals(info.getIp(), "127.0.0.1"); - assertEquals(info.getPort(), 8080); + assertEquals("127.0.0.1", info.getIp()); + assertEquals(8080, info.getPort()); } - + private ClientSyncData createSingleForBatchTest(int revision) { ClientSyncData syncData = new ClientSyncData(); syncData.setClientId(CLIENT_ID); @@ -320,7 +324,7 @@ private ClientSyncData createSingleForBatchTest(int revision) { syncData.setInstancePublishInfos(Collections.singletonList(new InstancePublishInfo("127.0.0.1", 8080))); return syncData; } - + private ClientSyncData createBatchForBatchTest(int revision) { ClientSyncData syncData = new ClientSyncData(); syncData.setClientId(CLIENT_ID); @@ -329,18 +333,15 @@ private ClientSyncData createBatchForBatchTest(int revision) { syncData.setAttributes(clientAttributes); syncData.setNamespaces(Collections.emptyList()); BatchInstancePublishInfo batchInstancePublishInfo = new BatchInstancePublishInfo(); - syncData.setBatchInstanceData(new BatchInstanceData(Collections.singletonList("batchData"), - Collections.singletonList("batchData"), - Collections.singletonList("batchData"), - Collections.singletonList(batchInstancePublishInfo))); + syncData.setBatchInstanceData(new BatchInstanceData(Collections.singletonList("batchData"), Collections.singletonList("batchData"), + Collections.singletonList("batchData"), Collections.singletonList(batchInstancePublishInfo))); batchInstancePublishInfo.setInstancePublishInfos( - Arrays.asList(new InstancePublishInfo("127.0.0.1", 8080), - new InstancePublishInfo("127.0.0.1", 8081))); + Arrays.asList(new InstancePublishInfo("127.0.0.1", 8080), new InstancePublishInfo("127.0.0.1", 8081))); return syncData; } @Test - public void testProcessVerifyData() { + void testProcessVerifyData() { DistroClientVerifyInfo verifyInfo = new DistroClientVerifyInfo(CLIENT_ID, 0L); when(serializer.deserialize(any(), eq(DistroClientVerifyInfo.class))).thenReturn(verifyInfo); assertFalse(distroClientDataProcessor.processVerifyData(distroData, MOCK_TARGET_SERVER)); @@ -349,7 +350,7 @@ public void testProcessVerifyData() { } @Test - public void testProcessSnapshot() { + void testProcessSnapshot() { ClientSyncDatumSnapshot snapshot = new ClientSyncDatumSnapshot(); snapshot.setClientSyncDataList(Collections.singletonList(clientSyncData)); when(serializer.deserialize(any(), eq(ClientSyncDatumSnapshot.class))).thenReturn(snapshot); @@ -362,13 +363,13 @@ public void testProcessSnapshot() { } @Test - public void testGetDistroData() { + void testGetDistroData() { DistroData actual = distroClientDataProcessor.getDistroData(distroKey); assertEquals(distroKey, actual.getDistroKey()); } @Test - public void testGetDatumSnapshot() { + void testGetDatumSnapshot() { when(clientManager.allClientId()).thenReturn(Collections.singletonList(CLIENT_ID)); DistroData actual = distroClientDataProcessor.getDatumSnapshot(); assertEquals(DataOperation.SNAPSHOT.name(), actual.getDistroKey().getResourceKey()); @@ -376,7 +377,7 @@ public void testGetDatumSnapshot() { } @Test - public void testGetVerifyData() { + void testGetVerifyData() { client.setRevision(10L); when(clientManager.allClientId()).thenReturn(Collections.singletonList(CLIENT_ID)); List list = distroClientDataProcessor.getVerifyData(); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/consistency/ephemeral/distro/v2/DistroClientTransportAgentTest.java b/naming/src/test/java/com/alibaba/nacos/naming/consistency/ephemeral/distro/v2/DistroClientTransportAgentTest.java index a262979aee0..4ceb2ac7f20 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/consistency/ephemeral/distro/v2/DistroClientTransportAgentTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/consistency/ephemeral/distro/v2/DistroClientTransportAgentTest.java @@ -31,18 +31,21 @@ import com.alibaba.nacos.naming.cluster.remote.response.DistroDataResponse; import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.utils.ApplicationUtils; -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.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.mock.env.MockEnvironment; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; @@ -51,8 +54,10 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class DistroClientTransportAgentTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class DistroClientTransportAgentTest { @Mock ClusterRpcClientProxy clusterRpcClientProxy; @@ -73,8 +78,8 @@ public class DistroClientTransportAgentTest { Response response; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { ApplicationUtils.injectContext(context); EnvUtil.setEnvironment(new MockEnvironment()); member = new Member(); @@ -92,24 +97,24 @@ public void setUp() throws Exception { // When run all project, the TpsNamingMonitor will be init by other unit test, will throw UnnecessaryStubbingException. } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { } @Test - public void testSupportCallbackTransport() { + void testSupportCallbackTransport() { assertTrue(transportAgent.supportCallbackTransport()); } @Test - public void testSyncDataForMemberNonExist() throws NacosException { + void testSyncDataForMemberNonExist() throws NacosException { assertTrue(transportAgent.syncData(new DistroData(), member.getAddress())); verify(memberManager, never()).find(member.getAddress()); verify(clusterRpcClientProxy, never()).sendRequest(any(Member.class), any()); } @Test - public void testSyncDataForMemberUnhealthy() throws NacosException { + void testSyncDataForMemberUnhealthy() throws NacosException { when(memberManager.hasMember(member.getAddress())).thenReturn(true); when(memberManager.find(member.getAddress())).thenReturn(member); assertFalse(transportAgent.syncData(new DistroData(), member.getAddress())); @@ -117,7 +122,7 @@ public void testSyncDataForMemberUnhealthy() throws NacosException { } @Test - public void testSyncDataForMemberDisconnect() throws NacosException { + void testSyncDataForMemberDisconnect() throws NacosException { when(memberManager.hasMember(member.getAddress())).thenReturn(true); when(memberManager.find(member.getAddress())).thenReturn(member); member.setState(NodeState.UP); @@ -126,7 +131,7 @@ public void testSyncDataForMemberDisconnect() throws NacosException { } @Test - public void testSyncDataFailure() throws NacosException { + void testSyncDataFailure() throws NacosException { when(memberManager.hasMember(member.getAddress())).thenReturn(true); when(memberManager.find(member.getAddress())).thenReturn(member); member.setState(NodeState.UP); @@ -136,7 +141,7 @@ public void testSyncDataFailure() throws NacosException { } @Test - public void testSyncDataException() throws NacosException { + void testSyncDataException() throws NacosException { when(memberManager.hasMember(member.getAddress())).thenReturn(true); when(memberManager.find(member.getAddress())).thenReturn(member); member.setState(NodeState.UP); @@ -146,7 +151,7 @@ public void testSyncDataException() throws NacosException { } @Test - public void testSyncDataSuccess() throws NacosException { + void testSyncDataSuccess() throws NacosException { when(memberManager.hasMember(member.getAddress())).thenReturn(true); when(memberManager.find(member.getAddress())).thenReturn(member); member.setState(NodeState.UP); @@ -155,7 +160,7 @@ public void testSyncDataSuccess() throws NacosException { } @Test - public void testSyncDataWithCallbackForMemberNonExist() throws NacosException { + void testSyncDataWithCallbackForMemberNonExist() throws NacosException { transportAgent.syncData(new DistroData(), member.getAddress(), distroCallback); verify(distroCallback).onSuccess(); verify(memberManager, never()).find(member.getAddress()); @@ -163,7 +168,7 @@ public void testSyncDataWithCallbackForMemberNonExist() throws NacosException { } @Test - public void testSyncDataWithCallbackForMemberUnhealthy() throws NacosException { + void testSyncDataWithCallbackForMemberUnhealthy() throws NacosException { when(memberManager.hasMember(member.getAddress())).thenReturn(true); when(memberManager.find(member.getAddress())).thenReturn(member); transportAgent.syncData(new DistroData(), member.getAddress(), distroCallback); @@ -172,7 +177,7 @@ public void testSyncDataWithCallbackForMemberUnhealthy() throws NacosException { } @Test - public void testSyncDataWithCallbackForMemberDisconnect() throws NacosException { + void testSyncDataWithCallbackForMemberDisconnect() throws NacosException { when(memberManager.hasMember(member.getAddress())).thenReturn(true); when(memberManager.find(member.getAddress())).thenReturn(member); member.setState(NodeState.UP); @@ -182,7 +187,7 @@ public void testSyncDataWithCallbackForMemberDisconnect() throws NacosException } @Test - public void testSyncDataWithCallbackFailure() throws NacosException { + void testSyncDataWithCallbackFailure() throws NacosException { when(memberManager.hasMember(member.getAddress())).thenReturn(true); when(memberManager.find(member.getAddress())).thenReturn(member); member.setState(NodeState.UP); @@ -193,7 +198,7 @@ public void testSyncDataWithCallbackFailure() throws NacosException { } @Test - public void testSyncDataWithCallbackException() throws NacosException { + void testSyncDataWithCallbackException() throws NacosException { when(memberManager.hasMember(member.getAddress())).thenReturn(true); when(memberManager.find(member.getAddress())).thenReturn(member); member.setState(NodeState.UP); @@ -204,7 +209,7 @@ public void testSyncDataWithCallbackException() throws NacosException { } @Test - public void testSyncDataWithCallbackException2() throws NacosException { + void testSyncDataWithCallbackException2() throws NacosException { when(memberManager.hasMember(member.getAddress())).thenReturn(true); when(memberManager.find(member.getAddress())).thenReturn(member); member.setState(NodeState.UP); @@ -219,7 +224,7 @@ public void testSyncDataWithCallbackException2() throws NacosException { } @Test - public void testSyncDataWithCallbackSuccess() throws NacosException { + void testSyncDataWithCallbackSuccess() throws NacosException { when(memberManager.hasMember(member.getAddress())).thenReturn(true); when(memberManager.find(member.getAddress())).thenReturn(member); member.setState(NodeState.UP); @@ -229,7 +234,7 @@ public void testSyncDataWithCallbackSuccess() throws NacosException { } @Test - public void testSyncVerifyDataForMemberNonExist() throws NacosException { + void testSyncVerifyDataForMemberNonExist() throws NacosException { DistroData verifyData = new DistroData(); verifyData.setDistroKey(new DistroKey()); assertTrue(transportAgent.syncVerifyData(verifyData, member.getAddress())); @@ -238,7 +243,7 @@ public void testSyncVerifyDataForMemberNonExist() throws NacosException { } @Test - public void testSyncVerifyDataForMemberUnhealthy() throws NacosException { + void testSyncVerifyDataForMemberUnhealthy() throws NacosException { DistroData verifyData = new DistroData(); verifyData.setDistroKey(new DistroKey()); when(memberManager.hasMember(member.getAddress())).thenReturn(true); @@ -248,7 +253,7 @@ public void testSyncVerifyDataForMemberUnhealthy() throws NacosException { } @Test - public void testSyncVerifyDataForMemberDisconnect() throws NacosException { + void testSyncVerifyDataForMemberDisconnect() throws NacosException { DistroData verifyData = new DistroData(); verifyData.setDistroKey(new DistroKey()); when(memberManager.hasMember(member.getAddress())).thenReturn(true); @@ -259,7 +264,7 @@ public void testSyncVerifyDataForMemberDisconnect() throws NacosException { } @Test - public void testSyncVerifyDataFailure() throws NacosException { + void testSyncVerifyDataFailure() throws NacosException { DistroData verifyData = new DistroData(); verifyData.setDistroKey(new DistroKey()); when(memberManager.hasMember(member.getAddress())).thenReturn(true); @@ -271,7 +276,7 @@ public void testSyncVerifyDataFailure() throws NacosException { } @Test - public void testSyncVerifyDataException() throws NacosException { + void testSyncVerifyDataException() throws NacosException { DistroData verifyData = new DistroData(); verifyData.setDistroKey(new DistroKey()); when(memberManager.hasMember(member.getAddress())).thenReturn(true); @@ -283,7 +288,7 @@ public void testSyncVerifyDataException() throws NacosException { } @Test - public void testSyncVerifyDataSuccess() throws NacosException { + void testSyncVerifyDataSuccess() throws NacosException { DistroData verifyData = new DistroData(); verifyData.setDistroKey(new DistroKey()); when(memberManager.hasMember(member.getAddress())).thenReturn(true); @@ -294,7 +299,7 @@ public void testSyncVerifyDataSuccess() throws NacosException { } @Test - public void testSyncVerifyDataWithCallbackForMemberNonExist() throws NacosException { + void testSyncVerifyDataWithCallbackForMemberNonExist() throws NacosException { DistroData verifyData = new DistroData(); verifyData.setDistroKey(new DistroKey()); transportAgent.syncVerifyData(verifyData, member.getAddress(), distroCallback); @@ -304,7 +309,7 @@ public void testSyncVerifyDataWithCallbackForMemberNonExist() throws NacosExcept } @Test - public void testSyncVerifyDataWithCallbackForMemberUnhealthy() throws NacosException { + void testSyncVerifyDataWithCallbackForMemberUnhealthy() throws NacosException { DistroData verifyData = new DistroData(); verifyData.setDistroKey(new DistroKey()); when(memberManager.hasMember(member.getAddress())).thenReturn(true); @@ -315,7 +320,7 @@ public void testSyncVerifyDataWithCallbackForMemberUnhealthy() throws NacosExcep } @Test - public void testSyncVerifyDataWithCallbackForMemberDisconnect() throws NacosException { + void testSyncVerifyDataWithCallbackForMemberDisconnect() throws NacosException { DistroData verifyData = new DistroData(); verifyData.setDistroKey(new DistroKey()); when(memberManager.hasMember(member.getAddress())).thenReturn(true); @@ -327,7 +332,7 @@ public void testSyncVerifyDataWithCallbackForMemberDisconnect() throws NacosExce } @Test - public void testSyncVerifyDataWithCallbackFailure() throws NacosException { + void testSyncVerifyDataWithCallbackFailure() throws NacosException { DistroData verifyData = new DistroData(); verifyData.setDistroKey(new DistroKey()); when(memberManager.hasMember(member.getAddress())).thenReturn(true); @@ -340,7 +345,7 @@ public void testSyncVerifyDataWithCallbackFailure() throws NacosException { } @Test - public void testSyncVerifyDataWithCallbackException() throws NacosException { + void testSyncVerifyDataWithCallbackException() throws NacosException { DistroData verifyData = new DistroData(); verifyData.setDistroKey(new DistroKey()); when(memberManager.hasMember(member.getAddress())).thenReturn(true); @@ -353,7 +358,7 @@ public void testSyncVerifyDataWithCallbackException() throws NacosException { } @Test - public void testSyncVerifyDataWithCallbackException2() throws NacosException { + void testSyncVerifyDataWithCallbackException2() throws NacosException { DistroData verifyData = new DistroData(); verifyData.setDistroKey(new DistroKey()); when(memberManager.hasMember(member.getAddress())).thenReturn(true); @@ -370,7 +375,7 @@ public void testSyncVerifyDataWithCallbackException2() throws NacosException { } @Test - public void testSyncVerifyDataWithCallbackSuccess() throws NacosException { + void testSyncVerifyDataWithCallbackSuccess() throws NacosException { DistroData verifyData = new DistroData(); verifyData.setDistroKey(new DistroKey()); when(memberManager.hasMember(member.getAddress())).thenReturn(true); @@ -381,89 +386,109 @@ public void testSyncVerifyDataWithCallbackSuccess() throws NacosException { verify(distroCallback).onSuccess(); } - @Test(expected = DistroException.class) - public void testGetDataForMemberNonExist() { - transportAgent.getData(new DistroKey(), member.getAddress()); + @Test + void testGetDataForMemberNonExist() { + assertThrows(DistroException.class, () -> { + transportAgent.getData(new DistroKey(), member.getAddress()); + }); } - @Test(expected = DistroException.class) - public void testGetDataForMemberUnhealthy() { - when(memberManager.find(member.getAddress())).thenReturn(member); - transportAgent.getData(new DistroKey(), member.getAddress()); + @Test + void testGetDataForMemberUnhealthy() { + assertThrows(DistroException.class, () -> { + when(memberManager.find(member.getAddress())).thenReturn(member); + transportAgent.getData(new DistroKey(), member.getAddress()); + }); } - @Test(expected = DistroException.class) - public void testGetDataForMemberDisconnect() { - when(memberManager.find(member.getAddress())).thenReturn(member); - member.setState(NodeState.UP); - transportAgent.getData(new DistroKey(), member.getAddress()); + @Test + void testGetDataForMemberDisconnect() { + assertThrows(DistroException.class, () -> { + when(memberManager.find(member.getAddress())).thenReturn(member); + member.setState(NodeState.UP); + transportAgent.getData(new DistroKey(), member.getAddress()); + }); } - @Test(expected = DistroException.class) - public void testGetDataException() throws NacosException { - when(memberManager.find(member.getAddress())).thenReturn(member); - member.setState(NodeState.UP); - when(clusterRpcClientProxy.isRunning(member)).thenReturn(true); - when(clusterRpcClientProxy.sendRequest(eq(member), any())).thenThrow(new NacosException()); - transportAgent.getData(new DistroKey(), member.getAddress()); + @Test + void testGetDataException() throws NacosException { + assertThrows(DistroException.class, () -> { + when(memberManager.find(member.getAddress())).thenReturn(member); + member.setState(NodeState.UP); + when(clusterRpcClientProxy.isRunning(member)).thenReturn(true); + when(clusterRpcClientProxy.sendRequest(eq(member), any())).thenThrow(new NacosException()); + transportAgent.getData(new DistroKey(), member.getAddress()); + }); } - @Test(expected = DistroException.class) - public void testGetDataFailure() { - when(memberManager.find(member.getAddress())).thenReturn(member); - member.setState(NodeState.UP); - when(clusterRpcClientProxy.isRunning(member)).thenReturn(true); - response.setErrorInfo(ResponseCode.FAIL.getCode(), "TEST"); - transportAgent.getData(new DistroKey(), member.getAddress()); + @Test + void testGetDataFailure() { + assertThrows(DistroException.class, () -> { + when(memberManager.find(member.getAddress())).thenReturn(member); + member.setState(NodeState.UP); + when(clusterRpcClientProxy.isRunning(member)).thenReturn(true); + response.setErrorInfo(ResponseCode.FAIL.getCode(), "TEST"); + transportAgent.getData(new DistroKey(), member.getAddress()); + }); } @Test - public void testGetDataSuccess() { + void testGetDataSuccess() { when(memberManager.find(member.getAddress())).thenReturn(member); member.setState(NodeState.UP); when(clusterRpcClientProxy.isRunning(member)).thenReturn(true); transportAgent.getData(new DistroKey(), member.getAddress()); } - @Test(expected = DistroException.class) - public void testGetDatumSnapshotForMemberNonExist() { - transportAgent.getDatumSnapshot(member.getAddress()); + @Test + void testGetDatumSnapshotForMemberNonExist() { + assertThrows(DistroException.class, () -> { + transportAgent.getDatumSnapshot(member.getAddress()); + }); } - @Test(expected = DistroException.class) - public void testGetDatumSnapshotForMemberUnhealthy() { - when(memberManager.find(member.getAddress())).thenReturn(member); - transportAgent.getDatumSnapshot(member.getAddress()); + @Test + void testGetDatumSnapshotForMemberUnhealthy() { + assertThrows(DistroException.class, () -> { + when(memberManager.find(member.getAddress())).thenReturn(member); + transportAgent.getDatumSnapshot(member.getAddress()); + }); } - @Test(expected = DistroException.class) - public void testGetDatumSnapshotForMemberDisconnect() { - when(memberManager.find(member.getAddress())).thenReturn(member); - member.setState(NodeState.UP); - transportAgent.getDatumSnapshot(member.getAddress()); + @Test + void testGetDatumSnapshotForMemberDisconnect() { + assertThrows(DistroException.class, () -> { + when(memberManager.find(member.getAddress())).thenReturn(member); + member.setState(NodeState.UP); + transportAgent.getDatumSnapshot(member.getAddress()); + }); } - @Test(expected = DistroException.class) - public void testGetDatumSnapshotException() throws NacosException { - when(memberManager.find(member.getAddress())).thenReturn(member); - member.setState(NodeState.UP); - when(clusterRpcClientProxy.isRunning(member)).thenReturn(true); - when(clusterRpcClientProxy.sendRequest(eq(member), any(), any(Long.class))).thenThrow(new NacosException()); - transportAgent.getDatumSnapshot(member.getAddress()); + @Test + void testGetDatumSnapshotException() throws NacosException { + assertThrows(DistroException.class, () -> { + when(memberManager.find(member.getAddress())).thenReturn(member); + member.setState(NodeState.UP); + when(clusterRpcClientProxy.isRunning(member)).thenReturn(true); + when(clusterRpcClientProxy.sendRequest(eq(member), any(), any(Long.class))).thenThrow(new NacosException()); + transportAgent.getDatumSnapshot(member.getAddress()); + }); } - @Test(expected = DistroException.class) - public void testGetDatumSnapshotFailure() throws NacosException { - when(memberManager.find(member.getAddress())).thenReturn(member); - member.setState(NodeState.UP); - when(clusterRpcClientProxy.isRunning(member)).thenReturn(true); - when(clusterRpcClientProxy.sendRequest(eq(member), any(), any(Long.class))).thenReturn(response); - response.setErrorInfo(ResponseCode.FAIL.getCode(), "TEST"); - transportAgent.getDatumSnapshot(member.getAddress()); + @Test + void testGetDatumSnapshotFailure() throws NacosException { + assertThrows(DistroException.class, () -> { + when(memberManager.find(member.getAddress())).thenReturn(member); + member.setState(NodeState.UP); + when(clusterRpcClientProxy.isRunning(member)).thenReturn(true); + when(clusterRpcClientProxy.sendRequest(eq(member), any(), any(Long.class))).thenReturn(response); + response.setErrorInfo(ResponseCode.FAIL.getCode(), "TEST"); + transportAgent.getDatumSnapshot(member.getAddress()); + }); } @Test - public void testGetDatumSnapshotSuccess() throws NacosException { + void testGetDatumSnapshotSuccess() throws NacosException { when(memberManager.find(member.getAddress())).thenReturn(member); member.setState(NodeState.UP); when(clusterRpcClientProxy.isRunning(member)).thenReturn(true); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/consistency/persistent/impl/NamingKvStorageTest.java b/naming/src/test/java/com/alibaba/nacos/naming/consistency/persistent/impl/NamingKvStorageTest.java deleted file mode 100644 index 34d29dd6c1b..00000000000 --- a/naming/src/test/java/com/alibaba/nacos/naming/consistency/persistent/impl/NamingKvStorageTest.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.naming.consistency.persistent.impl; - -import com.alibaba.nacos.core.exception.KvStorageException; -import com.alibaba.nacos.core.storage.kv.FileKvStorage; -import com.alibaba.nacos.sys.utils.DiskUtils; -import junit.framework.TestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import java.io.IOException; -import java.lang.reflect.Field; - -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -@RunWith(MockitoJUnitRunner.class) -public class NamingKvStorageTest extends TestCase { - - private NamingKvStorage namingKvStorage; - - @Mock - private FileKvStorage baseDirStorageMock; - - private final byte[] key = "fileName_test".getBytes(); - - private final String str = "str_test"; - - @Before - public void setUp() throws Exception { - super.setUp(); - namingKvStorage = new NamingKvStorage("baseDir_test"); - - Field baseDirStorageField = NamingKvStorage.class.getDeclaredField("baseDirStorage"); - baseDirStorageField.setAccessible(true); - baseDirStorageField.set(namingKvStorage, baseDirStorageMock); - - when(baseDirStorageMock.get(key)).thenReturn(null); - } - - @After - public void tearDown() throws IOException { - DiskUtils.deleteDirectory("baseDir_test"); - } - - @Test - public void testGet() throws KvStorageException { - namingKvStorage.get(key); - verify(baseDirStorageMock).get(key); - } - - @Test - public void testPut() throws KvStorageException { - byte[] value = "value_test".getBytes(); - namingKvStorage.put(key, value); - verify(baseDirStorageMock).put(key, value); - } - - @Test - public void testDelete() throws KvStorageException { - namingKvStorage.delete(key); - verify(baseDirStorageMock).delete(key); - } - - @Test - public void testDoSnapshot() throws KvStorageException { - namingKvStorage.doSnapshot(str); - verify(baseDirStorageMock).doSnapshot(str); - } - - @Test - public void testSnapshotLoad() throws KvStorageException { - namingKvStorage.snapshotLoad(str); - verify(baseDirStorageMock).snapshotLoad(str); - } -} diff --git a/naming/src/test/java/com/alibaba/nacos/naming/consistency/persistent/impl/NamingSnapshotOperationTest.java b/naming/src/test/java/com/alibaba/nacos/naming/consistency/persistent/impl/NamingSnapshotOperationTest.java deleted file mode 100644 index 62e6ffda179..00000000000 --- a/naming/src/test/java/com/alibaba/nacos/naming/consistency/persistent/impl/NamingSnapshotOperationTest.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.naming.consistency.persistent.impl; - -import com.alibaba.nacos.consistency.Serializer; -import com.alibaba.nacos.consistency.snapshot.Reader; -import com.alibaba.nacos.consistency.snapshot.Writer; -import com.alibaba.nacos.core.distributed.raft.RaftConfig; -import com.alibaba.nacos.core.distributed.raft.utils.RaftExecutor; -import com.alibaba.nacos.core.storage.kv.KvStorage; -import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.mock.env.MockEnvironment; - -import java.nio.file.Paths; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doAnswer; - -@RunWith(MockitoJUnitRunner.class) -public class NamingSnapshotOperationTest { - - static { - RaftExecutor.init(new RaftConfig()); - EnvUtil.setEnvironment(new MockEnvironment()); - } - - @Mock - private KvStorage storage; - - private final String snapshotDir = Paths.get(EnvUtil.getNacosTmpDir(), "rocks_snapshot_test").toString(); - - private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); - - private boolean isSnapshoted = false; - - @Before - public void init() throws Exception { - doAnswer(invocationOnMock -> { - isSnapshoted = true; - return null; - }).when(storage).doSnapshot(any(String.class)); - } - - @After - public void after() { - storage.shutdown(); - } - - @Test - public void testNamingSnapshot() throws InterruptedException { - AtomicBoolean result = new AtomicBoolean(false); - NamingSnapshotOperation operation = new NamingSnapshotOperation(storage, lock, Mockito.mock(Serializer.class)); - final Writer writer = new Writer(snapshotDir); - final CountDownLatch latch = new CountDownLatch(1); - - operation.onSnapshotSave(writer, (isOk, throwable) -> { - result.set(isOk && throwable == null); - latch.countDown(); - }); - latch.await(10, TimeUnit.SECONDS); - Assert.assertTrue(isSnapshoted); - Assert.assertTrue(result.get()); - - final Reader reader = new Reader(snapshotDir, writer.listFiles()); - boolean res = operation.onSnapshotLoad(reader); - Assert.assertTrue(res); - } - -} diff --git a/naming/src/test/java/com/alibaba/nacos/naming/controllers/CatalogControllerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/controllers/CatalogControllerTest.java index 9ced04c69d4..fbc8ffaab78 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/controllers/CatalogControllerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/controllers/CatalogControllerTest.java @@ -21,24 +21,24 @@ import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.naming.core.CatalogServiceV2Impl; import com.fasterxml.jackson.databind.node.ObjectNode; -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.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.ArrayList; import java.util.Collections; import java.util.List; -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; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class CatalogControllerTest { +@ExtendWith(MockitoExtension.class) +class CatalogControllerTest { private static final String TEST_CLUSTER_NAME = "test-cluster"; @@ -52,31 +52,29 @@ public class CatalogControllerTest { @InjectMocks private CatalogController catalogController; - @Before - public void setUp() throws NoSuchFieldException, IllegalAccessException, NacosException { + @BeforeEach + void setUp() throws NoSuchFieldException, IllegalAccessException, NacosException { } @Test - public void testServiceDetail() throws Exception { + void testServiceDetail() throws Exception { Object expected = new Object(); - when(catalogServiceV2.getServiceDetail(Constants.DEFAULT_NAMESPACE_ID, TEST_GROUP_NAME, TEST_SERVICE_NAME)) - .thenReturn(expected); + when(catalogServiceV2.getServiceDetail(Constants.DEFAULT_NAMESPACE_ID, TEST_GROUP_NAME, TEST_SERVICE_NAME)).thenReturn(expected); Object actual = catalogController.serviceDetail(Constants.DEFAULT_NAMESPACE_ID, TEST_GROUP_NAME + Constants.SERVICE_INFO_SPLITER + TEST_SERVICE_NAME); assertEquals(expected, actual); } @Test - public void testInstanceList() throws NacosException { + void testInstanceList() throws NacosException { Instance instance = new Instance(); instance.setIp("1.1.1.1"); instance.setPort(1234); instance.setClusterName(TEST_CLUSTER_NAME); List list = new ArrayList<>(1); list.add(instance); - when(catalogServiceV2 - .listInstances(Constants.DEFAULT_NAMESPACE_ID, TEST_GROUP_NAME, TEST_SERVICE_NAME, TEST_CLUSTER_NAME)) - .thenReturn(list); + when(catalogServiceV2.listInstances(Constants.DEFAULT_NAMESPACE_ID, TEST_GROUP_NAME, TEST_SERVICE_NAME, + TEST_CLUSTER_NAME)).thenReturn(list); ObjectNode result = catalogController.instanceList(Constants.DEFAULT_NAMESPACE_ID, TEST_GROUP_NAME + Constants.SERVICE_INFO_SPLITER + TEST_SERVICE_NAME, TEST_CLUSTER_NAME, 1, 10); String actual = result.toString(); @@ -88,19 +86,17 @@ public void testInstanceList() throws NacosException { } @Test - public void testListDetail() { + void testListDetail() { try { - when(catalogServiceV2 - .pageListServiceDetail(Constants.DEFAULT_NAMESPACE_ID, TEST_GROUP_NAME, TEST_SERVICE_NAME, 1, 10)) - .thenReturn(Collections.emptyList()); - Object res = catalogController - .listDetail(true, Constants.DEFAULT_NAMESPACE_ID, 1, 10, TEST_SERVICE_NAME, TEST_GROUP_NAME, null, - true); - Assert.assertTrue(res instanceof List); - Assert.assertEquals(0, ((List) res).size()); + when(catalogServiceV2.pageListServiceDetail(Constants.DEFAULT_NAMESPACE_ID, TEST_GROUP_NAME, TEST_SERVICE_NAME, 1, + 10)).thenReturn(Collections.emptyList()); + Object res = catalogController.listDetail(true, Constants.DEFAULT_NAMESPACE_ID, 1, 10, TEST_SERVICE_NAME, TEST_GROUP_NAME, null, + true); + assertTrue(res instanceof List); + assertEquals(0, ((List) res).size()); } catch (NacosException e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/controllers/ClusterControllerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/controllers/ClusterControllerTest.java index bc012caf62f..229ed92d157 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/controllers/ClusterControllerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/controllers/ClusterControllerTest.java @@ -20,22 +20,26 @@ import com.alibaba.nacos.naming.BaseTest; import com.alibaba.nacos.naming.core.ClusterOperatorV2Impl; import com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata; -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 javax.servlet.http.HttpServletRequest; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class ClusterControllerTest extends BaseTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class ClusterControllerTest extends BaseTest { @Mock private ClusterOperatorV2Impl clusterOperatorV2; @@ -45,14 +49,14 @@ public class ClusterControllerTest extends BaseTest { private ClusterController clusterController; - @Before + @BeforeEach public void before() { super.before(); clusterController = new ClusterController(clusterOperatorV2); } @Test - public void testUpdate() throws Exception { + void testUpdate() throws Exception { mockRequestParameter(CommonParams.NAMESPACE_ID, "test-namespace"); mockRequestParameter(CommonParams.CLUSTER_NAME, TEST_CLUSTER_NAME); mockRequestParameter(CommonParams.SERVICE_NAME, TEST_SERVICE_NAME); @@ -60,9 +64,8 @@ public void testUpdate() throws Exception { mockRequestParameter("useInstancePort4Check", "true"); mockRequestParameter("healthChecker", "{\"type\":\"HTTP\"}"); assertEquals("ok", clusterController.update(request)); - verify(clusterOperatorV2) - .updateClusterMetadata(eq("test-namespace"), eq(TEST_SERVICE_NAME), eq(TEST_CLUSTER_NAME), - any(ClusterMetadata.class)); + verify(clusterOperatorV2).updateClusterMetadata(eq("test-namespace"), eq(TEST_SERVICE_NAME), eq(TEST_CLUSTER_NAME), + any(ClusterMetadata.class)); } private void mockRequestParameter(String paramKey, String value) { diff --git a/naming/src/test/java/com/alibaba/nacos/naming/controllers/HealthControllerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/controllers/HealthControllerTest.java index d069e14f766..9d9911fd0a4 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/controllers/HealthControllerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/controllers/HealthControllerTest.java @@ -22,25 +22,27 @@ import com.alibaba.nacos.naming.constants.RequestConstant; import com.alibaba.nacos.naming.core.HealthOperatorV2Impl; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.ResponseEntity; import org.springframework.mock.env.MockEnvironment; import org.springframework.mock.web.MockHttpServletRequest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + /** * {@link HealthController} unit test. * * @author chenglu * @date 2021-07-21 19:19 */ -@RunWith(MockitoJUnitRunner.class) -public class HealthControllerTest { +@ExtendWith(MockitoExtension.class) +class HealthControllerTest { @InjectMocks private HealthController healthController; @@ -48,19 +50,19 @@ public class HealthControllerTest { @Mock private HealthOperatorV2Impl healthOperatorV2; - @Before - public void setUp() { + @BeforeEach + void setUp() { EnvUtil.setEnvironment(new MockEnvironment()); } @Test - public void testServer() { + void testServer() { ResponseEntity responseEntity = healthController.server(); - Assert.assertEquals(200, responseEntity.getStatusCodeValue()); + assertEquals(200, responseEntity.getStatusCodeValue()); } @Test - public void testUpdate() { + void testUpdate() { MockHttpServletRequest servletRequest = new MockHttpServletRequest(); servletRequest.addParameter(CommonParams.SERVICE_NAME, "test"); servletRequest.addParameter(RequestConstant.IP_KEY, "1.1.1.1"); @@ -69,16 +71,16 @@ public void testUpdate() { try { ResponseEntity responseEntity = healthController.update(servletRequest); - Assert.assertEquals(200, responseEntity.getStatusCodeValue()); + assertEquals(200, responseEntity.getStatusCodeValue()); } catch (NacosException e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } @Test - public void testCheckers() { + void testCheckers() { ResponseEntity responseEntity = healthController.checkers(); - Assert.assertEquals(200, responseEntity.getStatusCodeValue()); + assertEquals(200, responseEntity.getStatusCodeValue()); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/controllers/InstanceControllerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/controllers/InstanceControllerTest.java index 47fd5a3a22f..dec63c556f6 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/controllers/InstanceControllerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/controllers/InstanceControllerTest.java @@ -34,13 +34,15 @@ import com.alibaba.nacos.naming.misc.UtilsAndCommons; import com.alibaba.nacos.naming.pojo.Subscriber; import com.fasterxml.jackson.databind.node.ObjectNode; -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.InjectMocks; 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 javax.servlet.http.HttpServletRequest; import java.util.Collections; @@ -48,16 +50,18 @@ import java.util.List; import java.util.concurrent.TimeUnit; -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; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class InstanceControllerTest extends BaseTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class InstanceControllerTest extends BaseTest { @Mock private InstanceOperatorClientImpl instanceServiceV2; @@ -72,7 +76,7 @@ public class InstanceControllerTest extends BaseTest { private volatile Class eventReceivedClass; - @Before + @BeforeEach public void before() { super.before(); when(switchDomain.isDefaultInstanceEphemeral()).thenReturn(true); @@ -97,8 +101,8 @@ public void onEvent(Event event) { mockRequestParameter("port", "3306"); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { NotifyCenter.deregisterSubscriber(subscriber); NotifyCenter.deregisterPublisher(RegisterInstanceTraceEvent.class); NotifyCenter.deregisterPublisher(DeregisterInstanceTraceEvent.class); @@ -111,34 +115,34 @@ private void mockRequestParameter(String key, String value) { } @Test - public void testRegister() throws Exception { + void testRegister() throws Exception { assertEquals("ok", instanceController.register(request)); - verify(instanceServiceV2).registerInstance(eq(Constants.DEFAULT_NAMESPACE_ID), - eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), any(Instance.class)); + verify(instanceServiceV2).registerInstance(eq(Constants.DEFAULT_NAMESPACE_ID), eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), + any(Instance.class)); TimeUnit.SECONDS.sleep(1); - assertEquals(eventReceivedClass, RegisterInstanceTraceEvent.class); + assertEquals(RegisterInstanceTraceEvent.class, eventReceivedClass); } @Test - public void testDeregister() throws Exception { + void testDeregister() throws Exception { assertEquals("ok", instanceController.deregister(request)); - verify(instanceServiceV2).removeInstance(eq(Constants.DEFAULT_NAMESPACE_ID), - eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), any(Instance.class)); + verify(instanceServiceV2).removeInstance(eq(Constants.DEFAULT_NAMESPACE_ID), eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), + any(Instance.class)); TimeUnit.SECONDS.sleep(1); - assertEquals(eventReceivedClass, DeregisterInstanceTraceEvent.class); + assertEquals(DeregisterInstanceTraceEvent.class, eventReceivedClass); } @Test - public void testUpdate() throws Exception { + void testUpdate() throws Exception { assertEquals("ok", instanceController.update(request)); - verify(instanceServiceV2).updateInstance(eq(Constants.DEFAULT_NAMESPACE_ID), - eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), any(Instance.class)); + verify(instanceServiceV2).updateInstance(eq(Constants.DEFAULT_NAMESPACE_ID), eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), + any(Instance.class)); TimeUnit.SECONDS.sleep(1); - assertEquals(eventReceivedClass, UpdateInstanceTraceEvent.class); + assertEquals(UpdateInstanceTraceEvent.class, eventReceivedClass); } @Test - public void testBatchUpdateInstanceMetadata() throws Exception { + void testBatchUpdateInstanceMetadata() throws Exception { Instance instance = new Instance(); instance.setIp("1.1.1.1"); instance.setPort(3306); @@ -153,7 +157,7 @@ public void testBatchUpdateInstanceMetadata() throws Exception { } @Test - public void testBatchDeleteInstanceMetadata() throws Exception { + void testBatchDeleteInstanceMetadata() throws Exception { mockRequestParameter("metadata", "{}"); when(instanceServiceV2.batchDeleteMetadata(eq(Constants.DEFAULT_NAMESPACE_ID), any(), anyMap())).thenReturn( Collections.singletonList("1.1.1.1:3306:unknown:DEFAULT:ephemeral")); @@ -162,32 +166,31 @@ public void testBatchDeleteInstanceMetadata() throws Exception { } @Test - public void testPatch() throws Exception { + void testPatch() throws Exception { mockRequestParameter("metadata", "{}"); mockRequestParameter("app", "test"); mockRequestParameter("weight", "10"); mockRequestParameter("healthy", "false"); mockRequestParameter("enabled", "false"); assertEquals("ok", instanceController.patch(request)); - verify(instanceServiceV2).patchInstance(eq(Constants.DEFAULT_NAMESPACE_ID), - eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), any(InstancePatchObject.class)); + verify(instanceServiceV2).patchInstance(eq(Constants.DEFAULT_NAMESPACE_ID), eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), + any(InstancePatchObject.class)); } @Test - public void testList() throws Exception { + void testList() throws Exception { Instance instance = new Instance(); instance.setIp("1.1.1.1"); instance.setPort(3306); ServiceInfo expected = new ServiceInfo(); expected.setHosts(Collections.singletonList(instance)); - when(instanceServiceV2.listInstance(eq(Constants.DEFAULT_NAMESPACE_ID), - eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), any(Subscriber.class), eq(StringUtils.EMPTY), - eq(false))).thenReturn(expected); + when(instanceServiceV2.listInstance(eq(Constants.DEFAULT_NAMESPACE_ID), eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), + any(Subscriber.class), eq(StringUtils.EMPTY), eq(false))).thenReturn(expected); assertEquals(expected, instanceController.list(request)); } @Test - public void testDetail() throws Exception { + void testDetail() throws Exception { Instance instance = new Instance(); instance.setIp("1.1.1.1"); instance.setPort(3306); @@ -207,13 +210,11 @@ public void testDetail() throws Exception { } @Test - public void testBeat() throws Exception { - when(instanceServiceV2.handleBeat(eq(Constants.DEFAULT_NAMESPACE_ID), - eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), eq("1.1.1.1"), eq(3306), - eq(UtilsAndCommons.DEFAULT_CLUSTER_NAME), any(), any())).thenReturn(200); - when(instanceServiceV2.getHeartBeatInterval(eq(Constants.DEFAULT_NAMESPACE_ID), - eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), eq("1.1.1.1"), eq(3306), - eq(UtilsAndCommons.DEFAULT_CLUSTER_NAME))).thenReturn(10000L); + void testBeat() throws Exception { + when(instanceServiceV2.handleBeat(eq(Constants.DEFAULT_NAMESPACE_ID), eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), eq("1.1.1.1"), + eq(3306), eq(UtilsAndCommons.DEFAULT_CLUSTER_NAME), any(), any())).thenReturn(200); + when(instanceServiceV2.getHeartBeatInterval(eq(Constants.DEFAULT_NAMESPACE_ID), eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), + eq("1.1.1.1"), eq(3306), eq(UtilsAndCommons.DEFAULT_CLUSTER_NAME))).thenReturn(10000L); ObjectNode actual = instanceController.beat(request); assertEquals(200, actual.get("code").intValue()); assertEquals(10000L, actual.get("clientBeatInterval").longValue()); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/controllers/OperatorControllerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/controllers/OperatorControllerTest.java index 884cfcc9515..8ffac7f1072 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/controllers/OperatorControllerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/controllers/OperatorControllerTest.java @@ -31,28 +31,31 @@ import com.alibaba.nacos.sys.env.Constants; import com.alibaba.nacos.sys.env.EnvUtil; import com.fasterxml.jackson.databind.node.ObjectNode; -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.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.env.MockEnvironment; import org.springframework.mock.web.MockHttpServletRequest; import java.util.Collection; import java.util.HashSet; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + /** * {@link OperatorController} unit test. * * @author chenglu * @date 2021-07-21 19:28 */ -@RunWith(MockitoJUnitRunner.class) -public class OperatorControllerTest { +@ExtendWith(MockitoExtension.class) +class OperatorControllerTest { @InjectMocks private OperatorController operatorController; @@ -72,39 +75,39 @@ public class OperatorControllerTest { @Mock private DistroMapper distroMapper; - @Before - public void setUp() { + @BeforeEach + void setUp() { MockEnvironment environment = new MockEnvironment(); environment.setProperty(Constants.SUPPORT_UPGRADE_FROM_1X, "true"); EnvUtil.setEnvironment(environment); } @Test - public void testPushState() { + void testPushState() { MetricsMonitor.resetPush(); ObjectNode objectNode = operatorController.pushState(true, true); - Assert.assertTrue(objectNode.toString().contains("succeed\":0")); + assertTrue(objectNode.toString().contains("succeed\":0")); } @Test - public void testSwitchDomain() { + void testSwitchDomain() { SwitchDomain switchDomain = operatorController.switches(new MockHttpServletRequest()); - Assert.assertEquals(this.switchDomain, switchDomain); + assertEquals(this.switchDomain, switchDomain); } @Test - public void testUpdateSwitch() { + void testUpdateSwitch() { try { String res = operatorController.updateSwitch(true, "test", "test"); - Assert.assertEquals("ok", res); + assertEquals("ok", res); } catch (Exception e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } @Test - public void testMetrics() { + void testMetrics() { Mockito.when(serverStatusManager.getServerStatus()).thenReturn(ServerStatus.UP); Collection clients = new HashSet<>(); clients.add("1628132208793_127.0.0.1_8080"); @@ -120,25 +123,25 @@ public void testMetrics() { servletRequest.addParameter("onlyStatus", "false"); ObjectNode objectNode = operatorController.metrics(servletRequest); - Assert.assertEquals(1, objectNode.get("responsibleInstanceCount").asInt()); - Assert.assertEquals(ServerStatus.UP.toString(), objectNode.get("status").asText()); - Assert.assertEquals(3, objectNode.get("clientCount").asInt()); - Assert.assertEquals(1, objectNode.get("connectionBasedClientCount").asInt()); - Assert.assertEquals(1, objectNode.get("ephemeralIpPortClientCount").asInt()); - Assert.assertEquals(1, objectNode.get("persistentIpPortClientCount").asInt()); - Assert.assertEquals(1, objectNode.get("responsibleClientCount").asInt()); + assertEquals(1, objectNode.get("responsibleInstanceCount").asInt()); + assertEquals(ServerStatus.UP.toString(), objectNode.get("status").asText()); + assertEquals(3, objectNode.get("clientCount").asInt()); + assertEquals(1, objectNode.get("connectionBasedClientCount").asInt()); + assertEquals(1, objectNode.get("ephemeralIpPortClientCount").asInt()); + assertEquals(1, objectNode.get("persistentIpPortClientCount").asInt()); + assertEquals(1, objectNode.get("responsibleClientCount").asInt()); } @Test - public void testGetResponsibleServer4Client() { + void testGetResponsibleServer4Client() { Mockito.when(distroMapper.mapSrv(Mockito.anyString())).thenReturn("test"); ObjectNode objectNode = operatorController.getResponsibleServer4Client("test", "test"); - Assert.assertEquals("test", objectNode.get("responsibleServer").asText()); + assertEquals("test", objectNode.get("responsibleServer").asText()); } @Test - public void testSetLogLevel() { + void testSetLogLevel() { String res = operatorController.setLogLevel("test", "info"); - Assert.assertEquals("ok", res); + assertEquals("ok", res); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/controllers/ServiceControllerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/controllers/ServiceControllerTest.java index ca54a97d3c6..0a62348116c 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/controllers/ServiceControllerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/controllers/ServiceControllerTest.java @@ -27,15 +27,14 @@ import com.alibaba.nacos.naming.core.SubscribeManager; import com.alibaba.nacos.naming.pojo.Subscriber; import com.fasterxml.jackson.databind.node.ObjectNode; -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.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockHttpServletRequest; import java.util.Arrays; @@ -44,10 +43,11 @@ import java.util.List; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; -@RunWith(MockitoJUnitRunner.class) -public class ServiceControllerTest extends BaseTest { +@ExtendWith(MockitoExtension.class) +class ServiceControllerTest extends BaseTest { @InjectMocks private ServiceController serviceController; @@ -62,7 +62,7 @@ public class ServiceControllerTest extends BaseTest { private volatile Class eventReceivedClass; - @Before + @BeforeEach public void before() { super.before(); subscriber = new SmartSubscriber() { @@ -81,15 +81,15 @@ public void onEvent(Event event) { NotifyCenter.registerSubscriber(subscriber); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { NotifyCenter.deregisterSubscriber(subscriber); NotifyCenter.deregisterPublisher(UpdateServiceTraceEvent.class); eventReceivedClass = null; } @Test - public void testList() throws Exception { + void testList() throws Exception { Mockito.when(serviceOperatorV2.listService(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Collections.singletonList("DEFAULT_GROUP@@providers:com.alibaba.nacos.controller.test:1")); @@ -99,72 +99,72 @@ public void testList() throws Exception { servletRequest.addParameter("pageSize", "10"); ObjectNode objectNode = serviceController.list(servletRequest); - Assert.assertEquals(1, objectNode.get("count").asInt()); + assertEquals(1, objectNode.get("count").asInt()); } @Test - public void testCreate() { + void testCreate() { try { String res = serviceController.create(TEST_NAMESPACE, TEST_SERVICE_NAME, 0, "", ""); - Assert.assertEquals("ok", res); + assertEquals("ok", res); } catch (Exception e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } @Test - public void testRemove() { + void testRemove() { try { String res = serviceController.remove(TEST_NAMESPACE, TEST_SERVICE_NAME); - Assert.assertEquals("ok", res); + assertEquals("ok", res); } catch (Exception e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } @Test - public void testDetail() { + void testDetail() { try { ObjectNode result = Mockito.mock(ObjectNode.class); Mockito.when(serviceOperatorV2.queryService(Mockito.anyString(), Mockito.anyString())).thenReturn(result); ObjectNode objectNode = serviceController.detail(TEST_NAMESPACE, TEST_SERVICE_NAME); - Assert.assertEquals(result, objectNode); + assertEquals(result, objectNode); } catch (NacosException e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } @Test - public void testUpdate() throws Exception { + void testUpdate() throws Exception { MockHttpServletRequest servletRequest = new MockHttpServletRequest(); servletRequest.addParameter(CommonParams.SERVICE_NAME, TEST_SERVICE_NAME); servletRequest.addParameter("protectThreshold", "0.01"); try { String res = serviceController.update(servletRequest); - Assert.assertEquals("ok", res); + assertEquals("ok", res); } catch (Exception e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } TimeUnit.SECONDS.sleep(1); - assertEquals(eventReceivedClass, UpdateServiceTraceEvent.class); + assertEquals(UpdateServiceTraceEvent.class, eventReceivedClass); } @Test - public void testSearchService() { + void testSearchService() { try { Mockito.when(serviceOperatorV2.searchServiceName(Mockito.anyString(), Mockito.anyString())) .thenReturn(Collections.singletonList("result")); ObjectNode objectNode = serviceController.searchService(TEST_NAMESPACE, ""); - Assert.assertEquals(1, objectNode.get("count").asInt()); + assertEquals(1, objectNode.get("count").asInt()); } catch (NacosException e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } try { @@ -173,15 +173,15 @@ public void testSearchService() { Mockito.when(serviceOperatorV2.listAllNamespace()).thenReturn(Arrays.asList("re1", "re2")); ObjectNode objectNode = serviceController.searchService(null, ""); - Assert.assertEquals(4, objectNode.get("count").asInt()); + assertEquals(4, objectNode.get("count").asInt()); } catch (NacosException e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } @Test - public void testSubscribers() { + void testSubscribers() { Mockito.when(subscribeManager.getSubscribers(Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean())) .thenReturn(Collections.singletonList(Mockito.mock(Subscriber.class))); @@ -189,6 +189,6 @@ public void testSubscribers() { servletRequest.addParameter(CommonParams.SERVICE_NAME, TEST_SERVICE_NAME); ObjectNode objectNode = serviceController.subscribers(servletRequest); - Assert.assertEquals(1, objectNode.get("count").asInt()); + assertEquals(1, objectNode.get("count").asInt()); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/CatalogControllerV2Test.java b/naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/CatalogControllerV2Test.java index feca56a4090..bff7397348a 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/CatalogControllerV2Test.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/CatalogControllerV2Test.java @@ -24,13 +24,12 @@ import com.alibaba.nacos.naming.core.CatalogServiceV2Impl; import com.alibaba.nacos.naming.misc.UtilsAndCommons; import com.fasterxml.jackson.databind.JsonNode; -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.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; @@ -40,10 +39,13 @@ import java.util.ArrayList; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class CatalogControllerV2Test extends BaseTest { +@ExtendWith(MockitoExtension.class) +class CatalogControllerV2Test extends BaseTest { + + List instances; @Mock private CatalogServiceV2Impl catalogServiceV2; @@ -53,9 +55,7 @@ public class CatalogControllerV2Test extends BaseTest { private MockMvc mockmvc; - List instances; - - @Before + @BeforeEach public void before() { Instance instance = new Instance(); instance.setIp("1.1.1.1"); @@ -69,18 +69,17 @@ public void before() { } @Test - public void testInstanceList() throws Exception { + void testInstanceList() throws Exception { String serviceNameWithoutGroup = NamingUtils.getServiceName(TEST_SERVICE_NAME); String groupName = NamingUtils.getGroupName(TEST_SERVICE_NAME); - when(catalogServiceV2.listAllInstances(Constants.DEFAULT_NAMESPACE_ID, groupName, - serviceNameWithoutGroup)).thenReturn(instances); + when(catalogServiceV2.listAllInstances(Constants.DEFAULT_NAMESPACE_ID, groupName, serviceNameWithoutGroup)).thenReturn(instances); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get( - UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + UtilsAndCommons.NACOS_NAMING_CATALOG_CONTEXT - + "/instances").param("namespaceId", Constants.DEFAULT_NAMESPACE_ID) - .param("serviceName", TEST_SERVICE_NAME).param("pageNo", "1").param("pageSize", "100"); + UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + UtilsAndCommons.NACOS_NAMING_CATALOG_CONTEXT + "/instances") + .param("namespaceId", Constants.DEFAULT_NAMESPACE_ID).param("serviceName", TEST_SERVICE_NAME).param("pageNo", "1") + .param("pageSize", "100"); MockHttpServletResponse response = mockmvc.perform(builder).andReturn().getResponse(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); JsonNode data = JacksonUtils.toObj(response.getContentAsString()).get("data").get("instances"); - Assert.assertEquals(instances.size(), data.size()); + assertEquals(instances.size(), data.size()); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/ClientInfoControllerV2Test.java b/naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/ClientInfoControllerV2Test.java index 73795ee9c9d..5eae88e39a9 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/ClientInfoControllerV2Test.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/ClientInfoControllerV2Test.java @@ -28,13 +28,14 @@ import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.naming.misc.UtilsAndCommons; import com.fasterxml.jackson.databind.JsonNode; -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.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; @@ -44,11 +45,16 @@ import java.util.Arrays; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class ClientInfoControllerV2Test extends BaseTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class ClientInfoControllerV2Test extends BaseTest { + + private static final String URL = UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + UtilsAndCommons.NACOS_NAMING_CLIENT_CONTEXT; @InjectMocks ClientInfoControllerV2 clientInfoControllerV2; @@ -68,10 +74,7 @@ public class ClientInfoControllerV2Test extends BaseTest { private ConnectionBasedClient connectionBasedClient; - private static final String URL = - UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + UtilsAndCommons.NACOS_NAMING_CLIENT_CONTEXT; - - @Before + @BeforeEach public void before() { when(clientManager.allClientId()).thenReturn(Arrays.asList("127.0.0.1:8080#test1", "test2#test2")); when(clientManager.contains(anyString())).thenReturn(true); @@ -81,46 +84,42 @@ public void before() { } @Test - public void testGetClientList() throws Exception { + void testGetClientList() throws Exception { MockHttpServletRequestBuilder mockHttpServletRequestBuilder = MockMvcRequestBuilders.get(URL + "/list"); MockHttpServletResponse response = mockmvc.perform(mockHttpServletRequestBuilder).andReturn().getResponse(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); JsonNode jsonNode = JacksonUtils.toObj(response.getContentAsString()).get("data"); - Assert.assertEquals(2, jsonNode.size()); + assertEquals(2, jsonNode.size()); } @Test - public void testGetClientDetail() throws Exception { + void testGetClientDetail() throws Exception { when(clientManager.getClient("test1")).thenReturn(ipPortBasedClient); - MockHttpServletRequestBuilder mockHttpServletRequestBuilder = MockMvcRequestBuilders.get(URL) - .param("clientId", "test1"); + MockHttpServletRequestBuilder mockHttpServletRequestBuilder = MockMvcRequestBuilders.get(URL).param("clientId", "test1"); MockHttpServletResponse response = mockmvc.perform(mockHttpServletRequestBuilder).andReturn().getResponse(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } - + @Test - public void testGetPublishedServiceList() throws Exception { + void testGetPublishedServiceList() throws Exception { // single instance when(clientManager.getClient("test1")).thenReturn(connectionBasedClient); Service service = Service.newService("test", "test", "test"); connectionBasedClient.addServiceInstance(service, new InstancePublishInfo("127.0.0.1", 8848)); MockHttpServletRequestBuilder mockHttpServletRequestBuilder = MockMvcRequestBuilders.get(URL + "/publish/list") .param("clientId", "test1"); - mockmvc.perform(mockHttpServletRequestBuilder) - .andExpect(MockMvcResultMatchers.jsonPath("$.data.length()").value(1)); + mockmvc.perform(mockHttpServletRequestBuilder).andExpect(MockMvcResultMatchers.jsonPath("$.data.length()").value(1)); // batch instances BatchInstancePublishInfo instancePublishInfo = new BatchInstancePublishInfo(); - instancePublishInfo.setInstancePublishInfos(Arrays.asList(new InstancePublishInfo("127.0.0.1", 8848), - new InstancePublishInfo("127.0.0.1", 8849))); + instancePublishInfo.setInstancePublishInfos( + Arrays.asList(new InstancePublishInfo("127.0.0.1", 8848), new InstancePublishInfo("127.0.0.1", 8849))); connectionBasedClient.addServiceInstance(service, instancePublishInfo); - mockHttpServletRequestBuilder = MockMvcRequestBuilders.get(URL + "/publish/list") - .param("clientId", "test1"); - mockmvc.perform(mockHttpServletRequestBuilder) - .andExpect(MockMvcResultMatchers.jsonPath("$.data.length()").value(2)); + mockHttpServletRequestBuilder = MockMvcRequestBuilders.get(URL + "/publish/list").param("clientId", "test1"); + mockmvc.perform(mockHttpServletRequestBuilder).andExpect(MockMvcResultMatchers.jsonPath("$.data.length()").value(2)); } - + @Test - public void testGetPublishedClientList() throws Exception { + void testGetPublishedClientList() throws Exception { String baseTestKey = "nacos-getPublishedClientList-test"; // single instance Service service = Service.newService(baseTestKey, baseTestKey, baseTestKey); @@ -128,28 +127,19 @@ public void testGetPublishedClientList() throws Exception { when(clientManager.getClient("test")).thenReturn(connectionBasedClient); connectionBasedClient.addServiceInstance(service, new InstancePublishInfo("127.0.0.1", 8848)); MockHttpServletRequestBuilder mockHttpServletRequestBuilder = MockMvcRequestBuilders.get(URL + "/service/publisher/list") - .param("namespaceId", baseTestKey) - .param("groupName", baseTestKey) - .param("serviceName", baseTestKey) - .param("ip", "127.0.0.1") - .param("port", "8848"); - mockmvc.perform(mockHttpServletRequestBuilder) - .andExpect(MockMvcResultMatchers.jsonPath("$.data.length()").value(1)); - + .param("namespaceId", baseTestKey).param("groupName", baseTestKey).param("serviceName", baseTestKey) + .param("ip", "127.0.0.1").param("port", "8848"); + mockmvc.perform(mockHttpServletRequestBuilder).andExpect(MockMvcResultMatchers.jsonPath("$.data.length()").value(1)); + // batch instances when(clientServiceIndexesManager.getAllClientsRegisteredService(service)).thenReturn(Arrays.asList("test")); when(clientManager.getClient("test")).thenReturn(connectionBasedClient); BatchInstancePublishInfo instancePublishInfo = new BatchInstancePublishInfo(); - instancePublishInfo.setInstancePublishInfos(Arrays.asList(new InstancePublishInfo("127.0.0.1", 8848), - new InstancePublishInfo("127.0.0.1", 8849))); + instancePublishInfo.setInstancePublishInfos( + Arrays.asList(new InstancePublishInfo("127.0.0.1", 8848), new InstancePublishInfo("127.0.0.1", 8849))); connectionBasedClient.addServiceInstance(service, instancePublishInfo); - mockHttpServletRequestBuilder = MockMvcRequestBuilders.get(URL + "/service/publisher/list") - .param("namespaceId", baseTestKey) - .param("groupName", baseTestKey) - .param("serviceName", baseTestKey) - .param("ip", "127.0.0.1") - .param("port", "8848"); - mockmvc.perform(mockHttpServletRequestBuilder) - .andExpect(MockMvcResultMatchers.jsonPath("$.data.length()").value(1)); + mockHttpServletRequestBuilder = MockMvcRequestBuilders.get(URL + "/service/publisher/list").param("namespaceId", baseTestKey) + .param("groupName", baseTestKey).param("serviceName", baseTestKey).param("ip", "127.0.0.1").param("port", "8848"); + mockmvc.perform(mockHttpServletRequestBuilder).andExpect(MockMvcResultMatchers.jsonPath("$.data.length()").value(1)); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/HealthControllerV2Test.java b/naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/HealthControllerV2Test.java index 31fd852fa09..a61f08e0f27 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/HealthControllerV2Test.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/HealthControllerV2Test.java @@ -22,13 +22,12 @@ import com.alibaba.nacos.naming.core.HealthOperatorV2Impl; import com.alibaba.nacos.naming.misc.UtilsAndCommons; import com.alibaba.nacos.naming.model.form.UpdateHealthForm; -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.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; @@ -36,10 +35,11 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.doNothing; -@RunWith(MockitoJUnitRunner.class) -public class HealthControllerV2Test extends BaseTest { +@ExtendWith(MockitoExtension.class) +class HealthControllerV2Test extends BaseTest { @Mock private HealthOperatorV2Impl healthOperatorV2; @@ -51,7 +51,7 @@ public class HealthControllerV2Test extends BaseTest { private UpdateHealthForm updateHealthForm; - @Before + @BeforeEach public void before() { ReflectionTestUtils.setField(healthControllerV2, "healthOperatorV2", healthOperatorV2); mockmvc = MockMvcBuilders.standaloneSetup(healthControllerV2).build(); @@ -66,15 +66,15 @@ public void before() { } @Test - public void testUpdate() throws Exception { + void testUpdate() throws Exception { doNothing().when(healthOperatorV2).updateHealthStatusForPersistentInstance(TEST_NAMESPACE, - NamingUtils.getGroupedName(updateHealthForm.getServiceName(), updateHealthForm.getGroupName()), - TEST_CLUSTER_NAME, "123.123.123.123", 8888, true); - MockHttpServletRequestBuilder builder = convert(updateHealthForm, MockMvcRequestBuilders.put( - UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + UtilsAndCommons.NACOS_NAMING_HEALTH_CONTEXT)); + NamingUtils.getGroupedName(updateHealthForm.getServiceName(), updateHealthForm.getGroupName()), TEST_CLUSTER_NAME, + "123.123.123.123", 8888, true); + MockHttpServletRequestBuilder builder = convert(updateHealthForm, + MockMvcRequestBuilders.put(UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + UtilsAndCommons.NACOS_NAMING_HEALTH_CONTEXT)); MockHttpServletResponse response = mockmvc.perform(builder).andReturn().getResponse(); - Assert.assertEquals(200, response.getStatus()); - Assert.assertEquals("ok", JacksonUtils.toObj(response.getContentAsString()).get("data").asText()); + assertEquals(200, response.getStatus()); + assertEquals("ok", JacksonUtils.toObj(response.getContentAsString()).get("data").asText()); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/InstanceControllerV2Test.java b/naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/InstanceControllerV2Test.java index 7746912b30b..6d634c3eeee 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/InstanceControllerV2Test.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/InstanceControllerV2Test.java @@ -31,14 +31,13 @@ import com.alibaba.nacos.naming.model.form.InstanceMetadataBatchOperationForm; import com.alibaba.nacos.naming.model.vo.InstanceDetailInfoVo; import com.alibaba.nacos.naming.model.vo.InstanceMetadataBatchOperationVo; -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.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; @@ -50,14 +49,15 @@ import java.util.List; import java.util.concurrent.TimeUnit; -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.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class InstanceControllerV2Test extends BaseTest { +@ExtendWith(MockitoExtension.class) +class InstanceControllerV2Test extends BaseTest { @InjectMocks private InstanceControllerV2 instanceControllerV2; @@ -71,7 +71,7 @@ public class InstanceControllerV2Test extends BaseTest { private volatile Class eventReceivedClass; - @Before + @BeforeEach public void before() { super.before(); ReflectionTestUtils.setField(instanceControllerV2, "instanceServiceV2", instanceServiceV2); @@ -93,15 +93,15 @@ public void onEvent(Event event) { NotifyCenter.registerSubscriber(subscriber); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { NotifyCenter.deregisterSubscriber(subscriber); NotifyCenter.deregisterPublisher(UpdateInstanceTraceEvent.class); eventReceivedClass = null; } @Test - public void registerInstance() throws Exception { + void registerInstance() throws Exception { InstanceForm instanceForm = new InstanceForm(); instanceForm.setNamespaceId(TEST_NAMESPACE); @@ -125,7 +125,7 @@ public void registerInstance() throws Exception { } @Test - public void deregisterInstance() throws Exception { + void deregisterInstance() throws Exception { InstanceForm instanceForm = new InstanceForm(); instanceForm.setNamespaceId(TEST_NAMESPACE); @@ -150,7 +150,7 @@ public void deregisterInstance() throws Exception { } @Test - public void updateInstance() throws Exception { + void updateInstance() throws Exception { InstanceForm instanceForm = new InstanceForm(); instanceForm.setNamespaceId(TEST_NAMESPACE); instanceForm.setGroupName("DEFAULT_GROUP"); @@ -171,11 +171,11 @@ public void updateInstance() throws Exception { assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode()); assertEquals("ok", result.getData()); TimeUnit.SECONDS.sleep(1); - assertEquals(eventReceivedClass, UpdateInstanceTraceEvent.class); + assertEquals(UpdateInstanceTraceEvent.class, eventReceivedClass); } @Test - public void batchUpdateInstanceMetadata() throws Exception { + void batchUpdateInstanceMetadata() throws Exception { InstanceMetadataBatchOperationForm form = new InstanceMetadataBatchOperationForm(); form.setNamespaceId(TEST_NAMESPACE); @@ -200,47 +200,44 @@ public void batchUpdateInstanceMetadata() throws Exception { } @Test - public void patch() throws Exception { + void patch() throws Exception { MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.patch( UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT) .param("namespaceId", TEST_NAMESPACE).param("serviceName", TEST_SERVICE_NAME).param("ip", TEST_IP) - .param("cluster", TEST_CLUSTER_NAME).param("port", "9999").param("healthy", "true") - .param("weight", "2.0").param("enabled", "true").param("metadata", TEST_METADATA) - .param("ephemeral", "false"); + .param("cluster", TEST_CLUSTER_NAME).param("port", "9999").param("healthy", "true").param("weight", "2.0") + .param("enabled", "true").param("metadata", TEST_METADATA).param("ephemeral", "false"); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); - Assert.assertEquals("ok", actualValue); + assertEquals("ok", actualValue); } @Test - public void listInstance() throws Exception { + void listInstance() throws Exception { ServiceInfo serviceInfo = new ServiceInfo(); serviceInfo.setName("serviceInfo"); - when(instanceServiceV2.listInstance(eq(TEST_NAMESPACE), eq(TEST_SERVICE_NAME), any(), eq(TEST_CLUSTER_NAME), - eq(false))).thenReturn(serviceInfo); + when(instanceServiceV2.listInstance(eq(TEST_NAMESPACE), eq(TEST_SERVICE_NAME), any(), eq(TEST_CLUSTER_NAME), eq(false))).thenReturn( + serviceInfo); - Result result = instanceControllerV2.list(TEST_NAMESPACE, "DEFAULT_GROUP", "test-service", - TEST_CLUSTER_NAME, TEST_IP, 9999, false, "", "", ""); + Result result = instanceControllerV2.list(TEST_NAMESPACE, "DEFAULT_GROUP", "test-service", TEST_CLUSTER_NAME, TEST_IP, + 9999, false, "", "", ""); - verify(instanceServiceV2).listInstance(eq(TEST_NAMESPACE), eq(TEST_SERVICE_NAME), any(), eq(TEST_CLUSTER_NAME), - eq(false)); + verify(instanceServiceV2).listInstance(eq(TEST_NAMESPACE), eq(TEST_SERVICE_NAME), any(), eq(TEST_CLUSTER_NAME), eq(false)); assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode()); assertEquals(serviceInfo.getName(), result.getData().getName()); } @Test - public void detail() throws Exception { + void detail() throws Exception { Instance instance = new Instance(); instance.setInstanceId("test-id"); - when(instanceServiceV2.getInstance(TEST_NAMESPACE, TEST_SERVICE_NAME, TEST_CLUSTER_NAME, TEST_IP, - 9999)).thenReturn(instance); + when(instanceServiceV2.getInstance(TEST_NAMESPACE, TEST_SERVICE_NAME, TEST_CLUSTER_NAME, TEST_IP, 9999)).thenReturn(instance); - Result result = instanceControllerV2.detail(TEST_NAMESPACE, "DEFAULT_GROUP", - "test-service", TEST_CLUSTER_NAME, TEST_IP, 9999); + Result result = instanceControllerV2.detail(TEST_NAMESPACE, "DEFAULT_GROUP", "test-service", + TEST_CLUSTER_NAME, TEST_IP, 9999); verify(instanceServiceV2).getInstance(TEST_NAMESPACE, TEST_SERVICE_NAME, TEST_CLUSTER_NAME, TEST_IP, 9999); @@ -249,21 +246,21 @@ public void detail() throws Exception { } @Test - public void beat() throws Exception { + void beat() throws Exception { MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.put( - UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT - + "/beat").param("namespaceId", TEST_NAMESPACE).param("serviceName", TEST_SERVICE_NAME) - .param("ip", TEST_IP).param("clusterName", "clusterName").param("port", "0").param("beat", ""); + UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT + "/beat") + .param("namespaceId", TEST_NAMESPACE).param("serviceName", TEST_SERVICE_NAME).param("ip", TEST_IP) + .param("clusterName", "clusterName").param("port", "0").param("beat", ""); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); - Assert.assertNotNull(actualValue); + assertNotNull(actualValue); } @Test - public void listWithHealthStatus() throws Exception { + void listWithHealthStatus() throws Exception { MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get( - UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT - + "/statuses").param("key", ""); + UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT + "/statuses") + .param("key", ""); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getContentAsString(); - Assert.assertNotNull(actualValue); + assertNotNull(actualValue); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/OperatorControllerV2Test.java b/naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/OperatorControllerV2Test.java index 25e414a1090..b1673ab6b5a 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/OperatorControllerV2Test.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/OperatorControllerV2Test.java @@ -27,19 +27,19 @@ import com.alibaba.nacos.naming.model.vo.MetricsInfoVo; import com.alibaba.nacos.sys.env.Constants; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.env.MockEnvironment; import java.util.Collection; import java.util.HashSet; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * OperatorControllerV2Test. @@ -48,8 +48,8 @@ * @date 2022/9/15 */ -@RunWith(MockitoJUnitRunner.class) -public class OperatorControllerV2Test { +@ExtendWith(MockitoExtension.class) +class OperatorControllerV2Test { private OperatorControllerV2 operatorControllerV2; @@ -65,24 +65,23 @@ public class OperatorControllerV2Test { @Mock private ClientManager clientManager; - @Before - public void setUp() { - this.operatorControllerV2 = new OperatorControllerV2(switchManager, serverStatusManager, switchDomain, - clientManager); + @BeforeEach + void setUp() { + this.operatorControllerV2 = new OperatorControllerV2(switchManager, serverStatusManager, switchDomain, clientManager); MockEnvironment environment = new MockEnvironment(); environment.setProperty(Constants.SUPPORT_UPGRADE_FROM_1X, "true"); EnvUtil.setEnvironment(environment); } @Test - public void testSwitches() { + void testSwitches() { Result result = operatorControllerV2.switches(); assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode()); assertEquals(this.switchDomain, result.getData()); } @Test - public void testUpdateSwitches() { + void testUpdateSwitches() { UpdateSwitchForm updateSwitchForm = new UpdateSwitchForm(); updateSwitchForm.setDebug(true); updateSwitchForm.setEntry("test"); @@ -94,12 +93,12 @@ public void testUpdateSwitches() { assertEquals("ok", result.getData()); } catch (Exception e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } @Test - public void testMetrics() { + void testMetrics() { Mockito.when(serverStatusManager.getServerStatus()).thenReturn(ServerStatus.UP); Collection clients = new HashSet<>(); clients.add("1628132208793_127.0.0.1_8080"); @@ -113,11 +112,11 @@ public void testMetrics() { MetricsInfoVo metricsInfoVo = result.getData(); - Assert.assertEquals(ServerStatus.UP.toString(), metricsInfoVo.getStatus()); - Assert.assertEquals(3, metricsInfoVo.getClientCount().intValue()); - Assert.assertEquals(1, metricsInfoVo.getConnectionBasedClientCount().intValue()); - Assert.assertEquals(1, metricsInfoVo.getEphemeralIpPortClientCount().intValue()); - Assert.assertEquals(1, metricsInfoVo.getPersistentIpPortClientCount().intValue()); - Assert.assertEquals(3, metricsInfoVo.getResponsibleClientCount().intValue()); + assertEquals(ServerStatus.UP.toString(), metricsInfoVo.getStatus()); + assertEquals(3, metricsInfoVo.getClientCount().intValue()); + assertEquals(1, metricsInfoVo.getConnectionBasedClientCount().intValue()); + assertEquals(1, metricsInfoVo.getEphemeralIpPortClientCount().intValue()); + assertEquals(1, metricsInfoVo.getPersistentIpPortClientCount().intValue()); + assertEquals(3, metricsInfoVo.getResponsibleClientCount().intValue()); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/ServiceControllerV2Test.java b/naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/ServiceControllerV2Test.java index c6b48c84376..091119ca936 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/ServiceControllerV2Test.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/ServiceControllerV2Test.java @@ -30,26 +30,26 @@ import com.alibaba.nacos.naming.pojo.ServiceDetailInfo; import com.alibaba.nacos.naming.pojo.ServiceNameView; import com.alibaba.nacos.naming.selector.SelectorManager; -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.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class ServiceControllerV2Test { +@ExtendWith(MockitoExtension.class) +class ServiceControllerV2Test { @Mock private SelectorManager selectorManager; @@ -63,8 +63,8 @@ public class ServiceControllerV2Test { private volatile Class eventReceivedClass; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { serviceController = new ServiceControllerV2(serviceOperatorV2, selectorManager); subscriber = new SmartSubscriber() { @Override @@ -82,15 +82,15 @@ public void onEvent(Event event) { NotifyCenter.registerSubscriber(subscriber); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { NotifyCenter.deregisterSubscriber(subscriber); NotifyCenter.deregisterPublisher(UpdateServiceTraceEvent.class); eventReceivedClass = null; } @Test - public void testCreate() throws Exception { + void testCreate() throws Exception { ServiceForm serviceForm = new ServiceForm(); serviceForm.setNamespaceId(Constants.DEFAULT_NAMESPACE_ID); @@ -102,42 +102,36 @@ public void testCreate() throws Exception { serviceForm.setSelector(""); Result actual = serviceController.create(serviceForm); - verify(serviceOperatorV2).create( - eq(Service.newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "service")), + verify(serviceOperatorV2).create(eq(Service.newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "service")), any(ServiceMetadata.class)); assertEquals(ErrorCode.SUCCESS.getCode(), actual.getCode()); assertEquals("ok", actual.getData()); } @Test - public void testRemove() throws Exception { - Result actual = serviceController.remove(Constants.DEFAULT_NAMESPACE_ID, "service", - Constants.DEFAULT_GROUP); - verify(serviceOperatorV2).delete( - Service.newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "service")); + void testRemove() throws Exception { + Result actual = serviceController.remove(Constants.DEFAULT_NAMESPACE_ID, "service", Constants.DEFAULT_GROUP); + verify(serviceOperatorV2).delete(Service.newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "service")); assertEquals("ok", actual.getData()); assertEquals(ErrorCode.SUCCESS.getCode(), actual.getCode()); } @Test - public void testDetail() throws Exception { + void testDetail() throws Exception { ServiceDetailInfo expected = new ServiceDetailInfo(); when(serviceOperatorV2.queryService( - Service.newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "service"))).thenReturn( - expected); - Result actual = serviceController.detail(Constants.DEFAULT_NAMESPACE_ID, "service", - Constants.DEFAULT_GROUP); + Service.newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "service"))).thenReturn(expected); + Result actual = serviceController.detail(Constants.DEFAULT_NAMESPACE_ID, "service", Constants.DEFAULT_GROUP); assertEquals(ErrorCode.SUCCESS.getCode(), actual.getCode()); assertEquals(expected, actual.getData()); } @Test - public void testList() throws Exception { + void testList() throws Exception { when(serviceOperatorV2.listService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "")).thenReturn( Collections.singletonList("serviceName")); - Result actual = serviceController.list(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, - "", 1, 10); + Result actual = serviceController.list(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "", 1, 10); assertEquals(ErrorCode.SUCCESS.getCode(), actual.getCode()); assertEquals(1, actual.getData().getCount()); assertEquals(1, actual.getData().getServices().size()); @@ -145,7 +139,7 @@ public void testList() throws Exception { } @Test - public void testUpdate() throws Exception { + void testUpdate() throws Exception { ServiceForm serviceForm = new ServiceForm(); serviceForm.setNamespaceId(Constants.DEFAULT_NAMESPACE_ID); serviceForm.setGroupName(Constants.DEFAULT_GROUP); @@ -154,12 +148,11 @@ public void testUpdate() throws Exception { serviceForm.setMetadata(""); serviceForm.setSelector(""); Result actual = serviceController.update(serviceForm); - verify(serviceOperatorV2).update( - eq(Service.newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "service")), + verify(serviceOperatorV2).update(eq(Service.newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "service")), any(ServiceMetadata.class)); assertEquals(ErrorCode.SUCCESS.getCode(), actual.getCode()); assertEquals("ok", actual.getData()); TimeUnit.SECONDS.sleep(1); - assertEquals(eventReceivedClass, UpdateServiceTraceEvent.class); + assertEquals(UpdateServiceTraceEvent.class, eventReceivedClass); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/CatalogServiceV2ImplTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/CatalogServiceV2ImplTest.java index 8efa6b18151..7bb46030907 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/CatalogServiceV2ImplTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/CatalogServiceV2ImplTest.java @@ -28,27 +28,30 @@ import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.naming.pojo.ServiceDetailInfo; import com.fasterxml.jackson.databind.node.ObjectNode; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; import java.util.List; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; + /** * {@link CatalogServiceV2Impl} unit tests. * * @author chenglu * @date 2021-08-03 19:56 */ -@RunWith(MockitoJUnitRunner.class) -public class CatalogServiceV2ImplTest { +@ExtendWith(MockitoExtension.class) +class CatalogServiceV2ImplTest { private CatalogServiceV2Impl catalogServiceV2Impl; @@ -58,16 +61,16 @@ public class CatalogServiceV2ImplTest { @Mock private NamingMetadataManager metadataManager; - @Before - public void setUp() { + @BeforeEach + void setUp() { catalogServiceV2Impl = new CatalogServiceV2Impl(serviceStorage, metadataManager); ServiceManager serviceManager = ServiceManager.getInstance(); Service service = Service.newService("A", "B", "C"); serviceManager.getSingleton(service); } - @After - public void tearDown() { + @AfterEach + void tearDown() { ServiceManager serviceManager = ServiceManager.getInstance(); Service service = Service.newService("A", "B", "C"); serviceManager.removeSingleton(service); @@ -77,29 +80,29 @@ public void tearDown() { } @Test - public void testGetServiceDetail() throws NacosException { + void testGetServiceDetail() throws NacosException { ServiceMetadata serviceMetadata = new ServiceMetadata(); serviceMetadata.setProtectThreshold(0.75F); Mockito.when(metadataManager.getServiceMetadata(Mockito.any())).thenReturn(Optional.of(serviceMetadata)); Mockito.when(serviceStorage.getClusters(Mockito.any())).thenReturn(Collections.singleton("C")); Object obj = catalogServiceV2Impl.getServiceDetail("A", "B", "C"); ObjectNode objectNode = (ObjectNode) obj; - Assert.assertEquals("C", objectNode.get(FieldsConstants.SERVICE).get(FieldsConstants.NAME).asText()); - Assert.assertEquals("B", objectNode.get(FieldsConstants.SERVICE).get(FieldsConstants.GROUP_NAME).asText()); - Assert.assertEquals("none", - objectNode.get(FieldsConstants.SERVICE).get(FieldsConstants.SELECTOR).get("type").asText()); - Assert.assertEquals(0, objectNode.get(FieldsConstants.SERVICE).get(FieldsConstants.METADATA).size()); - Assert.assertEquals(0.75, - objectNode.get(FieldsConstants.SERVICE).get(FieldsConstants.PROTECT_THRESHOLD).asDouble(), 0.1); + assertEquals("C", objectNode.get(FieldsConstants.SERVICE).get(FieldsConstants.NAME).asText()); + assertEquals("B", objectNode.get(FieldsConstants.SERVICE).get(FieldsConstants.GROUP_NAME).asText()); + assertEquals("none", objectNode.get(FieldsConstants.SERVICE).get(FieldsConstants.SELECTOR).get("type").asText()); + assertEquals(0, objectNode.get(FieldsConstants.SERVICE).get(FieldsConstants.METADATA).size()); + assertEquals(0.75, objectNode.get(FieldsConstants.SERVICE).get(FieldsConstants.PROTECT_THRESHOLD).asDouble(), 0.1); } - @Test(expected = NacosException.class) - public void testGetServiceDetailNonExist() throws NacosException { - catalogServiceV2Impl.getServiceDetail("A", "BB", "CC"); + @Test + void testGetServiceDetailNonExist() throws NacosException { + assertThrows(NacosException.class, () -> { + catalogServiceV2Impl.getServiceDetail("A", "BB", "CC"); + }); } @Test - public void testListInstances() throws NacosException { + void testListInstances() throws NacosException { Mockito.when(serviceStorage.getClusters(Mockito.any())).thenReturn(Collections.singleton("D")); ServiceInfo serviceInfo = new ServiceInfo(); serviceInfo.setGroupName("B"); @@ -110,21 +113,25 @@ public void testListInstances() throws NacosException { serviceInfo.setHosts(Collections.singletonList(instance)); Mockito.when(serviceStorage.getData(Mockito.any())).thenReturn(serviceInfo); List instances = catalogServiceV2Impl.listInstances("A", "B", "C", "D"); - Assert.assertEquals(1, instances.size()); + assertEquals(1, instances.size()); } - @Test(expected = NacosException.class) - public void testListInstancesNonExistService() throws NacosException { - catalogServiceV2Impl.listInstances("A", "BB", "CC", "DD"); + @Test + void testListInstancesNonExistService() throws NacosException { + assertThrows(NacosException.class, () -> { + catalogServiceV2Impl.listInstances("A", "BB", "CC", "DD"); + }); } - @Test(expected = NacosException.class) - public void testListInstancesNonExistCluster() throws NacosException { - catalogServiceV2Impl.listInstances("A", "B", "C", "DD"); + @Test + void testListInstancesNonExistCluster() throws NacosException { + assertThrows(NacosException.class, () -> { + catalogServiceV2Impl.listInstances("A", "B", "C", "DD"); + }); } @Test - public void testPageListService() throws NacosException { + void testPageListService() throws NacosException { ServiceInfo serviceInfo = new ServiceInfo(); serviceInfo.setHosts(Collections.singletonList(new Instance())); Mockito.when(serviceStorage.getData(Mockito.any())).thenReturn(serviceInfo); @@ -133,11 +140,11 @@ public void testPageListService() throws NacosException { Mockito.when(metadataManager.getServiceMetadata(Mockito.any())).thenReturn(Optional.of(metadata)); ObjectNode obj = (ObjectNode) catalogServiceV2Impl.pageListService("A", "B", "C", 1, 10, null, false); - Assert.assertEquals(1, obj.get(FieldsConstants.COUNT).asInt()); + assertEquals(1, obj.get(FieldsConstants.COUNT).asInt()); } @Test - public void testPageListServiceNotSpecifiedName() throws NacosException { + void testPageListServiceNotSpecifiedName() throws NacosException { ServiceInfo serviceInfo = new ServiceInfo(); serviceInfo.setHosts(Collections.singletonList(new Instance())); Mockito.when(serviceStorage.getData(Mockito.any())).thenReturn(serviceInfo); @@ -146,20 +153,20 @@ public void testPageListServiceNotSpecifiedName() throws NacosException { Mockito.when(metadataManager.getServiceMetadata(Mockito.any())).thenReturn(Optional.of(metadata)); ObjectNode obj = (ObjectNode) catalogServiceV2Impl.pageListService("A", "", "", 1, 10, null, false); - Assert.assertEquals(1, obj.get(FieldsConstants.COUNT).asInt()); + assertEquals(1, obj.get(FieldsConstants.COUNT).asInt()); } @Test - public void testPageListServiceForIgnoreEmptyService() throws NacosException { + void testPageListServiceForIgnoreEmptyService() throws NacosException { ServiceInfo serviceInfo = new ServiceInfo(); Mockito.when(serviceStorage.getData(Mockito.any())).thenReturn(serviceInfo); ObjectNode obj = (ObjectNode) catalogServiceV2Impl.pageListService("A", "B", "C", 1, 10, null, true); - Assert.assertEquals(0, obj.get(FieldsConstants.COUNT).asInt()); + assertEquals(0, obj.get(FieldsConstants.COUNT).asInt()); } @Test - public void testPageListServiceForPage() throws NacosException { + void testPageListServiceForPage() throws NacosException { ServiceInfo serviceInfo = new ServiceInfo(); Mockito.when(serviceStorage.getData(Mockito.any())).thenReturn(serviceInfo); ServiceManager.getInstance().getSingleton(Service.newService("CatalogService", "CatalogService", "1")); @@ -167,12 +174,12 @@ public void testPageListServiceForPage() throws NacosException { ServiceManager.getInstance().getSingleton(Service.newService("CatalogService", "CatalogService", "3")); ObjectNode obj = (ObjectNode) catalogServiceV2Impl.pageListService("CatalogService", "", "", 2, 1, null, false); - Assert.assertEquals(3, obj.get(FieldsConstants.COUNT).asInt()); - Assert.assertEquals("2", obj.get(FieldsConstants.SERVICE_LIST).get(0).get("name").asText()); + assertEquals(3, obj.get(FieldsConstants.COUNT).asInt()); + assertEquals("2", obj.get(FieldsConstants.SERVICE_LIST).get(0).get("name").asText()); } @Test - public void testPageListServiceDetail() { + void testPageListServiceDetail() { try { ServiceMetadata metadata = new ServiceMetadata(); Mockito.when(metadataManager.getServiceMetadata(Mockito.any())).thenReturn(Optional.of(metadata)); @@ -185,13 +192,12 @@ public void testPageListServiceDetail() { serviceInfo.setHosts(instances); Mockito.when(serviceStorage.getData(Mockito.any())).thenReturn(serviceInfo); - List result = (List) catalogServiceV2Impl - .pageListServiceDetail("A", "B", "C", 1, 10); + List result = (List) catalogServiceV2Impl.pageListServiceDetail("A", "B", "C", 1, 10); - Assert.assertEquals(1, result.size()); + assertEquals(1, result.size()); } catch (NacosException e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/ClusterOperatorV2ImplTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/ClusterOperatorV2ImplTest.java index 03e85819b9b..0d624f1ca3c 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/ClusterOperatorV2ImplTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/ClusterOperatorV2ImplTest.java @@ -21,19 +21,18 @@ import com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata; import com.alibaba.nacos.naming.core.v2.metadata.NamingMetadataOperateService; import com.alibaba.nacos.naming.core.v2.pojo.Service; -import junit.framework.TestCase; -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 static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.verify; -@RunWith(MockitoJUnitRunner.class) -public class ClusterOperatorV2ImplTest extends TestCase { +@ExtendWith(MockitoExtension.class) +class ClusterOperatorV2ImplTest { private ClusterOperatorV2Impl clusterOperatorV2Impl; @@ -42,9 +41,8 @@ public class ClusterOperatorV2ImplTest extends TestCase { private ClusterMetadata clusterMetadata; - @Before - public void setUp() throws Exception { - super.setUp(); + @BeforeEach + void setUp() throws Exception { Service service = Service.newService("namespace_test", "group_test", "name_test"); ServiceManager.getInstance().getSingleton(service); clusterOperatorV2Impl = new ClusterOperatorV2Impl(metadataOperateServiceMock); @@ -52,10 +50,8 @@ public void setUp() throws Exception { } @Test - public void testUpdateClusterMetadata() throws NacosException { - clusterOperatorV2Impl - .updateClusterMetadata("namespace_test", "group_test@@name_test", "clusterName_test", clusterMetadata); - verify(metadataOperateServiceMock) - .addClusterMetadata(any(Service.class), anyString(), any(ClusterMetadata.class)); + void testUpdateClusterMetadata() throws NacosException { + clusterOperatorV2Impl.updateClusterMetadata("namespace_test", "group_test@@name_test", "clusterName_test", clusterMetadata); + verify(metadataOperateServiceMock).addClusterMetadata(any(Service.class), anyString(), any(ClusterMetadata.class)); } } \ No newline at end of file diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/DistroMapperTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/DistroMapperTest.java index cf9c7b2d860..ae983c331b7 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/DistroMapperTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/DistroMapperTest.java @@ -20,21 +20,21 @@ import com.alibaba.nacos.core.cluster.ServerMemberManager; import com.alibaba.nacos.naming.misc.SwitchDomain; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.core.env.StandardEnvironment; import java.util.HashSet; import java.util.concurrent.ConcurrentSkipListMap; -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; -@RunWith(MockitoJUnitRunner.class) -public class DistroMapperTest { +@ExtendWith(MockitoExtension.class) +class DistroMapperTest { private DistroMapper distroMapper; @@ -55,8 +55,8 @@ public class DistroMapperTest { private int port = 8848; - @Before - public void setUp() { + @BeforeEach + void setUp() { ConcurrentSkipListMap serverList = new ConcurrentSkipListMap<>(); EnvUtil.setEnvironment(new StandardEnvironment()); EnvUtil.setIsStandalone(true); @@ -71,12 +71,12 @@ public void setUp() { } @Test - public void testResponsible() { + void testResponsible() { assertTrue(distroMapper.responsible(serviceName)); } @Test - public void testMapSrv() { + void testMapSrv() { String server = distroMapper.mapSrv(serviceName); assertEquals(server, ip4); } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/HealthOperatorV2ImplTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/HealthOperatorV2ImplTest.java index 825fd6c03ef..180dba36ddc 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/HealthOperatorV2ImplTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/HealthOperatorV2ImplTest.java @@ -27,26 +27,27 @@ import com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata; import com.alibaba.nacos.naming.core.v2.pojo.InstancePublishInfo; import com.alibaba.nacos.naming.core.v2.service.ClientOperationServiceProxy; -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.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.HashMap; import java.util.Map; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.fail; + /** * {@link HealthOperatorV2Impl} unit tests. * * @author chenglu * @date 2021-08-03 22:31 */ -@RunWith(MockitoJUnitRunner.class) -public class HealthOperatorV2ImplTest { +@ExtendWith(MockitoExtension.class) +class HealthOperatorV2ImplTest { @InjectMocks private HealthOperatorV2Impl healthOperatorV2; @@ -61,7 +62,7 @@ public class HealthOperatorV2ImplTest { private ClientOperationServiceProxy clientOperationService; @Test - public void testUpdateHealthStatusForPersistentInstance() { + void testUpdateHealthStatusForPersistentInstance() { try { ServiceMetadata metadata = new ServiceMetadata(); Map clusterMap = new HashMap<>(2); @@ -84,7 +85,7 @@ public void testUpdateHealthStatusForPersistentInstance() { healthOperatorV2.updateHealthStatusForPersistentInstance("A", "B", "C", "1.1.1.1", 8080, true); } catch (NacosException e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/InstanceOperatorClientImplTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/InstanceOperatorClientImplTest.java index 06e3a7cb621..857e6cccea2 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/InstanceOperatorClientImplTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/InstanceOperatorClientImplTest.java @@ -40,17 +40,16 @@ import com.alibaba.nacos.naming.selector.SelectorManager; import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.utils.ApplicationUtils; -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.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.mockito.stubbing.Answer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.mock.env.MockEnvironment; @@ -61,6 +60,9 @@ import java.util.Map; import java.util.Optional; +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.Mockito.when; @@ -70,11 +72,10 @@ * @author chenglu * @date 2021-08-03 22:46 */ -@RunWith(MockitoJUnitRunner.class) -public class InstanceOperatorClientImplTest { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class InstanceOperatorClientImplTest { @InjectMocks private InstanceOperatorClientImpl instanceOperatorClient; @@ -106,44 +107,45 @@ public class InstanceOperatorClientImplTest { @Mock private ConfigurableApplicationContext context; - @Before - public void setUp() { + @BeforeEach + void setUp() { Service service = Service.newService("A", "DEFAULT_GROUP", "C"); ServiceManager.getInstance().getSingleton(service); EnvUtil.setEnvironment(new MockEnvironment()); ApplicationUtils.injectContext(context); when(context.getBean(SelectorManager.class)).thenReturn(selectorManager); - when(selectorManager.select(any(), any(), any())) - .then((Answer>) invocationOnMock -> invocationOnMock.getArgument(2)); + when(selectorManager.select(any(), any(), any())).then( + (Answer>) invocationOnMock -> invocationOnMock.getArgument(2)); } - @After - public void tearDown() { + @AfterEach + void tearDown() { Service service = Service.newService("A", "DEFAULT_GROUP", "C"); ServiceManager.getInstance().removeSingleton(service); } @Test - public void testRegisterInstance() throws NacosException { + void testRegisterInstance() throws NacosException { instanceOperatorClient.registerInstance("A", "B", new Instance()); Mockito.verify(clientOperationService).registerInstance(Mockito.any(), Mockito.any(), Mockito.anyString()); } @Test - public void testRegisterInstanceWithInvalidClusterName() throws NacosException { - expectedException.expect(NacosException.class); - expectedException.expectMessage("Instance 'clusterName' should be characters with only 0-9a-zA-Z-. (current: cluster1,cluster2)"); - - Instance instance = new Instance(); - instance.setEphemeral(true); - instance.setClusterName("cluster1,cluster2"); - new InstanceOperatorClientImpl(null, null, null, null, null, null, null).registerInstance("ns-01", - "serviceName01", instance); + void testRegisterInstanceWithInvalidClusterName() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { + + Instance instance = new Instance(); + instance.setEphemeral(true); + instance.setClusterName("cluster1,cluster2"); + new InstanceOperatorClientImpl(null, null, null, null, null, null, null).registerInstance("ns-01", "serviceName01", instance); + }); + assertTrue(exception.getMessage() + .contains("Instance 'clusterName' should be characters with only 0-9a-zA-Z-. (current: cluster1,cluster2)")); } @Test - public void testRemoveInstance() { + void testRemoveInstance() { when(clientManager.contains(Mockito.anyString())).thenReturn(true); instanceOperatorClient.removeInstance("A", "B", new Instance()); @@ -152,7 +154,7 @@ public void testRemoveInstance() { } @Test - public void testUpdateInstance() throws NacosException { + void testUpdateInstance() throws NacosException { Instance instance = new Instance(); instance.setServiceName("C"); instanceOperatorClient.updateInstance("A", "C", instance); @@ -161,7 +163,7 @@ public void testUpdateInstance() throws NacosException { } @Test - public void testPatchInstance() throws NacosException { + void testPatchInstance() throws NacosException { Instance instance = new Instance(); instance.setIp("1.1.1.1"); instance.setPort(8848); @@ -174,12 +176,11 @@ public void testPatchInstance() throws NacosException { instanceOperatorClient.patchInstance("A", "B", new InstancePatchObject("C", "1.1.1.1", 8848)); - Mockito.verify(metadataOperateService) - .updateInstanceMetadata(Mockito.any(), Mockito.anyString(), Mockito.any()); + Mockito.verify(metadataOperateService).updateInstanceMetadata(Mockito.any(), Mockito.anyString(), Mockito.any()); } @Test - public void testListInstance() { + void testListInstance() { when(pushService.canEnablePush(Mockito.anyString())).thenReturn(true); ServiceInfo serviceInfo = new ServiceInfo(); @@ -197,7 +198,7 @@ public void testListInstance() { } @Test - public void testHandleBeat() throws NacosException { + void testHandleBeat() throws NacosException { IpPortBasedClient ipPortBasedClient = Mockito.mock(IpPortBasedClient.class); when(clientManager.getClient(Mockito.anyString())).thenReturn(ipPortBasedClient); @@ -205,29 +206,27 @@ public void testHandleBeat() throws NacosException { RsInfo rsInfo = new RsInfo(); rsInfo.setMetadata(new HashMap<>(1)); - int res = instanceOperatorClient - .handleBeat("A", "C", "1.1.1.1", 8848, "D", rsInfo, BeatInfoInstanceBuilder.newBuilder()); + int res = instanceOperatorClient.handleBeat("A", "C", "1.1.1.1", 8848, "D", rsInfo, BeatInfoInstanceBuilder.newBuilder()); - Assert.assertEquals(NamingResponseCode.OK, res); + assertEquals(NamingResponseCode.OK, res); } @Test - public void testGetHeartBeatInterval() { + void testGetHeartBeatInterval() { InstanceMetadata instanceMetadata = new InstanceMetadata(); Map map = new HashMap<>(2); instanceMetadata.setExtendData(map); - when(metadataManager.getInstanceMetadata(Mockito.any(), Mockito.anyString())) - .thenReturn(Optional.of(instanceMetadata)); + when(metadataManager.getInstanceMetadata(Mockito.any(), Mockito.anyString())).thenReturn(Optional.of(instanceMetadata)); when(switchDomain.getClientBeatInterval()).thenReturn(100L); long interval = instanceOperatorClient.getHeartBeatInterval("A", "C", "1.1.1.1", 8848, "D"); - Assert.assertEquals(100L, interval); + assertEquals(100L, interval); } @Test - public void testListAllInstances() throws NacosException { + void testListAllInstances() throws NacosException { ServiceInfo serviceInfo = new ServiceInfo(); serviceInfo.setHosts(Collections.emptyList()); @@ -235,11 +234,11 @@ public void testListAllInstances() throws NacosException { List instances = instanceOperatorClient.listAllInstances("A", "C"); - Assert.assertEquals(0, instances.size()); + assertEquals(0, instances.size()); } @Test - public void testBatchUpdateMetadata() throws NacosException { + void testBatchUpdateMetadata() throws NacosException { Instance instance = new Instance(); instance.setServiceName("C"); instance.setIp("1.1.1.1"); @@ -251,11 +250,11 @@ public void testBatchUpdateMetadata() throws NacosException { InstanceOperationInfo instanceOperationInfo = new InstanceOperationInfo(); List res = instanceOperatorClient.batchUpdateMetadata("A", instanceOperationInfo, new HashMap<>()); - Assert.assertEquals(1, res.size()); + assertEquals(1, res.size()); } @Test - public void testBatchDeleteMetadata() throws NacosException { + void testBatchDeleteMetadata() throws NacosException { Instance instance = new Instance(); instance.setServiceName("C"); instance.setIp("1.1.1.1"); @@ -264,9 +263,8 @@ public void testBatchDeleteMetadata() throws NacosException { serviceInfo.setHosts(Collections.singletonList(instance)); when(serviceStorage.getData(Mockito.any())).thenReturn(serviceInfo); - List res = instanceOperatorClient - .batchDeleteMetadata("A", new InstanceOperationInfo(), new HashMap<>()); + List res = instanceOperatorClient.batchDeleteMetadata("A", new InstanceOperationInfo(), new HashMap<>()); - Assert.assertEquals(1, res.size()); + assertEquals(1, res.size()); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/ServiceOperatorV2ImplTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/ServiceOperatorV2ImplTest.java index cb4e49d7da2..34cee8f84e3 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/ServiceOperatorV2ImplTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/ServiceOperatorV2ImplTest.java @@ -28,15 +28,14 @@ import com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata; import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.fasterxml.jackson.databind.node.ObjectNode; -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.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.util.ReflectionUtils; import java.lang.reflect.Field; @@ -46,14 +45,16 @@ import java.util.Map; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * {@link ServiceOperatorV2Impl} unit tests. * * @author chenglu * @date 2021-08-04 00:06 */ -@RunWith(MockitoJUnitRunner.class) -public class ServiceOperatorV2ImplTest { +@ExtendWith(MockitoExtension.class) +class ServiceOperatorV2ImplTest { @InjectMocks private ServiceOperatorV2Impl serviceOperatorV2; @@ -67,15 +68,15 @@ public class ServiceOperatorV2ImplTest { @Mock private ServiceStorage serviceStorage; - @Before - public void setUp() throws IllegalAccessException { + @BeforeEach + void setUp() throws IllegalAccessException { cleanNamespace(); Service service = Service.newService("A", "B", "C"); ServiceManager.getInstance().getSingleton(service); } - @After - public void tearDown() throws IllegalAccessException { + @AfterEach + void tearDown() throws IllegalAccessException { Service service = Service.newService("A", "B", "C"); ServiceManager.getInstance().removeSingleton(service); cleanNamespace(); @@ -89,21 +90,21 @@ private void cleanNamespace() throws IllegalAccessException { } @Test - public void testCreate() throws NacosException { + void testCreate() throws NacosException { serviceOperatorV2.create("A", "B", new ServiceMetadata()); - + Mockito.verify(metadataOperateService).updateServiceMetadata(Mockito.any(), Mockito.any()); } @Test - public void testUpdate() throws NacosException { + void testUpdate() throws NacosException { serviceOperatorV2.update(Service.newService("A", "B", "C"), new ServiceMetadata()); Mockito.verify(metadataOperateService).updateServiceMetadata(Mockito.any(), Mockito.any()); } @Test - public void testDelete() throws NacosException { + void testDelete() throws NacosException { ServiceInfo serviceInfo = new ServiceInfo(); serviceInfo.setHosts(Collections.emptyList()); Mockito.when(serviceStorage.getPushData(Mockito.any())).thenReturn(serviceInfo); @@ -114,7 +115,7 @@ public void testDelete() throws NacosException { } @Test - public void testQueryService() throws NacosException { + void testQueryService() throws NacosException { ClusterMetadata clusterMetadata = new ClusterMetadata(); Map clusterMetadataMap = new HashMap<>(2); clusterMetadataMap.put("D", clusterMetadata); @@ -125,26 +126,26 @@ public void testQueryService() throws NacosException { Mockito.when(serviceStorage.getClusters(Mockito.any())).thenReturn(Collections.singleton("D")); ObjectNode objectNode = serviceOperatorV2.queryService("A", "B@@C"); - - Assert.assertEquals("A", objectNode.get(FieldsConstants.NAME_SPACE_ID).asText()); - Assert.assertEquals("C", objectNode.get(FieldsConstants.NAME).asText()); - Assert.assertEquals(1, objectNode.get(FieldsConstants.CLUSTERS).size()); + + assertEquals("A", objectNode.get(FieldsConstants.NAME_SPACE_ID).asText()); + assertEquals("C", objectNode.get(FieldsConstants.NAME).asText()); + assertEquals(1, objectNode.get(FieldsConstants.CLUSTERS).size()); } @Test - public void testListService() throws NacosException { + void testListService() throws NacosException { Collection res = serviceOperatorV2.listService("A", "B", null); - Assert.assertEquals(1, res.size()); + assertEquals(1, res.size()); } @Test - public void testListAllNamespace() { - Assert.assertEquals(1, serviceOperatorV2.listAllNamespace().size()); + void testListAllNamespace() { + assertEquals(1, serviceOperatorV2.listAllNamespace().size()); } @Test - public void testSearchServiceName() throws NacosException { + void testSearchServiceName() throws NacosException { Collection res = serviceOperatorV2.searchServiceName("A", ""); - Assert.assertEquals(1, res.size()); + assertEquals(1, res.size()); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/SubscribeManagerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/SubscribeManagerTest.java index 2ebf0150b80..e394b55d47c 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/SubscribeManagerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/SubscribeManagerTest.java @@ -19,20 +19,22 @@ import com.alibaba.nacos.naming.pojo.Subscriber; import com.alibaba.nacos.naming.push.NamingSubscriberServiceAggregationImpl; import com.alibaba.nacos.naming.push.NamingSubscriberServiceLocalImpl; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.util.ReflectionTestUtils; import java.util.ArrayList; import java.util.List; -@RunWith(MockitoJUnitRunner.class) -public class SubscribeManagerTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@ExtendWith(MockitoExtension.class) +class SubscribeManagerTest { private SubscribeManager subscribeManager; @@ -42,35 +44,34 @@ public class SubscribeManagerTest { @Mock private NamingSubscriberServiceLocalImpl local; - @Before - public void before() { + @BeforeEach + void before() { subscribeManager = new SubscribeManager(); ReflectionTestUtils.setField(subscribeManager, "aggregationService", aggregation); ReflectionTestUtils.setField(subscribeManager, "localService", local); } @Test - public void getSubscribersWithFalse() { + void getSubscribersWithFalse() { String serviceName = "test"; String namespaceId = "public"; boolean aggregation = Boolean.FALSE; try { List clients = new ArrayList(); - Subscriber subscriber = new Subscriber("127.0.0.1:8080", "test", "app", "127.0.0.1", namespaceId, - serviceName, 0); + Subscriber subscriber = new Subscriber("127.0.0.1:8080", "test", "app", "127.0.0.1", namespaceId, serviceName, 0); clients.add(subscriber); Mockito.when(this.local.getFuzzySubscribers(Mockito.anyString(), Mockito.anyString())).thenReturn(clients); List list = subscribeManager.getSubscribers(serviceName, namespaceId, aggregation); - Assert.assertNotNull(list); - Assert.assertEquals(1, list.size()); - Assert.assertEquals("public", list.get(0).getNamespaceId()); + assertNotNull(list); + assertEquals(1, list.size()); + assertEquals("public", list.get(0).getNamespaceId()); } catch (Exception ignored) { } } @Test - public void testGetSubscribersFuzzy() { + void testGetSubscribersFuzzy() { String serviceName = "test"; String namespaceId = "public"; boolean aggregation = Boolean.TRUE; @@ -79,34 +80,31 @@ public void testGetSubscribersFuzzy() { Subscriber subscriber = new Subscriber("127.0.0.1:8080", "test", "app", "127.0.0.1", namespaceId, "testGroupName@@test_subscriber", 0); clients.add(subscriber); - Mockito.when(this.aggregation.getFuzzySubscribers(Mockito.anyString(), Mockito.anyString())) - .thenReturn(clients); + Mockito.when(this.aggregation.getFuzzySubscribers(Mockito.anyString(), Mockito.anyString())).thenReturn(clients); List list = subscribeManager.getSubscribers(serviceName, namespaceId, aggregation); - Assert.assertNotNull(list); - Assert.assertEquals(1, list.size()); - Assert.assertEquals("testGroupName@@test_subscriber", list.get(0).getServiceName()); + assertNotNull(list); + assertEquals(1, list.size()); + assertEquals("testGroupName@@test_subscriber", list.get(0).getServiceName()); } catch (Exception ignored) { } } @Test - public void getSubscribersWithTrue() { + void getSubscribersWithTrue() { String serviceName = "testGroupName@@test_subscriber"; String namespaceId = "public"; boolean aggregation = Boolean.TRUE; try { List clients = new ArrayList<>(); - Subscriber subscriber = new Subscriber("127.0.0.1:8080", "test", "app", "127.0.0.1", namespaceId, - serviceName, 0); + Subscriber subscriber = new Subscriber("127.0.0.1:8080", "test", "app", "127.0.0.1", namespaceId, serviceName, 0); clients.add(subscriber); - Mockito.when(this.aggregation.getFuzzySubscribers(Mockito.anyString(), Mockito.anyString())) - .thenReturn(clients); + Mockito.when(this.aggregation.getFuzzySubscribers(Mockito.anyString(), Mockito.anyString())).thenReturn(clients); List list = subscribeManager.getSubscribers(serviceName, namespaceId, aggregation); - Assert.assertNotNull(list); - Assert.assertEquals(1, list.size()); - Assert.assertEquals("testGroupName@@test_subscriber", list.get(0).getServiceName()); - Assert.assertEquals("public", list.get(0).getNamespaceId()); + assertNotNull(list); + assertEquals(1, list.size()); + assertEquals("testGroupName@@test_subscriber", list.get(0).getServiceName()); + assertEquals("public", list.get(0).getNamespaceId()); } catch (Exception ignored) { } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/cleaner/EmptyServiceAutoCleanerV2Test.java b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/cleaner/EmptyServiceAutoCleanerV2Test.java index c3aca6f6bdd..0537209ce7f 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/cleaner/EmptyServiceAutoCleanerV2Test.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/cleaner/EmptyServiceAutoCleanerV2Test.java @@ -22,26 +22,28 @@ import com.alibaba.nacos.naming.core.v2.index.ServiceStorage; import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.env.MockEnvironment; import java.util.Collections; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + /** * {@link EmptyServiceAutoCleanerV2} unit test. * * @author chenglu * @date 2021-07-21 12:40 */ -@RunWith(MockitoJUnitRunner.class) -public class EmptyServiceAutoCleanerV2Test { +@ExtendWith(MockitoExtension.class) +class EmptyServiceAutoCleanerV2Test { @Mock private ClientServiceIndexesManager clientServiceIndexesManager; @@ -54,8 +56,8 @@ public class EmptyServiceAutoCleanerV2Test { @Mock private Service service; - @Before - public void setUp() { + @BeforeEach + void setUp() { EnvUtil.setEnvironment(new MockEnvironment()); emptyServiceAutoCleanerV2 = new EmptyServiceAutoCleanerV2(clientServiceIndexesManager, serviceStorage); Mockito.when(service.getNamespace()).thenReturn("public"); @@ -63,18 +65,18 @@ public void setUp() { serviceManager.getSingleton(service); } - @After - public void tearDown() { + @AfterEach + void tearDown() { ServiceManager.getInstance().removeSingleton(service); } @Test - public void testGetType() { - Assert.assertEquals("emptyService", emptyServiceAutoCleanerV2.getType()); + void testGetType() { + assertEquals("emptyService", emptyServiceAutoCleanerV2.getType()); } @Test - public void testDoClean() { + void testDoClean() { try { Mockito.when(clientServiceIndexesManager.getAllClientsRegisteredService(Mockito.any())).thenReturn(Collections.emptyList()); @@ -83,7 +85,7 @@ public void testDoClean() { emptyServiceAutoCleanerV2.doClean(); } catch (Exception e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/cleaner/ExpiredMetadataCleanerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/cleaner/ExpiredMetadataCleanerTest.java index 8f88df9cb0d..9bd43eb79e5 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/cleaner/ExpiredMetadataCleanerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/cleaner/ExpiredMetadataCleanerTest.java @@ -21,12 +21,11 @@ import com.alibaba.nacos.naming.core.v2.metadata.NamingMetadataManager; import com.alibaba.nacos.naming.core.v2.metadata.NamingMetadataOperateService; import com.alibaba.nacos.sys.env.EnvUtil; -import junit.framework.TestCase; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.env.MockEnvironment; import java.util.Set; @@ -34,37 +33,36 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class ExpiredMetadataCleanerTest extends TestCase { - +@ExtendWith(MockitoExtension.class) +class ExpiredMetadataCleanerTest { + private ExpiredMetadataCleaner expiredMetadataCleaner; - + @Mock private NamingMetadataManager metadataManagerMock; - + @Mock private NamingMetadataOperateService metadataOperateServiceMock; - + private Set set = new ConcurrentHashSet<>(); - + @Mock private ExpiredMetadataInfo expiredMetadataInfoMock; - - @Before - public void setUp() throws Exception { - super.setUp(); + + @BeforeEach + void setUp() throws Exception { EnvUtil.setEnvironment(new MockEnvironment()); expiredMetadataCleaner = new ExpiredMetadataCleaner(metadataManagerMock, metadataOperateServiceMock); - + set.add(expiredMetadataInfoMock); - + when(metadataManagerMock.getExpiredMetadataInfos()).thenReturn(set); when(expiredMetadataInfoMock.getCreateTime()).thenReturn(0L); when(metadataManagerMock.containServiceMetadata(expiredMetadataInfoMock.getService())).thenReturn(true); } - + @Test - public void testDoClean() { + void testDoClean() { expiredMetadataCleaner.doClean(); verify(metadataManagerMock).getExpiredMetadataInfos(); verify(metadataOperateServiceMock).deleteServiceMetadata(expiredMetadataInfoMock.getService()); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/AbstractClientTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/AbstractClientTest.java index c26e2894f45..327bd2d8984 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/AbstractClientTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/AbstractClientTest.java @@ -20,16 +20,19 @@ import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.naming.monitor.MetricsMonitor; import com.alibaba.nacos.naming.pojo.Subscriber; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collection; -@RunWith(MockitoJUnitRunner.class) -public class AbstractClientTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@ExtendWith(MockitoExtension.class) +class AbstractClientTest { private AbstractClient abstractClient; @@ -39,89 +42,88 @@ public class AbstractClientTest { private Subscriber subscriber; - @Before - public void setUp() { + @BeforeEach + void setUp() { abstractClient = new MockAbstractClient(0L); service = Service.newService("ns1", "group1", "serviceName001"); instancePublishInfo = new InstancePublishInfo("127.0.0.1", 8890); - subscriber = new Subscriber("127.0.0.1:8848", "agent1", "appName", "127.0.0.1", - "ns1", "serviceName001", 9090); + subscriber = new Subscriber("127.0.0.1:8848", "agent1", "appName", "127.0.0.1", "ns1", "serviceName001", 9090); MetricsMonitor.getIpCountMonitor().set(0); MetricsMonitor.getSubscriberCount().set(0); } @Test - public void addServiceInstance() { + void addServiceInstance() { boolean result = abstractClient.addServiceInstance(service, instancePublishInfo); - Assert.assertTrue(result); + assertTrue(result); } @Test - public void addServiceSubscriber() { - Assert.assertTrue(abstractClient.addServiceSubscriber(service, subscriber)); + void addServiceSubscriber() { + assertTrue(abstractClient.addServiceSubscriber(service, subscriber)); } @Test - public void testGetLastUpdatedTime() { - Assert.assertNotNull(abstractClient.getLastUpdatedTime()); + void testGetLastUpdatedTime() { + assertNotNull(abstractClient.getLastUpdatedTime()); } @Test - public void removeServiceInstanceSuccess() { + void removeServiceInstanceSuccess() { addServiceInstance(); InstancePublishInfo publishInfo = abstractClient.removeServiceInstance(service); - Assert.assertNotNull(publishInfo); + assertNotNull(publishInfo); } @Test - public void getInstancePublishInfo() { + void getInstancePublishInfo() { addServiceInstance(); InstancePublishInfo publishInfo = abstractClient.getInstancePublishInfo(service); - Assert.assertNotNull(publishInfo); + assertNotNull(publishInfo); } @Test - public void getAllPublishedService() { + void getAllPublishedService() { Collection allPublishedService = abstractClient.getAllPublishedService(); - Assert.assertNotNull(allPublishedService); + assertNotNull(allPublishedService); } @Test - public void removeServiceSubscriber() { + void removeServiceSubscriber() { boolean result = abstractClient.removeServiceSubscriber(service); - Assert.assertTrue(result); + assertTrue(result); } @Test - public void getSubscriber() { + void getSubscriber() { addServiceSubscriber(); Subscriber subscriber1 = abstractClient.getSubscriber(service); - Assert.assertNotNull(subscriber1); + assertNotNull(subscriber1); } @Test - public void getAllSubscribeService() { + void getAllSubscribeService() { Collection allSubscribeService = abstractClient.getAllSubscribeService(); - Assert.assertNotNull(allSubscribeService); + assertNotNull(allSubscribeService); } @Test - public void generateSyncData() { + void generateSyncData() { ClientSyncData clientSyncData = abstractClient.generateSyncData(); - Assert.assertNotNull(clientSyncData); + assertNotNull(clientSyncData); } @Test - public void release() { + void release() { abstractClient.addServiceInstance(service, instancePublishInfo); - Assert.assertEquals(1, MetricsMonitor.getIpCountMonitor().get()); + assertEquals(1, MetricsMonitor.getIpCountMonitor().get()); abstractClient.addServiceSubscriber(service, subscriber); - Assert.assertEquals(1, MetricsMonitor.getSubscriberCount().get()); + assertEquals(1, MetricsMonitor.getSubscriberCount().get()); abstractClient.release(); - Assert.assertEquals(0, MetricsMonitor.getSubscriberCount().get()); - Assert.assertEquals(0, MetricsMonitor.getIpCountMonitor().get()); + assertEquals(0, MetricsMonitor.getSubscriberCount().get()); + assertEquals(0, MetricsMonitor.getIpCountMonitor().get()); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/impl/ConnectionBasedClientTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/impl/ConnectionBasedClientTest.java index 0b9fc0acc7b..b5ac31e90fa 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/impl/ConnectionBasedClientTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/impl/ConnectionBasedClientTest.java @@ -17,15 +17,15 @@ package com.alibaba.nacos.naming.core.v2.client.impl; import com.alibaba.nacos.naming.misc.ClientConfig; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; -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 ConnectionBasedClientTest { +class ConnectionBasedClientTest { private final String connectionId = System.currentTimeMillis() + "_127.0.0.1_80"; @@ -33,33 +33,32 @@ public class ConnectionBasedClientTest { private ConnectionBasedClient connectionBasedClient; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { connectionBasedClient = new ConnectionBasedClient(connectionId, isNative, null); } @Test - public void testIsEphemeral() { + void testIsEphemeral() { assertTrue(connectionBasedClient.isEphemeral()); } @Test - public void testIsExpire() { + void testIsExpire() { connectionBasedClient.setLastRenewTime(); - long mustExpireTime = - connectionBasedClient.getLastRenewTime() + 2 * ClientConfig.getInstance().getClientExpiredTime(); + long mustExpireTime = connectionBasedClient.getLastRenewTime() + 2 * ClientConfig.getInstance().getClientExpiredTime(); assertTrue(connectionBasedClient.isExpire(mustExpireTime)); } @Test - public void testRecalculateRevision() { + void testRecalculateRevision() { assertEquals(0, connectionBasedClient.getRevision()); connectionBasedClient.recalculateRevision(); assertEquals(1, connectionBasedClient.getRevision()); } @Test - public void testRecalculateRevisionAsync() throws InterruptedException { + void testRecalculateRevisionAsync() throws InterruptedException { assertEquals(0, connectionBasedClient.getRevision()); for (int i = 0; i < 10; i++) { Thread thread = new Thread(() -> { diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/impl/IpPortBasedClientTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/impl/IpPortBasedClientTest.java index 15ad549b980..c346266ea59 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/impl/IpPortBasedClientTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/impl/IpPortBasedClientTest.java @@ -20,22 +20,22 @@ import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.naming.misc.ClientConfig; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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 org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.env.MockEnvironment; import java.util.Collection; -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; -@RunWith(MockitoJUnitRunner.class) -public class IpPortBasedClientTest { +@ExtendWith(MockitoExtension.class) +class IpPortBasedClientTest { private final String clientId = "127.0.0.1:80#true"; @@ -46,58 +46,57 @@ public class IpPortBasedClientTest { private InstancePublishInfo instancePublishInfo; - @BeforeClass - public static void setUpBeforeClass() { + @BeforeAll + static void setUpBeforeClass() { EnvUtil.setEnvironment(new MockEnvironment()); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { ipPortBasedClient = new IpPortBasedClient(clientId, true, 123L); ipPortBasedClient.init(); instancePublishInfo = new InstancePublishInfo(); } @Test - public void testGetClientId() { + void testGetClientId() { assertEquals(clientId, ipPortBasedClient.getClientId()); } @Test - public void testGetResponsibleId() { + void testGetResponsibleId() { String responsibleId = "127.0.0.1:80"; assertEquals(responsibleId, ipPortBasedClient.getResponsibleId()); } @Test - public void testIsExpire() { - long mustExpireTime = - ipPortBasedClient.getLastUpdatedTime() + ClientConfig.getInstance().getClientExpiredTime() * 2; + void testIsExpire() { + long mustExpireTime = ipPortBasedClient.getLastUpdatedTime() + ClientConfig.getInstance().getClientExpiredTime() * 2; assertTrue(ipPortBasedClient.isExpire(mustExpireTime)); } @Test - public void testGetAllInstancePublishInfo() { + void testGetAllInstancePublishInfo() { ipPortBasedClient.addServiceInstance(service, instancePublishInfo); Collection allInstancePublishInfo = ipPortBasedClient.getAllInstancePublishInfo(); - assertEquals(allInstancePublishInfo.size(), 1); + assertEquals(1, allInstancePublishInfo.size()); assertEquals(allInstancePublishInfo.iterator().next(), instancePublishInfo); } @Test - public void testRecalculateRevision() { + void testRecalculateRevision() { assertEquals(123L, ipPortBasedClient.getRevision()); assertEquals(-1531701243L, ipPortBasedClient.recalculateRevision()); } @Test - public void testConstructor0() { + void testConstructor0() { IpPortBasedClient client = new IpPortBasedClient(clientId, true); assertEquals(0, client.getRevision()); } - @After - public void tearDown() { + @AfterEach + void tearDown() { ipPortBasedClient.release(); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/manager/ClientManagerDelegateTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/manager/ClientManagerDelegateTest.java index f06993f79dc..dd782ce8060 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/manager/ClientManagerDelegateTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/manager/ClientManagerDelegateTest.java @@ -20,23 +20,27 @@ import com.alibaba.nacos.naming.core.v2.client.manager.impl.ConnectionBasedClientManager; import com.alibaba.nacos.naming.core.v2.client.manager.impl.EphemeralIpPortClientManager; import com.alibaba.nacos.naming.core.v2.client.manager.impl.PersistentIpPortClientManager; -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.Collection; import java.util.Collections; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class ClientManagerDelegateTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class ClientManagerDelegateTest { private final String connectionId = System.currentTimeMillis() + "_127.0.0.1_80"; @@ -57,10 +61,9 @@ public class ClientManagerDelegateTest { private ClientManagerDelegate delegate; - @Before - public void setUp() throws Exception { - delegate = new ClientManagerDelegate(connectionBasedClientManager, ephemeralIpPortClientManager, - persistentIpPortClientManager); + @BeforeEach + void setUp() throws Exception { + delegate = new ClientManagerDelegate(connectionBasedClientManager, ephemeralIpPortClientManager, persistentIpPortClientManager); when(connectionBasedClientManager.contains(connectionId)).thenReturn(true); when(ephemeralIpPortClientManager.contains(ephemeralIpPortId)).thenReturn(true); when(persistentIpPortClientManager.contains(persistentIpPortId)).thenReturn(true); @@ -70,7 +73,7 @@ public void setUp() throws Exception { } @Test - public void testChooseConnectionClient() { + void testChooseConnectionClient() { delegate.getClient(connectionId); verify(connectionBasedClientManager).getClient(connectionId); verify(ephemeralIpPortClientManager, never()).getClient(connectionId); @@ -78,7 +81,7 @@ public void testChooseConnectionClient() { } @Test - public void testChooseConnectionClientForV6() { + void testChooseConnectionClientForV6() { delegate.getClient(connectionIdForV6); verify(connectionBasedClientManager).getClient(connectionIdForV6); verify(ephemeralIpPortClientManager, never()).getClient(connectionIdForV6); @@ -86,7 +89,7 @@ public void testChooseConnectionClientForV6() { } @Test - public void testChooseEphemeralIpPortClient() { + void testChooseEphemeralIpPortClient() { DistroClientVerifyInfo verify = new DistroClientVerifyInfo(ephemeralIpPortId, 0); delegate.verifyClient(verify); verify(connectionBasedClientManager, never()).verifyClient(verify); @@ -95,7 +98,7 @@ public void testChooseEphemeralIpPortClient() { } @Test - public void testChoosePersistentIpPortClient() { + void testChoosePersistentIpPortClient() { DistroClientVerifyInfo verify = new DistroClientVerifyInfo(persistentIpPortId, 0); delegate.verifyClient(verify); verify(connectionBasedClientManager, never()).verifyClient(verify); @@ -104,27 +107,27 @@ public void testChoosePersistentIpPortClient() { } @Test - public void testContainsConnectionId() { + void testContainsConnectionId() { assertTrue(delegate.contains(connectionId)); } @Test - public void testContainsConnectionIdFailed() { + void testContainsConnectionIdFailed() { assertFalse(delegate.contains(connectionIdForV6)); } @Test - public void testContainsEphemeralIpPortId() { + void testContainsEphemeralIpPortId() { assertTrue(delegate.contains(ephemeralIpPortId)); } @Test - public void testContainsPersistentIpPortId() { + void testContainsPersistentIpPortId() { assertTrue(delegate.contains(persistentIpPortId)); } @Test - public void testAllClientId() { + void testAllClientId() { Collection actual = delegate.allClientId(); assertTrue(actual.contains(connectionId)); assertTrue(actual.contains(ephemeralIpPortId)); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/manager/impl/ConnectionBasedClientManagerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/manager/impl/ConnectionBasedClientManagerTest.java index c1d19859573..bffd0d2fd48 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/manager/impl/ConnectionBasedClientManagerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/manager/impl/ConnectionBasedClientManagerTest.java @@ -24,29 +24,33 @@ import com.alibaba.nacos.naming.core.v2.client.ClientAttributes; import com.alibaba.nacos.naming.core.v2.client.impl.ConnectionBasedClient; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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 org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.mock.env.MockEnvironment; import java.util.Collection; -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; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class ConnectionBasedClientManagerTest { - - ConnectionBasedClientManager connectionBasedClientManager; +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class ConnectionBasedClientManagerTest { private final String connectionId = System.currentTimeMillis() + "_127.0.0.1_80"; + ConnectionBasedClientManager connectionBasedClientManager; + @Mock private ConnectionBasedClient client; @@ -59,13 +63,13 @@ public class ConnectionBasedClientManagerTest { @Mock private ClientAttributes clientAttributes; - @BeforeClass - public static void setUpBeforeClass() { + @BeforeAll + static void setUpBeforeClass() { EnvUtil.setEnvironment(new MockEnvironment()); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { connectionBasedClientManager = new ConnectionBasedClientManager(); when(client.isNative()).thenReturn(true); when(connectionMeta.getConnectionId()).thenReturn(connectionId); @@ -80,7 +84,7 @@ public void setUp() throws Exception { } @Test - public void testAllClientId() { + void testAllClientId() { Collection allClientIds = connectionBasedClientManager.allClientId(); assertEquals(1, allClientIds.size()); assertTrue(connectionBasedClientManager.verifyClient(new DistroClientVerifyInfo(connectionId, 0))); @@ -88,7 +92,7 @@ public void testAllClientId() { } @Test - public void testContainsConnectionId() { + void testContainsConnectionId() { assertTrue(connectionBasedClientManager.verifyClient(new DistroClientVerifyInfo(connectionId, 0))); assertTrue(connectionBasedClientManager.contains(connectionId)); String unUsedClientId = "127.0.0.1:8888#true"; @@ -97,12 +101,12 @@ public void testContainsConnectionId() { } @Test - public void testIsResponsibleClient() { + void testIsResponsibleClient() { assertTrue(connectionBasedClientManager.isResponsibleClient(client)); } - @After - public void tearDown() { + @AfterEach + void tearDown() { connectionBasedClientManager.clientDisConnected(connection); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/manager/impl/EphemeralIpPortClientManagerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/manager/impl/EphemeralIpPortClientManagerTest.java index 62c8b7ad118..1df258b30f5 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/manager/impl/EphemeralIpPortClientManagerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/manager/impl/EphemeralIpPortClientManagerTest.java @@ -24,28 +24,34 @@ import com.alibaba.nacos.naming.core.v2.client.impl.IpPortBasedClient; import com.alibaba.nacos.naming.misc.SwitchDomain; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.mock.env.MockEnvironment; import java.util.Collection; -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; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class EphemeralIpPortClientManagerTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class EphemeralIpPortClientManagerTest { private final String ephemeralIpPortId = "127.0.0.1:80#true"; private final String syncedClientId = "127.0.0.1:8080#true"; + EphemeralIpPortClientManager ephemeralIpPortClientManager; + @Mock private IpPortBasedClient client; @@ -58,15 +64,13 @@ public class EphemeralIpPortClientManagerTest { @Mock private ClientAttributes attributes; - EphemeralIpPortClientManager ephemeralIpPortClientManager; - - @BeforeClass - public static void setUpBeforeClass() { + @BeforeAll + static void setUpBeforeClass() { EnvUtil.setEnvironment(new MockEnvironment()); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { ephemeralIpPortClientManager = new EphemeralIpPortClientManager(distroMapper, switchDomain); when(client.getClientId()).thenReturn(ephemeralIpPortId); when(client.getRevision()).thenReturn(1320L); @@ -76,13 +80,13 @@ public void setUp() throws Exception { } @Test - public void testGetClient() { + void testGetClient() { Client fetchedClient = ephemeralIpPortClientManager.getClient(ephemeralIpPortId); assertEquals(fetchedClient, client); } @Test - public void testAllClientId() { + void testAllClientId() { Collection allClientIds = ephemeralIpPortClientManager.allClientId(); assertEquals(2, allClientIds.size()); assertTrue(allClientIds.contains(ephemeralIpPortId)); @@ -90,7 +94,7 @@ public void testAllClientId() { } @Test - public void testContainsEphemeralIpPortId() { + void testContainsEphemeralIpPortId() { assertTrue(ephemeralIpPortClientManager.contains(ephemeralIpPortId)); assertTrue(ephemeralIpPortClientManager.contains(syncedClientId)); String unUsedClientId = "127.0.0.1:8888#true"; @@ -98,13 +102,13 @@ public void testContainsEphemeralIpPortId() { } @Test - public void testVerifyClient0() { + void testVerifyClient0() { assertTrue(ephemeralIpPortClientManager.verifyClient(new DistroClientVerifyInfo(ephemeralIpPortId, 0))); assertTrue(ephemeralIpPortClientManager.verifyClient(new DistroClientVerifyInfo(syncedClientId, 0))); } @Test - public void testVerifyClient() { + void testVerifyClient() { assertFalse(ephemeralIpPortClientManager.verifyClient(new DistroClientVerifyInfo(ephemeralIpPortId, 1))); assertTrue(ephemeralIpPortClientManager.verifyClient(new DistroClientVerifyInfo(ephemeralIpPortId, 1320))); assertFalse(ephemeralIpPortClientManager.verifyClient(new DistroClientVerifyInfo(syncedClientId, 1))); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/manager/impl/PersistentIpPortClientManagerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/manager/impl/PersistentIpPortClientManagerTest.java index 30d5931dcd3..3bdb05c2731 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/manager/impl/PersistentIpPortClientManagerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/manager/impl/PersistentIpPortClientManagerTest.java @@ -19,31 +19,32 @@ import com.alibaba.nacos.naming.consistency.ephemeral.distro.v2.DistroClientVerifyInfo; import com.alibaba.nacos.naming.core.v2.client.ClientAttributes; import com.alibaba.nacos.naming.core.v2.client.impl.IpPortBasedClient; -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.util.Collection; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class PersistentIpPortClientManagerTest { - - PersistentIpPortClientManager persistentIpPortClientManager; +@ExtendWith(MockitoExtension.class) +class PersistentIpPortClientManagerTest { private final String clientId = System.currentTimeMillis() + "_127.0.0.1_80"; private final String snapshotClientId = System.currentTimeMillis() + "_127.0.0.1_8080"; + PersistentIpPortClientManager persistentIpPortClientManager; + @Mock private ClientAttributes clientAttributes; @@ -53,44 +54,48 @@ public class PersistentIpPortClientManagerTest { @Mock private IpPortBasedClient snapshotClient; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { persistentIpPortClientManager = new PersistentIpPortClientManager(); when(client.getClientId()).thenReturn(clientId); persistentIpPortClientManager.clientConnected(client); } @Test - public void testAllClientId() { + void testAllClientId() { Collection allClientIds = persistentIpPortClientManager.allClientId(); assertEquals(1, allClientIds.size()); assertTrue(allClientIds.contains(clientId)); } @Test - public void testContains() { + void testContains() { assertTrue(persistentIpPortClientManager.contains(clientId)); String unUsedClientId = "127.0.0.1:8888#true"; assertFalse(persistentIpPortClientManager.contains(unUsedClientId)); } @Test - public void testIsResponsibleClient() { + void testIsResponsibleClient() { assertTrue(persistentIpPortClientManager.isResponsibleClient(client)); } - @Test(expected = UnsupportedOperationException.class) - public void makeSureSyncClientConnected() { - persistentIpPortClientManager.syncClientConnected(clientId, clientAttributes); + @Test + void makeSureSyncClientConnected() { + assertThrows(UnsupportedOperationException.class, () -> { + persistentIpPortClientManager.syncClientConnected(clientId, clientAttributes); + }); } - @Test(expected = UnsupportedOperationException.class) - public void makeSureNoVerify() { - persistentIpPortClientManager.verifyClient(new DistroClientVerifyInfo(clientId, 0)); + @Test + void makeSureNoVerify() { + assertThrows(UnsupportedOperationException.class, () -> { + persistentIpPortClientManager.verifyClient(new DistroClientVerifyInfo(clientId, 0)); + }); } @Test - public void testLoadFromSnapshot() { + void testLoadFromSnapshot() { ConcurrentMap snapshotClients = new ConcurrentHashMap<>(); snapshotClients.put(snapshotClientId, snapshotClient); persistentIpPortClientManager.loadFromSnapshot(snapshotClients); @@ -99,8 +104,8 @@ public void testLoadFromSnapshot() { assertTrue(allClientIds.contains(snapshotClientId)); } - @After - public void tearDown() { + @AfterEach + void tearDown() { persistentIpPortClientManager.clientDisconnected(clientId); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/event/publisher/NamingEventPublisherFactoryTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/event/publisher/NamingEventPublisherFactoryTest.java index 3e312629118..1c9615bfdcc 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/event/publisher/NamingEventPublisherFactoryTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/event/publisher/NamingEventPublisherFactoryTest.java @@ -18,9 +18,9 @@ import com.alibaba.nacos.common.notify.EventPublisher; import com.alibaba.nacos.common.notify.NotifyCenter; -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 org.springframework.util.ReflectionUtils; import java.lang.reflect.Field; @@ -28,14 +28,14 @@ import java.util.Map; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; -public class NamingEventPublisherFactoryTest { +class NamingEventPublisherFactoryTest { private Map originalEventPublisherMap; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { originalEventPublisherMap = new HashMap<>(NotifyCenter.getPublisherMap()); NotifyCenter.getPublisherMap().clear(); // Protect other unit test publisher affect this case. @@ -45,20 +45,20 @@ public void setUp() throws Exception { map.clear(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { NotifyCenter.getPublisherMap().clear(); NotifyCenter.getPublisherMap().putAll(originalEventPublisherMap); originalEventPublisherMap = null; } @Test - public void testApply() { + void testApply() { NamingEventPublisherFactory.getInstance().apply(TestEvent.TestEvent1.class, Byte.SIZE); NamingEventPublisherFactory.getInstance().apply(TestEvent.TestEvent2.class, Byte.SIZE); NamingEventPublisherFactory.getInstance().apply(TestEvent.class, Byte.SIZE); - String expectedStatus = "Naming event publisher statues:\n" - + "\tPublisher TestEvent : shutdown=false, queue= 0/8 \n"; + String expectedStatus = + "Naming event publisher statues:\n" + "\tPublisher TestEvent : shutdown=false, queue= 0/8 \n"; assertThat(NamingEventPublisherFactory.getInstance().getAllPublisherStatues(), is(expectedStatus)); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/event/publisher/NamingEventPublisherTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/event/publisher/NamingEventPublisherTest.java index 47ce15e8010..236f57d220e 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/event/publisher/NamingEventPublisherTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/event/publisher/NamingEventPublisherTest.java @@ -20,21 +20,21 @@ import com.alibaba.nacos.common.notify.listener.SmartSubscriber; import com.alibaba.nacos.common.notify.listener.Subscriber; import com.alibaba.nacos.common.utils.ThreadUtils; -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 static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -@RunWith(MockitoJUnitRunner.class) -public class NamingEventPublisherTest { +@ExtendWith(MockitoExtension.class) +class NamingEventPublisherTest { @Mock private Subscriber subscriber; @@ -44,19 +44,19 @@ public class NamingEventPublisherTest { private NamingEventPublisher namingEventPublisher; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { namingEventPublisher = new NamingEventPublisher(); namingEventPublisher.init(TestEvent.class, Byte.SIZE); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { namingEventPublisher.shutdown(); } @Test - public void testAddSubscriber() { + void testAddSubscriber() { namingEventPublisher.addSubscriber(subscriber, TestEvent.TestEvent1.class); namingEventPublisher.addSubscriber(smartSubscriber, TestEvent.TestEvent2.class); TestEvent.TestEvent1 testEvent1 = new TestEvent.TestEvent1(); @@ -69,7 +69,7 @@ public void testAddSubscriber() { } @Test - public void testRemoveSubscriber() { + void testRemoveSubscriber() { namingEventPublisher.addSubscriber(subscriber, TestEvent.TestEvent1.class); namingEventPublisher.addSubscriber(smartSubscriber, TestEvent.TestEvent1.class); TestEvent.TestEvent1 testEvent1 = new TestEvent.TestEvent1(); @@ -86,7 +86,7 @@ public void testRemoveSubscriber() { } @Test - public void testPublishOverFlow() { + void testPublishOverFlow() { TestEvent testEvent = new TestEvent(); for (int i = 0; i < Byte.SIZE; i++) { namingEventPublisher.publish(testEvent); @@ -97,7 +97,7 @@ public void testPublishOverFlow() { } @Test - public void getStatus() throws NacosException { + void getStatus() throws NacosException { namingEventPublisher.publish(new TestEvent()); namingEventPublisher.publish(new TestEvent.TestEvent1()); namingEventPublisher.publish(new TestEvent.TestEvent2()); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/index/ClientServiceIndexesManagerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/index/ClientServiceIndexesManagerTest.java index 0aa980ba64f..0c9bc8676a4 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/index/ClientServiceIndexesManagerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/index/ClientServiceIndexesManagerTest.java @@ -20,13 +20,12 @@ import com.alibaba.nacos.naming.core.v2.client.Client; import com.alibaba.nacos.naming.core.v2.event.client.ClientOperationEvent; import com.alibaba.nacos.naming.core.v2.pojo.Service; -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.lang.reflect.InvocationTargetException; @@ -38,8 +37,13 @@ import java.util.Set; import java.util.concurrent.ConcurrentMap; -@RunWith(MockitoJUnitRunner.class) -public class ClientServiceIndexesManagerTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@ExtendWith(MockitoExtension.class) +class ClientServiceIndexesManagerTest { + + private static final String NACOS = "nacos"; @Mock private Service service; @@ -55,76 +59,72 @@ public class ClientServiceIndexesManagerTest { private ClientServiceIndexesManager clientServiceIndexesManager; - private static final String NACOS = "nacos"; - - @Before - public void setUp() throws NoSuchFieldException, IllegalAccessException { + @BeforeEach + void setUp() throws NoSuchFieldException, IllegalAccessException { clientServiceIndexesManager = new ClientServiceIndexesManager(); Class clientServiceIndexesManagerClass = ClientServiceIndexesManager.class; Field publisherIndexesField = clientServiceIndexesManagerClass.getDeclaredField("publisherIndexes"); publisherIndexesField.setAccessible(true); - ConcurrentMap> publisherIndexes = (ConcurrentMap>) publisherIndexesField - .get(clientServiceIndexesManager); + ConcurrentMap> publisherIndexes = (ConcurrentMap>) publisherIndexesField.get( + clientServiceIndexesManager); publisherIndexes.put(service, new HashSet<>(Collections.singletonList(NACOS))); Field subscriberIndexesField = clientServiceIndexesManagerClass.getDeclaredField("subscriberIndexes"); subscriberIndexesField.setAccessible(true); - ConcurrentMap> subscriberIndexes = (ConcurrentMap>) subscriberIndexesField - .get(clientServiceIndexesManager); + ConcurrentMap> subscriberIndexes = (ConcurrentMap>) subscriberIndexesField.get( + clientServiceIndexesManager); subscriberIndexes.put(service, new HashSet<>(Collections.singletonList(NACOS))); } @Test - public void testGetAllClientsRegisteredService() { - Collection allClientsRegisteredService = clientServiceIndexesManager - .getAllClientsRegisteredService(service); + void testGetAllClientsRegisteredService() { + Collection allClientsRegisteredService = clientServiceIndexesManager.getAllClientsRegisteredService(service); - Assert.assertNotNull(allClientsRegisteredService); - Assert.assertEquals(allClientsRegisteredService.size(), 1); + assertNotNull(allClientsRegisteredService); + assertEquals(1, allClientsRegisteredService.size()); } @Test - public void testGetAllClientsSubscribeService() { + void testGetAllClientsSubscribeService() { - Collection allClientsSubscribeService = clientServiceIndexesManager - .getAllClientsSubscribeService(service); + Collection allClientsSubscribeService = clientServiceIndexesManager.getAllClientsSubscribeService(service); - Assert.assertNotNull(allClientsSubscribeService); - Assert.assertEquals(allClientsSubscribeService.size(), 1); + assertNotNull(allClientsSubscribeService); + assertEquals(1, allClientsSubscribeService.size()); } @Test - public void testGetSubscribedService() { + void testGetSubscribedService() { Collection subscribedService = clientServiceIndexesManager.getSubscribedService(); - Assert.assertNotNull(subscribedService); - Assert.assertEquals(subscribedService.size(), 1); + assertNotNull(subscribedService); + assertEquals(1, subscribedService.size()); } @Test - public void testRemovePublisherIndexesByEmptyService() throws NoSuchFieldException, IllegalAccessException { + void testRemovePublisherIndexesByEmptyService() throws NoSuchFieldException, IllegalAccessException { clientServiceIndexesManager.removePublisherIndexesByEmptyService(service); Class clientServiceIndexesManagerClass = ClientServiceIndexesManager.class; Field publisherIndexesField = clientServiceIndexesManagerClass.getDeclaredField("publisherIndexes"); publisherIndexesField.setAccessible(true); - ConcurrentMap> publisherIndexes = (ConcurrentMap>) publisherIndexesField - .get(clientServiceIndexesManager); + ConcurrentMap> publisherIndexes = (ConcurrentMap>) publisherIndexesField.get( + clientServiceIndexesManager); - Assert.assertEquals(publisherIndexes.size(), 1); + assertEquals(1, publisherIndexes.size()); } @Test - public void testSubscribeTypes() { + void testSubscribeTypes() { List> classes = clientServiceIndexesManager.subscribeTypes(); - Assert.assertNotNull(classes); - Assert.assertEquals(classes.size(), 5); + assertNotNull(classes); + assertEquals(5, classes.size()); } @Test - public void testOnEvent() { + void testOnEvent() { Mockito.when(clientReleaseEvent.getClient()).thenReturn(client); clientServiceIndexesManager.onEvent(clientReleaseEvent); @@ -137,71 +137,62 @@ public void testOnEvent() { } @Test - public void testAddPublisherIndexes() - throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + void testAddPublisherIndexes() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { String clientId = "clientId"; Class clientServiceIndexesManagerClass = ClientServiceIndexesManager.class; - Method addPublisherIndexes = clientServiceIndexesManagerClass - .getDeclaredMethod("addPublisherIndexes", Service.class, String.class); + Method addPublisherIndexes = clientServiceIndexesManagerClass.getDeclaredMethod("addPublisherIndexes", Service.class, String.class); addPublisherIndexes.setAccessible(true); addPublisherIndexes.invoke(clientServiceIndexesManager, service, clientId); - Collection allClientsSubscribeService = clientServiceIndexesManager - .getAllClientsRegisteredService(service); + Collection allClientsSubscribeService = clientServiceIndexesManager.getAllClientsRegisteredService(service); - Assert.assertNotNull(allClientsSubscribeService); - Assert.assertEquals(allClientsSubscribeService.size(), 2); + assertNotNull(allClientsSubscribeService); + assertEquals(2, allClientsSubscribeService.size()); } @Test - public void testRemovePublisherIndexes() - throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + void testRemovePublisherIndexes() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { String clientId = "clientId"; Class clientServiceIndexesManagerClass = ClientServiceIndexesManager.class; - Method removePublisherIndexes = clientServiceIndexesManagerClass - .getDeclaredMethod("removePublisherIndexes", Service.class, String.class); + Method removePublisherIndexes = clientServiceIndexesManagerClass.getDeclaredMethod("removePublisherIndexes", Service.class, + String.class); removePublisherIndexes.setAccessible(true); removePublisherIndexes.invoke(clientServiceIndexesManager, service, clientId); - Collection allClientsSubscribeService = clientServiceIndexesManager - .getAllClientsRegisteredService(service); + Collection allClientsSubscribeService = clientServiceIndexesManager.getAllClientsRegisteredService(service); - Assert.assertNotNull(allClientsSubscribeService); - Assert.assertEquals(allClientsSubscribeService.size(), 1); + assertNotNull(allClientsSubscribeService); + assertEquals(1, allClientsSubscribeService.size()); } @Test - public void testAddSubscriberIndexes() - throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + void testAddSubscriberIndexes() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { String clientId = "clientId"; Class clientServiceIndexesManagerClass = ClientServiceIndexesManager.class; - Method addSubscriberIndexes = clientServiceIndexesManagerClass - .getDeclaredMethod("addSubscriberIndexes", Service.class, String.class); + Method addSubscriberIndexes = clientServiceIndexesManagerClass.getDeclaredMethod("addSubscriberIndexes", Service.class, + String.class); addSubscriberIndexes.setAccessible(true); addSubscriberIndexes.invoke(clientServiceIndexesManager, service, clientId); - Collection allClientsSubscribeService = clientServiceIndexesManager - .getAllClientsSubscribeService(service); + Collection allClientsSubscribeService = clientServiceIndexesManager.getAllClientsSubscribeService(service); - Assert.assertNotNull(allClientsSubscribeService); - Assert.assertEquals(allClientsSubscribeService.size(), 2); + assertNotNull(allClientsSubscribeService); + assertEquals(2, allClientsSubscribeService.size()); } @Test - public void testRemoveSubscriberIndexes() - throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + void testRemoveSubscriberIndexes() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { String clientId = "clientId"; Class clientServiceIndexesManagerClass = ClientServiceIndexesManager.class; - Method removeSubscriberIndexes = clientServiceIndexesManagerClass - .getDeclaredMethod("removeSubscriberIndexes", Service.class, String.class); + Method removeSubscriberIndexes = clientServiceIndexesManagerClass.getDeclaredMethod("removeSubscriberIndexes", Service.class, + String.class); removeSubscriberIndexes.setAccessible(true); removeSubscriberIndexes.invoke(clientServiceIndexesManager, service, clientId); - Collection allClientsSubscribeService = clientServiceIndexesManager - .getAllClientsSubscribeService(service); + Collection allClientsSubscribeService = clientServiceIndexesManager.getAllClientsSubscribeService(service); - Assert.assertNotNull(allClientsSubscribeService); - Assert.assertEquals(allClientsSubscribeService.size(), 1); + assertNotNull(allClientsSubscribeService); + assertEquals(1, allClientsSubscribeService.size()); } } \ No newline at end of file diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/index/ServiceStorageTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/index/ServiceStorageTest.java index 2938a03cf8e..a63fd06058b 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/index/ServiceStorageTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/index/ServiceStorageTest.java @@ -23,13 +23,12 @@ import com.alibaba.nacos.naming.core.v2.pojo.InstancePublishInfo; import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.naming.misc.SwitchDomain; -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.lang.reflect.InvocationTargetException; @@ -41,8 +40,16 @@ import java.util.Set; import java.util.concurrent.ConcurrentMap; -@RunWith(MockitoJUnitRunner.class) -public class ServiceStorageTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@ExtendWith(MockitoExtension.class) +class ServiceStorageTest { + + private static final Service SERVICE = Service.newService("namespaceId", "groupName", "serviceName"); + + private static final String NACOS = "nacos"; @Mock private ClientServiceIndexesManager clientServiceIndexesManager; @@ -64,104 +71,96 @@ public class ServiceStorageTest { private ServiceStorage serviceStorage; - private static final Service SERVICE = Service.newService("namespaceId", "groupName", "serviceName"); - - private static final String NACOS = "nacos"; - - @Before - public void setUp() throws NoSuchFieldException, IllegalAccessException { - serviceStorage = new ServiceStorage(clientServiceIndexesManager, clientManagerDelegate, switchDomain, - namingMetadataManager); + @BeforeEach + void setUp() throws NoSuchFieldException, IllegalAccessException { + serviceStorage = new ServiceStorage(clientServiceIndexesManager, clientManagerDelegate, switchDomain, namingMetadataManager); Field serviceClusterIndex = ServiceStorage.class.getDeclaredField("serviceClusterIndex"); serviceClusterIndex.setAccessible(true); - ConcurrentMap> serviceSetConcurrentMap = (ConcurrentMap>) serviceClusterIndex - .get(serviceStorage); + ConcurrentMap> serviceSetConcurrentMap = (ConcurrentMap>) serviceClusterIndex.get( + serviceStorage); serviceSetConcurrentMap.put(SERVICE, new HashSet<>(Collections.singletonList(NACOS))); Field serviceDataIndexes = ServiceStorage.class.getDeclaredField("serviceDataIndexes"); serviceDataIndexes.setAccessible(true); - ConcurrentMap infoConcurrentMap = (ConcurrentMap) serviceDataIndexes - .get(serviceStorage); + ConcurrentMap infoConcurrentMap = (ConcurrentMap) serviceDataIndexes.get( + serviceStorage); infoConcurrentMap.put(SERVICE, serviceInfo); } @Test - public void testGetClusters() { + void testGetClusters() { Set clusters = serviceStorage.getClusters(SERVICE); - Assert.assertNotNull(clusters); + assertNotNull(clusters); for (String cluster : clusters) { - Assert.assertEquals(cluster, NACOS); + assertEquals(NACOS, cluster); } } @Test - public void testGetData() { + void testGetData() { ServiceInfo serviceInfo = serviceStorage.getData(SERVICE); - Assert.assertNotNull(serviceInfo); + assertNotNull(serviceInfo); } - @Test() - public void testGetPushData() { + @Test + void testGetPushData() { ServiceInfo pushData = serviceStorage.getPushData(SERVICE); Mockito.verify(switchDomain).getDefaultPushCacheMillis(); - Assert.assertNotNull(pushData); + assertNotNull(pushData); } @Test - public void testRemoveData() throws NoSuchFieldException, IllegalAccessException { + void testRemoveData() throws NoSuchFieldException, IllegalAccessException { serviceStorage.removeData(SERVICE); Field serviceClusterIndex = ServiceStorage.class.getDeclaredField("serviceClusterIndex"); serviceClusterIndex.setAccessible(true); - ConcurrentMap> serviceSetConcurrentMap = (ConcurrentMap>) serviceClusterIndex - .get(serviceStorage); + ConcurrentMap> serviceSetConcurrentMap = (ConcurrentMap>) serviceClusterIndex.get( + serviceStorage); Field serviceDataIndexes = ServiceStorage.class.getDeclaredField("serviceDataIndexes"); serviceDataIndexes.setAccessible(true); - ConcurrentMap infoConcurrentMap = (ConcurrentMap) serviceDataIndexes - .get(serviceStorage); + ConcurrentMap infoConcurrentMap = (ConcurrentMap) serviceDataIndexes.get( + serviceStorage); - Assert.assertEquals(serviceSetConcurrentMap.size(), 0); - Assert.assertEquals(infoConcurrentMap.size(), 0); + assertEquals(0, serviceSetConcurrentMap.size()); + assertEquals(0, infoConcurrentMap.size()); } @Test - public void testGetAllInstancesFromIndex() - throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + void testGetAllInstancesFromIndex() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Class serviceStorageClass = ServiceStorage.class; - Method getAllInstancesFromIndex = serviceStorageClass - .getDeclaredMethod("getAllInstancesFromIndex", Service.class); + Method getAllInstancesFromIndex = serviceStorageClass.getDeclaredMethod("getAllInstancesFromIndex", Service.class); getAllInstancesFromIndex.setAccessible(true); List list = (List) getAllInstancesFromIndex.invoke(serviceStorage, SERVICE); - Assert.assertNotNull(list); + assertNotNull(list); } @Test - public void testGetInstanceInfo() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + void testGetInstanceInfo() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Class serviceStorageClass = ServiceStorage.class; Method getInstanceInfo = serviceStorageClass.getDeclaredMethod("getInstanceInfo", String.class, Service.class); getInstanceInfo.setAccessible(true); - Optional optionalInstancePublishInfo = (Optional) getInstanceInfo - .invoke(serviceStorage, NACOS, SERVICE); + Optional optionalInstancePublishInfo = (Optional) getInstanceInfo.invoke(serviceStorage, + NACOS, SERVICE); - Assert.assertFalse(optionalInstancePublishInfo.isPresent()); + assertFalse(optionalInstancePublishInfo.isPresent()); } @Test - public void testParseInstance() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + void testParseInstance() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Class serviceStorageClass = ServiceStorage.class; - Method parseInstance = serviceStorageClass - .getDeclaredMethod("parseInstance", Service.class, InstancePublishInfo.class); + Method parseInstance = serviceStorageClass.getDeclaredMethod("parseInstance", Service.class, InstancePublishInfo.class); parseInstance.setAccessible(true); Instance instance = (Instance) parseInstance.invoke(serviceStorage, SERVICE, instancePublishInfo); Mockito.verify(namingMetadataManager).getInstanceMetadata(SERVICE, instancePublishInfo.getMetadataId()); - Assert.assertNotNull(instance); + assertNotNull(instance); } } \ No newline at end of file diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/metadata/MetadataOperationTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/metadata/MetadataOperationTest.java index 9d77e513974..338556616f6 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/metadata/MetadataOperationTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/metadata/MetadataOperationTest.java @@ -16,94 +16,96 @@ package com.alibaba.nacos.naming.core.v2.metadata; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; -@RunWith(MockitoJUnitRunner.class) -public class MetadataOperationTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +@ExtendWith(MockitoExtension.class) +class MetadataOperationTest { private MetadataOperation metadataOperation; - @Before - public void setUp() { + @BeforeEach + void setUp() { metadataOperation = new MetadataOperation(); } @Test - public void testGetNamespace() { + void testGetNamespace() { String namespace = metadataOperation.getNamespace(); - Assert.assertNull(namespace); + assertNull(namespace); } @Test - public void testSetNamespace() { + void testSetNamespace() { String namespace = "2398479283749823984"; metadataOperation.setNamespace(namespace); - Assert.assertEquals(metadataOperation.getNamespace(), namespace); + assertEquals(metadataOperation.getNamespace(), namespace); } @Test - public void testGetGroup() { + void testGetGroup() { String group = metadataOperation.getGroup(); - Assert.assertNull(group); + assertNull(group); } @Test - public void testSetGroup() { + void testSetGroup() { String group = "default"; metadataOperation.setGroup(group); - Assert.assertEquals(metadataOperation.getGroup(), group); + assertEquals(metadataOperation.getGroup(), group); } @Test - public void testGetServiceName() { + void testGetServiceName() { String serviceName = metadataOperation.getServiceName(); - Assert.assertNull(serviceName); + assertNull(serviceName); } @Test - public void testSetServiceName() { + void testSetServiceName() { String serviceName = "nacos"; metadataOperation.setServiceName(serviceName); - Assert.assertEquals(metadataOperation.getServiceName(), serviceName); + assertEquals(metadataOperation.getServiceName(), serviceName); } @Test - public void testGetTag() { + void testGetTag() { String tag = metadataOperation.getTag(); - Assert.assertNull(tag); + assertNull(tag); } @Test - public void testSetTag() { + void testSetTag() { String tag = "tag"; metadataOperation.setTag(tag); - Assert.assertEquals(metadataOperation.getTag(), tag); + assertEquals(metadataOperation.getTag(), tag); } @Test - public void testGetMetadata() { + void testGetMetadata() { Object metadata = metadataOperation.getMetadata(); - Assert.assertNull(metadata); + assertNull(metadata); } @Test - public void testSetMetadata() { + void testSetMetadata() { String metadata = "metadata"; metadataOperation.setMetadata(metadata); - Assert.assertEquals(metadataOperation.getMetadata(), metadata); + assertEquals(metadataOperation.getMetadata(), metadata); } } \ No newline at end of file diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/metadata/NamingMetadataManagerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/metadata/NamingMetadataManagerTest.java index 55f40b76fe7..ac6e6aed2fd 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/metadata/NamingMetadataManagerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/metadata/NamingMetadataManagerTest.java @@ -21,13 +21,12 @@ import com.alibaba.nacos.naming.core.v2.event.client.ClientEvent; import com.alibaba.nacos.naming.core.v2.event.metadata.MetadataEvent; import com.alibaba.nacos.naming.core.v2.pojo.Service; -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.List; @@ -37,8 +36,15 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -@RunWith(MockitoJUnitRunner.class) -public class NamingMetadataManagerTest { +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.assertTrue; + +@ExtendWith(MockitoExtension.class) +class NamingMetadataManagerTest { + + private static final String METADATA_ID = "METADATA_ID"; @Mock private Service service; @@ -63,61 +69,58 @@ public class NamingMetadataManagerTest { private NamingMetadataManager namingMetadataManager; - private static final String METADATA_ID = "METADATA_ID"; - - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { namingMetadataManager = new NamingMetadataManager(); Class namingMetadataManagerClass = NamingMetadataManager.class; Field serviceMetadataMapField = namingMetadataManagerClass.getDeclaredField("serviceMetadataMap"); serviceMetadataMapField.setAccessible(true); - ConcurrentMap serviceMetadataMap = (ConcurrentMap) serviceMetadataMapField - .get(namingMetadataManager); + ConcurrentMap serviceMetadataMap = (ConcurrentMap) serviceMetadataMapField.get( + namingMetadataManager); serviceMetadataMap.put(service, serviceMetadata); Field instanceMetadataMapField = namingMetadataManagerClass.getDeclaredField("instanceMetadataMap"); instanceMetadataMapField.setAccessible(true); - ConcurrentMap> instanceMetadataMap = - (ConcurrentMap>) instanceMetadataMapField.get(namingMetadataManager); ConcurrentMap concurrentMap = new ConcurrentHashMap<>(); concurrentMap.put(METADATA_ID, instanceMetadata); - instanceMetadataMap.put(service, concurrentMap); + ((ConcurrentMap>) instanceMetadataMapField.get(namingMetadataManager)).put(service, + concurrentMap); } @Test - public void testContainServiceMetadata() { + void testContainServiceMetadata() { boolean result = namingMetadataManager.containServiceMetadata(service); - Assert.assertTrue(result); + assertTrue(result); } @Test - public void testContainInstanceMetadata() { + void testContainInstanceMetadata() { boolean result = namingMetadataManager.containInstanceMetadata(service, METADATA_ID); - Assert.assertTrue(result); + assertTrue(result); } @Test - public void testGetServiceMetadata() { + void testGetServiceMetadata() { Optional serviceMetadata = namingMetadataManager.getServiceMetadata(service); - Assert.assertTrue(serviceMetadata.isPresent()); - Assert.assertNotNull(serviceMetadata.get()); + assertTrue(serviceMetadata.isPresent()); + assertNotNull(serviceMetadata.get()); } @Test - public void testGetInstanceMetadata() { + void testGetInstanceMetadata() { Optional instanceMetadata = namingMetadataManager.getInstanceMetadata(service, METADATA_ID); - Assert.assertTrue(instanceMetadata.isPresent()); - Assert.assertNotNull(instanceMetadata.get()); + assertTrue(instanceMetadata.isPresent()); + assertNotNull(instanceMetadata.get()); } @Test - public void testUpdateServiceMetadata() throws NoSuchFieldException, IllegalAccessException { + void testUpdateServiceMetadata() throws NoSuchFieldException, IllegalAccessException { ServiceMetadata serviceMetadata = new ServiceMetadata(); Class serviceMetadataClass = ServiceMetadata.class; @@ -128,13 +131,13 @@ public void testUpdateServiceMetadata() throws NoSuchFieldException, IllegalAcce namingMetadataManager.updateServiceMetadata(service, serviceMetadata); Optional optional = namingMetadataManager.getServiceMetadata(service); - Assert.assertTrue(optional.isPresent()); - Assert.assertNotNull(optional.get()); - Assert.assertFalse(optional.get().isEphemeral()); + assertTrue(optional.isPresent()); + assertNotNull(optional.get()); + assertFalse(optional.get().isEphemeral()); } @Test - public void testUpdateInstanceMetadata() throws NoSuchFieldException, IllegalAccessException { + void testUpdateInstanceMetadata() throws NoSuchFieldException, IllegalAccessException { InstanceMetadata instanceMetadata = new InstanceMetadata(); Class instanceMetadataClass = InstanceMetadata.class; Field enabled = instanceMetadataClass.getDeclaredField("enabled"); @@ -144,79 +147,77 @@ public void testUpdateInstanceMetadata() throws NoSuchFieldException, IllegalAcc namingMetadataManager.updateInstanceMetadata(service, METADATA_ID, instanceMetadata); Optional optional = namingMetadataManager.getInstanceMetadata(service, METADATA_ID); - Assert.assertTrue(optional.isPresent()); - Assert.assertNotNull(optional.get()); - Assert.assertFalse(optional.get().isEnabled()); + assertTrue(optional.isPresent()); + assertNotNull(optional.get()); + assertFalse(optional.get().isEnabled()); } @Test - public void testRemoveServiceMetadata() { + void testRemoveServiceMetadata() { namingMetadataManager.removeServiceMetadata(service); Optional serviceMetadata = namingMetadataManager.getServiceMetadata(service); - Assert.assertFalse(serviceMetadata.isPresent()); + assertFalse(serviceMetadata.isPresent()); } @Test - public void testRemoveInstanceMetadata() { + void testRemoveInstanceMetadata() { namingMetadataManager.removeInstanceMetadata(service, METADATA_ID); Optional instanceMetadata = namingMetadataManager.getInstanceMetadata(service, METADATA_ID); - Assert.assertFalse(instanceMetadata.isPresent()); + assertFalse(instanceMetadata.isPresent()); } @Test - public void testGetServiceMetadataSnapshot() { + void testGetServiceMetadataSnapshot() { Map serviceMetadataSnapshot = namingMetadataManager.getServiceMetadataSnapshot(); - Assert.assertEquals(serviceMetadataSnapshot.size(), 1); + assertEquals(1, serviceMetadataSnapshot.size()); } @Test - public void testGetInstanceMetadataSnapshot() { - Map> instanceMetadataSnapshot = namingMetadataManager - .getInstanceMetadataSnapshot(); + void testGetInstanceMetadataSnapshot() { + Map> instanceMetadataSnapshot = namingMetadataManager.getInstanceMetadataSnapshot(); - Assert.assertEquals(instanceMetadataSnapshot.size(), 1); + assertEquals(1, instanceMetadataSnapshot.size()); } @Test - public void testLoadServiceMetadataSnapshot() { + void testLoadServiceMetadataSnapshot() { namingMetadataManager.loadServiceMetadataSnapshot(new ConcurrentHashMap<>()); Map serviceMetadataSnapshot = namingMetadataManager.getServiceMetadataSnapshot(); - Assert.assertEquals(serviceMetadataSnapshot.size(), 0); + assertEquals(0, serviceMetadataSnapshot.size()); } @Test - public void testLoadInstanceMetadataSnapshot() { + void testLoadInstanceMetadataSnapshot() { namingMetadataManager.loadInstanceMetadataSnapshot(new ConcurrentHashMap<>()); - Map> instanceMetadataSnapshot = namingMetadataManager - .getInstanceMetadataSnapshot(); + Map> instanceMetadataSnapshot = namingMetadataManager.getInstanceMetadataSnapshot(); - Assert.assertEquals(instanceMetadataSnapshot.size(), 0); + assertEquals(0, instanceMetadataSnapshot.size()); } @Test - public void testGetExpiredMetadataInfos() { + void testGetExpiredMetadataInfos() { Set expiredMetadataInfos = namingMetadataManager.getExpiredMetadataInfos(); - Assert.assertNotNull(expiredMetadataInfos); + assertNotNull(expiredMetadataInfos); } @Test - public void testSubscribeTypes() { + void testSubscribeTypes() { List> classes = namingMetadataManager.subscribeTypes(); - Assert.assertEquals(classes.size(), 3); + assertEquals(3, classes.size()); } @Test - public void testOnEvent() { + void testOnEvent() { Mockito.when(instanceMetadataEvent.getService()).thenReturn(service); Mockito.when(instanceMetadataEvent.getMetadataId()).thenReturn(METADATA_ID); Mockito.when(serviceMetadataEvent.getService()).thenReturn(service); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/metadata/NamingMetadataOperateServiceTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/metadata/NamingMetadataOperateServiceTest.java index 9c5ac7fcf7e..20c0a1a66fc 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/metadata/NamingMetadataOperateServiceTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/metadata/NamingMetadataOperateServiceTest.java @@ -20,15 +20,17 @@ import com.alibaba.nacos.consistency.cp.CPProtocol; import com.alibaba.nacos.core.distributed.ProtocolManager; import com.alibaba.nacos.naming.core.v2.pojo.Service; -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; -@RunWith(MockitoJUnitRunner.class) -public class NamingMetadataOperateServiceTest { +import static org.junit.jupiter.api.Assertions.assertThrows; + +@ExtendWith(MockitoExtension.class) +class NamingMetadataOperateServiceTest { @Mock private ProtocolManager protocolManager; @@ -41,61 +43,71 @@ public class NamingMetadataOperateServiceTest { private NamingMetadataOperateService namingMetadataOperateService; - @Before - public void testSetUp() throws Exception { + @BeforeEach + void testSetUp() throws Exception { Mockito.when(protocolManager.getCpProtocol()).thenReturn(cpProtocol); namingMetadataOperateService = new NamingMetadataOperateService(protocolManager); } - @Test(expected = NacosRuntimeException.class) - public void testUpdateServiceMetadata() { - ServiceMetadata serviceMetadata = new ServiceMetadata(); - namingMetadataOperateService.updateServiceMetadata(service, serviceMetadata); - - Mockito.verify(service).getNamespace(); - Mockito.verify(service).getGroup(); - Mockito.verify(service).getName(); + @Test + void testUpdateServiceMetadata() { + assertThrows(NacosRuntimeException.class, () -> { + ServiceMetadata serviceMetadata = new ServiceMetadata(); + namingMetadataOperateService.updateServiceMetadata(service, serviceMetadata); + + Mockito.verify(service).getNamespace(); + Mockito.verify(service).getGroup(); + Mockito.verify(service).getName(); + }); } - @Test(expected = NacosRuntimeException.class) - public void testDeleteServiceMetadata() { - namingMetadataOperateService.deleteServiceMetadata(service); - - Mockito.verify(service).getNamespace(); - Mockito.verify(service).getGroup(); - Mockito.verify(service).getName(); + @Test + void testDeleteServiceMetadata() { + assertThrows(NacosRuntimeException.class, () -> { + namingMetadataOperateService.deleteServiceMetadata(service); + + Mockito.verify(service).getNamespace(); + Mockito.verify(service).getGroup(); + Mockito.verify(service).getName(); + }); } - @Test(expected = NacosRuntimeException.class) - public void testUpdateInstanceMetadata() { - String metadataId = "metadataId"; - InstanceMetadata instanceMetadata = new InstanceMetadata(); - namingMetadataOperateService.updateInstanceMetadata(service, metadataId, instanceMetadata); - - Mockito.verify(service).getNamespace(); - Mockito.verify(service).getGroup(); - Mockito.verify(service).getName(); + @Test + void testUpdateInstanceMetadata() { + assertThrows(NacosRuntimeException.class, () -> { + String metadataId = "metadataId"; + InstanceMetadata instanceMetadata = new InstanceMetadata(); + namingMetadataOperateService.updateInstanceMetadata(service, metadataId, instanceMetadata); + + Mockito.verify(service).getNamespace(); + Mockito.verify(service).getGroup(); + Mockito.verify(service).getName(); + }); } - @Test(expected = NacosRuntimeException.class) - public void testDeleteInstanceMetadata() { - String metadataId = "metadataId"; - namingMetadataOperateService.deleteInstanceMetadata(service, metadataId); - - Mockito.verify(service).getNamespace(); - Mockito.verify(service).getGroup(); - Mockito.verify(service).getName(); + @Test + void testDeleteInstanceMetadata() { + assertThrows(NacosRuntimeException.class, () -> { + String metadataId = "metadataId"; + namingMetadataOperateService.deleteInstanceMetadata(service, metadataId); + + Mockito.verify(service).getNamespace(); + Mockito.verify(service).getGroup(); + Mockito.verify(service).getName(); + }); } - @Test(expected = NacosRuntimeException.class) - public void testAddClusterMetadata() { - String clusterName = "clusterName"; - ClusterMetadata clusterMetadata = new ClusterMetadata(); - namingMetadataOperateService.addClusterMetadata(service, clusterName, clusterMetadata); - - Mockito.verify(service).getNamespace(); - Mockito.verify(service).getGroup(); - Mockito.verify(service).getName(); + @Test + void testAddClusterMetadata() { + assertThrows(NacosRuntimeException.class, () -> { + String clusterName = "clusterName"; + ClusterMetadata clusterMetadata = new ClusterMetadata(); + namingMetadataOperateService.addClusterMetadata(service, clusterName, clusterMetadata); + + Mockito.verify(service).getNamespace(); + Mockito.verify(service).getGroup(); + Mockito.verify(service).getName(); + }); } } \ No newline at end of file diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/metadata/ServiceMetadataProcessorTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/metadata/ServiceMetadataProcessorTest.java index 76ed0cdfc76..9665fcd5a5a 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/metadata/ServiceMetadataProcessorTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/metadata/ServiceMetadataProcessorTest.java @@ -30,23 +30,27 @@ import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.sys.utils.ApplicationUtils; import com.google.protobuf.ByteString; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.context.ConfigurableApplicationContext; import java.lang.reflect.Field; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -@RunWith(MockitoJUnitRunner.class) -public class ServiceMetadataProcessorTest { +@ExtendWith(MockitoExtension.class) +class ServiceMetadataProcessorTest { @Mock private NamingMetadataManager namingMetadataManager; @@ -65,8 +69,8 @@ public class ServiceMetadataProcessorTest { private ServiceMetadataProcessor serviceMetadataProcessor; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { Mockito.when(protocolManager.getCpProtocol()).thenReturn(cpProtocol); ApplicationUtils.injectContext(context); @@ -74,22 +78,22 @@ public void setUp() throws Exception { } @Test - public void testLoadSnapshotOperate() { + void testLoadSnapshotOperate() { List snapshotOperations = serviceMetadataProcessor.loadSnapshotOperate(); - Assert.assertNotNull(snapshotOperations); - Assert.assertEquals(snapshotOperations.size(), 1); + assertNotNull(snapshotOperations); + assertEquals(1, snapshotOperations.size()); } @Test - public void testOnRequest() { + void testOnRequest() { Response response = serviceMetadataProcessor.onRequest(ReadRequest.getDefaultInstance()); - Assert.assertNull(response); + assertNull(response); } @Test - public void testOnApply() throws NoSuchFieldException, IllegalAccessException { + void testOnApply() throws NoSuchFieldException, IllegalAccessException { WriteRequest defaultInstance = WriteRequest.getDefaultInstance(); Class writeRequestClass = WriteRequest.class; Field operation = writeRequestClass.getDeclaredField("operation_"); @@ -117,7 +121,7 @@ public void testOnApply() throws NoSuchFieldException, IllegalAccessException { Service singleton = ServiceManager.getInstance().getSingleton(service); namingMetadataManager.updateServiceMetadata(singleton, metadataOperation.getMetadata()); - Assert.assertTrue(addResponse.getSuccess()); + assertTrue(addResponse.getSuccess()); verify(namingMetadataManager).getServiceMetadata(service); verify(namingMetadataManager).updateServiceMetadata(service, serviceMetadata); @@ -125,7 +129,7 @@ public void testOnApply() throws NoSuchFieldException, IllegalAccessException { operation.set(defaultInstance, "CHANGE"); Response changeResponse = serviceMetadataProcessor.onApply(defaultInstance); - Assert.assertTrue(changeResponse.getSuccess()); + assertTrue(changeResponse.getSuccess()); verify(namingMetadataManager, times(2)).getServiceMetadata(service); verify(namingMetadataManager).updateServiceMetadata(service, serviceMetadata); @@ -133,7 +137,7 @@ public void testOnApply() throws NoSuchFieldException, IllegalAccessException { operation.set(defaultInstance, "DELETE"); Response deleteResponse = serviceMetadataProcessor.onApply(defaultInstance); - Assert.assertTrue(deleteResponse.getSuccess()); + assertTrue(deleteResponse.getSuccess()); verify(namingMetadataManager).removeServiceMetadata(service); verify(serviceStorage).removeData(service); @@ -141,13 +145,13 @@ public void testOnApply() throws NoSuchFieldException, IllegalAccessException { operation.set(defaultInstance, "VERIFY"); Response otherResponse = serviceMetadataProcessor.onApply(defaultInstance); - Assert.assertFalse(otherResponse.getSuccess()); + assertFalse(otherResponse.getSuccess()); } @Test - public void testGroup() { + void testGroup() { String group = serviceMetadataProcessor.group(); - Assert.assertEquals(group, Constants.SERVICE_METADATA); + assertEquals(Constants.SERVICE_METADATA, group); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/metadata/ServiceMetadataSnapshotOperationTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/metadata/ServiceMetadataSnapshotOperationTest.java index ca6a321e0fa..1b3f6743424 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/metadata/ServiceMetadataSnapshotOperationTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/metadata/ServiceMetadataSnapshotOperationTest.java @@ -19,13 +19,14 @@ import com.alibaba.nacos.consistency.SerializeFactory; import com.alibaba.nacos.consistency.Serializer; import com.alibaba.nacos.naming.core.v2.pojo.Service; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import java.io.InputStream; import java.util.HashMap; @@ -34,32 +35,36 @@ import java.util.concurrent.ConcurrentMap; import java.util.concurrent.locks.ReentrantReadWriteLock; -@RunWith(MockitoJUnitRunner.class) -public class ServiceMetadataSnapshotOperationTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class ServiceMetadataSnapshotOperationTest { @Mock private NamingMetadataManager namingMetadataManager; private ServiceMetadataSnapshotOperation serviceMetadataSnapshotOperation; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { Map map = new HashMap<>(); map.put(Service.newService("namespace", "group", "name"), new ServiceMetadata()); Mockito.when(namingMetadataManager.getServiceMetadataSnapshot()).thenReturn(map); - serviceMetadataSnapshotOperation = new ServiceMetadataSnapshotOperation(namingMetadataManager, - new ReentrantReadWriteLock()); + serviceMetadataSnapshotOperation = new ServiceMetadataSnapshotOperation(namingMetadataManager, new ReentrantReadWriteLock()); } @Test - public void testDumpSnapshot() { + void testDumpSnapshot() { InputStream inputStream = serviceMetadataSnapshotOperation.dumpSnapshot(); - Assert.assertNotNull(inputStream); + assertNotNull(inputStream); } @Test - public void testLoadSnapshot() { + void testLoadSnapshot() { ConcurrentMap map = new ConcurrentHashMap<>(); Service service = Service.newService("namespace", "group", "name"); map.put(service, new ServiceMetadata()); @@ -68,28 +73,28 @@ public void testLoadSnapshot() { serviceMetadataSnapshotOperation.loadSnapshot(aDefault.serialize(map)); Map serviceMetadataSnapshot = namingMetadataManager.getServiceMetadataSnapshot(); - Assert.assertNotNull(serviceMetadataSnapshot); - Assert.assertEquals(serviceMetadataSnapshot.size(), 1); + assertNotNull(serviceMetadataSnapshot); + assertEquals(1, serviceMetadataSnapshot.size()); } @Test - public void testGetSnapshotArchive() { + void testGetSnapshotArchive() { String snapshotArchive = serviceMetadataSnapshotOperation.getSnapshotArchive(); - Assert.assertEquals(snapshotArchive, "service_metadata.zip"); + assertEquals("service_metadata.zip", snapshotArchive); } @Test - public void testGetSnapshotSaveTag() { + void testGetSnapshotSaveTag() { String snapshotSaveTag = serviceMetadataSnapshotOperation.getSnapshotSaveTag(); - Assert.assertEquals(snapshotSaveTag, ServiceMetadataSnapshotOperation.class.getSimpleName() + ".SAVE"); + assertEquals(snapshotSaveTag, ServiceMetadataSnapshotOperation.class.getSimpleName() + ".SAVE"); } @Test - public void testGetSnapshotLoadTag() { + void testGetSnapshotLoadTag() { String snapshotLoadTag = serviceMetadataSnapshotOperation.getSnapshotLoadTag(); - Assert.assertEquals(snapshotLoadTag, ServiceMetadataSnapshotOperation.class.getSimpleName() + ".LOAD"); + assertEquals(snapshotLoadTag, ServiceMetadataSnapshotOperation.class.getSimpleName() + ".LOAD"); } } \ No newline at end of file diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/metadata/ServiceMetadataTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/metadata/ServiceMetadataTest.java index c3dc411af6c..b27581b5d7a 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/metadata/ServiceMetadataTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/metadata/ServiceMetadataTest.java @@ -19,115 +19,119 @@ import com.alibaba.nacos.api.selector.Selector; import com.alibaba.nacos.naming.selector.LabelSelector; import com.alibaba.nacos.naming.selector.NoneSelector; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.HashMap; import java.util.Map; -@RunWith(MockitoJUnitRunner.class) -public class ServiceMetadataTest { +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.assertTrue; + +@ExtendWith(MockitoExtension.class) +class ServiceMetadataTest { @Mock private ClusterMetadata clusterMetadata; private ServiceMetadata serviceMetadata; - @Before - public void setUp() { + @BeforeEach + void setUp() { serviceMetadata = new ServiceMetadata(); } @Test - public void testIsEphemeral() { - Assert.assertTrue(serviceMetadata.isEphemeral()); + void testIsEphemeral() { + assertTrue(serviceMetadata.isEphemeral()); } @Test - public void testSetEphemeral() { + void testSetEphemeral() { serviceMetadata.setEphemeral(false); - Assert.assertFalse(serviceMetadata.isEphemeral()); + assertFalse(serviceMetadata.isEphemeral()); } @Test - public void testGetProtectThreshold() { - Assert.assertEquals(serviceMetadata.getProtectThreshold(), 0.0F, 0); + void testGetProtectThreshold() { + assertEquals(0.0F, serviceMetadata.getProtectThreshold(), 0); } @Test - public void testSetProtectThreshold() { + void testSetProtectThreshold() { serviceMetadata.setProtectThreshold(1.0F); - Assert.assertEquals(serviceMetadata.getProtectThreshold(), 1.0F, 0); + assertEquals(1.0F, serviceMetadata.getProtectThreshold(), 0); } @Test - public void testGetSelector() { + void testGetSelector() { Selector selector = serviceMetadata.getSelector(); - Assert.assertNotNull(selector); + assertNotNull(selector); boolean result = selector instanceof NoneSelector; - Assert.assertTrue(result); + assertTrue(result); } @Test - public void testSetSelector() { + void testSetSelector() { LabelSelector labelSelector = new LabelSelector(); serviceMetadata.setSelector(labelSelector); Selector selector = serviceMetadata.getSelector(); - Assert.assertNotNull(selector); + assertNotNull(selector); boolean result = selector instanceof LabelSelector; - Assert.assertTrue(result); + assertTrue(result); } @Test - public void testGetExtendData() { + void testGetExtendData() { Map extendData = serviceMetadata.getExtendData(); - Assert.assertNotNull(extendData); - Assert.assertEquals(extendData.size(), 0); + assertNotNull(extendData); + assertEquals(0, extendData.size()); } @Test - public void testSetExtendData() { + void testSetExtendData() { Map extendData = new HashMap<>(); extendData.put("nacos", "nacos"); serviceMetadata.setExtendData(extendData); Map map = serviceMetadata.getExtendData(); - Assert.assertNotNull(map); - Assert.assertEquals(map.size(), 1); + assertNotNull(map); + assertEquals(1, map.size()); } @Test - public void testGetClusters() { + void testGetClusters() { Map clusters = serviceMetadata.getClusters(); - Assert.assertNotNull(clusters); - Assert.assertEquals(clusters.size(), 0); + assertNotNull(clusters); + assertEquals(0, clusters.size()); } @Test - public void testSetClusters() { + void testSetClusters() { Map clusters = new HashMap<>(); clusters.put("key", clusterMetadata); serviceMetadata.setClusters(clusters); Map map = serviceMetadata.getClusters(); - Assert.assertNotNull(map); - Assert.assertEquals(map.size(), 1); + assertNotNull(map); + assertEquals(1, map.size()); } @Test - public void testEquals() { + void testEquals() { ServiceMetadata serviceMetadata1 = new ServiceMetadata(); ServiceMetadata serviceMetadata2 = new ServiceMetadata(); boolean equals = serviceMetadata1.equals(serviceMetadata2); - Assert.assertFalse(equals); + assertFalse(equals); } } \ No newline at end of file diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/service/ClientOperationServiceProxyTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/service/ClientOperationServiceProxyTest.java index 0e2371c1ee9..e649a66c4a6 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/service/ClientOperationServiceProxyTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/service/ClientOperationServiceProxyTest.java @@ -23,18 +23,27 @@ import com.alibaba.nacos.naming.core.v2.service.impl.EphemeralClientOperationServiceImpl; import com.alibaba.nacos.naming.core.v2.service.impl.PersistentClientOperationServiceImpl; import com.alibaba.nacos.naming.pojo.Subscriber; -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 static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class ClientOperationServiceProxyTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class ClientOperationServiceProxyTest { + + private final String ephemeralIpPortId = System.currentTimeMillis() + "127.0.0.1:80#true"; + + private final String persistentIpPortId = System.currentTimeMillis() + "127.0.0.1:80#false"; + @Mock private EphemeralClientOperationServiceImpl ephemeralClientOperationServiceImpl; @@ -46,10 +55,6 @@ public class ClientOperationServiceProxyTest { @Mock private Service service; - private final String ephemeralIpPortId = System.currentTimeMillis() + "127.0.0.1:80#true"; - - private final String persistentIpPortId = System.currentTimeMillis() + "127.0.0.1:80#false"; - @Mock private Instance ephemeralInstance; @@ -59,60 +64,54 @@ public class ClientOperationServiceProxyTest { @Mock private Subscriber subscriber; - @Before - public void setUp() throws Exception { - clientOperationServiceProxy = new ClientOperationServiceProxy( - ephemeralClientOperationServiceImpl, persistentClientOperationServiceImpl); + @BeforeEach + void setUp() throws Exception { + clientOperationServiceProxy = new ClientOperationServiceProxy(ephemeralClientOperationServiceImpl, + persistentClientOperationServiceImpl); when(ephemeralInstance.isEphemeral()).thenReturn(true); when(persistentInstance.isEphemeral()).thenReturn(false); when(service.getNamespace()).thenReturn("public"); } @Test - public void testChooseEphemeralClientOperationService() throws NacosException { + void testChooseEphemeralClientOperationService() throws NacosException { // Test register. clientOperationServiceProxy.registerInstance(service, ephemeralInstance, ephemeralIpPortId); verify(ephemeralClientOperationServiceImpl).registerInstance(service, ephemeralInstance, ephemeralIpPortId); - verify(persistentClientOperationServiceImpl, never()) - .registerInstance(service, ephemeralInstance, ephemeralIpPortId); + verify(persistentClientOperationServiceImpl, never()).registerInstance(service, ephemeralInstance, ephemeralIpPortId); // Before service is registered. clientOperationServiceProxy.deregisterInstance(service, ephemeralInstance, ephemeralIpPortId); - verify(ephemeralClientOperationServiceImpl, never()) - .deregisterInstance(service, ephemeralInstance, ephemeralIpPortId); - verify(persistentClientOperationServiceImpl, never()) - .deregisterInstance(service, ephemeralInstance, ephemeralIpPortId); + verify(ephemeralClientOperationServiceImpl, never()).deregisterInstance(service, ephemeralInstance, ephemeralIpPortId); + verify(persistentClientOperationServiceImpl, never()).deregisterInstance(service, ephemeralInstance, ephemeralIpPortId); ServiceManager.getInstance().getSingleton(service); // Test deregister. clientOperationServiceProxy.deregisterInstance(service, ephemeralInstance, ephemeralIpPortId); verify(ephemeralClientOperationServiceImpl).deregisterInstance(service, ephemeralInstance, ephemeralIpPortId); - verify(persistentClientOperationServiceImpl, never()) - .deregisterInstance(service, ephemeralInstance, ephemeralIpPortId); + verify(persistentClientOperationServiceImpl, never()).deregisterInstance(service, ephemeralInstance, ephemeralIpPortId); } @Test - public void testChoosePersistentClientOperationService() throws NacosException { + void testChoosePersistentClientOperationService() throws NacosException { clientOperationServiceProxy.registerInstance(service, persistentInstance, persistentIpPortId); verify(persistentClientOperationServiceImpl).registerInstance(service, persistentInstance, persistentIpPortId); - verify(ephemeralClientOperationServiceImpl, never()) - .registerInstance(service, persistentInstance, persistentIpPortId); + verify(ephemeralClientOperationServiceImpl, never()).registerInstance(service, persistentInstance, persistentIpPortId); ServiceManager.getInstance().getSingleton(service); // Test deregister. clientOperationServiceProxy.deregisterInstance(service, persistentInstance, persistentIpPortId); verify(persistentClientOperationServiceImpl).deregisterInstance(service, persistentInstance, persistentIpPortId); - verify(ephemeralClientOperationServiceImpl, never()) - .deregisterInstance(service, persistentInstance, persistentIpPortId); + verify(ephemeralClientOperationServiceImpl, never()).deregisterInstance(service, persistentInstance, persistentIpPortId); } @Test - public void testSubscribeService() { + void testSubscribeService() { clientOperationServiceProxy.subscribeService(service, subscriber, ephemeralIpPortId); verify(ephemeralClientOperationServiceImpl).subscribeService(service, subscriber, ephemeralIpPortId); verify(persistentClientOperationServiceImpl, never()).subscribeService(service, subscriber, ephemeralIpPortId); } @Test - public void testUnsubscribeService() { + void testUnsubscribeService() { clientOperationServiceProxy.unsubscribeService(service, subscriber, ephemeralIpPortId); verify(ephemeralClientOperationServiceImpl).unsubscribeService(service, subscriber, ephemeralIpPortId); verify(persistentClientOperationServiceImpl, never()).unsubscribeService(service, subscriber, ephemeralIpPortId); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/service/impl/EphemeralClientOperationServiceImplTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/service/impl/EphemeralClientOperationServiceImplTest.java index 8ddbec03d2b..89e8a03dcdd 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/service/impl/EphemeralClientOperationServiceImplTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/service/impl/EphemeralClientOperationServiceImplTest.java @@ -25,27 +25,37 @@ import com.alibaba.nacos.naming.core.v2.client.manager.ClientManagerDelegate; import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.naming.pojo.Subscriber; -import junit.framework.TestCase; -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.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.ArrayList; import java.util.Collection; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class EphemeralClientOperationServiceImplTest extends TestCase { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class EphemeralClientOperationServiceImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); + private final String ipPortBasedClientId = "1.1.1.1:80#true"; + + private final String connectionBasedClientId = "test"; + + private final String ip = "1.1.1.1"; + + private final int port = 80; private EphemeralClientOperationServiceImpl ephemeralClientOperationServiceImpl; @@ -65,16 +75,8 @@ public class EphemeralClientOperationServiceImplTest extends TestCase { private Client connectionBasedClient; - private final String ipPortBasedClientId = "1.1.1.1:80#true"; - - private final String connectionBasedClientId = "test"; - - private final String ip = "1.1.1.1"; - - private final int port = 80; - - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { when(instance.getIp()).thenReturn(ip); when(instance.getPort()).thenReturn(port); when(service.getNamespace()).thenReturn("public"); @@ -87,25 +89,28 @@ public void setUp() throws Exception { when(clientManager.getClient(ipPortBasedClientId)).thenReturn(ipPortBasedClient); } - @Test(expected = NacosRuntimeException.class) - public void testRegisterPersistentInstance() throws NacosException { - when(service.isEphemeral()).thenReturn(false); - // Excepted exception - ephemeralClientOperationServiceImpl.registerInstance(service, instance, ipPortBasedClientId); + @Test + void testRegisterPersistentInstance() throws NacosException { + assertThrows(NacosRuntimeException.class, () -> { + when(service.isEphemeral()).thenReturn(false); + // Excepted exception + ephemeralClientOperationServiceImpl.registerInstance(service, instance, ipPortBasedClientId); + }); } @Test - public void testRegisterInstanceWithInvalidClusterName() throws NacosException { - expectedException.expect(NacosException.class); - expectedException.expectMessage( - "Instance 'clusterName' should be characters with only 0-9a-zA-Z-. (current: cluster1,cluster2)"); - - when(instance.getClusterName()).thenReturn("cluster1,cluster2"); - ephemeralClientOperationServiceImpl.registerInstance(service, instance, ipPortBasedClientId); + void testRegisterInstanceWithInvalidClusterName() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { + + when(instance.getClusterName()).thenReturn("cluster1,cluster2"); + ephemeralClientOperationServiceImpl.registerInstance(service, instance, ipPortBasedClientId); + }); + assertTrue(exception.getMessage() + .contains("Instance 'clusterName' should be characters with only 0-9a-zA-Z-. (current: cluster1,cluster2)")); } @Test - public void testRegisterAndDeregisterInstance() throws Exception { + void testRegisterAndDeregisterInstance() throws Exception { // Test register instance ephemeralClientOperationServiceImpl.registerInstance(service, instance, ipPortBasedClientId); assertTrue(ipPortBasedClient.getAllPublishedService().contains(service)); @@ -118,30 +123,30 @@ public void testRegisterAndDeregisterInstance() throws Exception { } @Test - public void testBatchRegisterAndDeregisterInstance() throws Exception { + void testBatchRegisterAndDeregisterInstance() throws Exception { // test Batch register instance - + Instance instance1 = new Instance(); instance1.setEphemeral(true); instance1.setIp("127.0.0.1"); instance1.setPort(9087); instance1.setHealthy(true); - + Instance instance2 = new Instance(); instance2.setEphemeral(true); instance2.setIp("127.0.0.2"); instance2.setPort(9045); instance2.setHealthy(true); - + List instances = new ArrayList<>(); instances.add(instance1); instances.add(instance2); ephemeralClientOperationServiceImpl.batchRegisterInstance(service, instances, connectionBasedClientId); assertTrue(connectionBasedClient.getAllPublishedService().contains(service)); } - + @Test - public void testSubscribeAndUnsubscribeService() throws Exception { + void testSubscribeAndUnsubscribeService() throws Exception { // Test subscribe instance ephemeralClientOperationServiceImpl.subscribeService(service, subscriber, ipPortBasedClientId); assertTrue(ipPortBasedClient.getAllSubscribeService().contains(service)); @@ -149,84 +154,104 @@ public void testSubscribeAndUnsubscribeService() throws Exception { ephemeralClientOperationServiceImpl.unsubscribeService(service, subscriber, ipPortBasedClientId); assertFalse(ipPortBasedClient.getAllSubscribeService().contains(service)); } - - @Test(expected = NacosRuntimeException.class) - public void testRegisterWhenClientNull() throws NacosException { - when(clientManager.getClient(anyString())).thenReturn(null); - // Excepted exception - ephemeralClientOperationServiceImpl.registerInstance(service, instance, ipPortBasedClientId); + + @Test + void testRegisterWhenClientNull() throws NacosException { + assertThrows(NacosRuntimeException.class, () -> { + when(clientManager.getClient(anyString())).thenReturn(null); + // Excepted exception + ephemeralClientOperationServiceImpl.registerInstance(service, instance, ipPortBasedClientId); + }); } - - @Test(expected = NacosRuntimeException.class) - public void testRegisterWhenClientPersistent() throws NacosException { - Client persistentClient = new IpPortBasedClient(ipPortBasedClientId, false); - when(clientManager.getClient(anyString())).thenReturn(persistentClient); - // Excepted exception - ephemeralClientOperationServiceImpl.registerInstance(service, instance, ipPortBasedClientId); + + @Test + void testRegisterWhenClientPersistent() throws NacosException { + assertThrows(NacosRuntimeException.class, () -> { + Client persistentClient = new IpPortBasedClient(ipPortBasedClientId, false); + when(clientManager.getClient(anyString())).thenReturn(persistentClient); + // Excepted exception + ephemeralClientOperationServiceImpl.registerInstance(service, instance, ipPortBasedClientId); + }); } - - @Test(expected = NacosRuntimeException.class) - public void testBatchRegisterWhenClientNull() { - when(clientManager.getClient(anyString())).thenReturn(null); - // Excepted exception - List instances = new ArrayList<>(); - ephemeralClientOperationServiceImpl.batchRegisterInstance(service, instances, ipPortBasedClientId); + + @Test + void testBatchRegisterWhenClientNull() { + assertThrows(NacosRuntimeException.class, () -> { + when(clientManager.getClient(anyString())).thenReturn(null); + // Excepted exception + List instances = new ArrayList<>(); + ephemeralClientOperationServiceImpl.batchRegisterInstance(service, instances, ipPortBasedClientId); + }); } - - @Test(expected = NacosRuntimeException.class) - public void testBatchRegisterWhenClientPersistent() { - Client persistentClient = new IpPortBasedClient(ipPortBasedClientId, false); - when(clientManager.getClient(anyString())).thenReturn(persistentClient); - // Excepted exception - List instances = new ArrayList<>(); - ephemeralClientOperationServiceImpl.batchRegisterInstance(service, instances, ipPortBasedClientId); + + @Test + void testBatchRegisterWhenClientPersistent() { + assertThrows(NacosRuntimeException.class, () -> { + Client persistentClient = new IpPortBasedClient(ipPortBasedClientId, false); + when(clientManager.getClient(anyString())).thenReturn(persistentClient); + // Excepted exception + List instances = new ArrayList<>(); + ephemeralClientOperationServiceImpl.batchRegisterInstance(service, instances, ipPortBasedClientId); + }); } - - @Test(expected = NacosRuntimeException.class) - public void testDeRegisterWhenClientNull() throws NacosException { - // Test register instance - ephemeralClientOperationServiceImpl.registerInstance(service, instance, ipPortBasedClientId); - when(clientManager.getClient(anyString())).thenReturn(null); - // Excepted exception - ephemeralClientOperationServiceImpl.registerInstance(service, instance, ipPortBasedClientId); + + @Test + void testDeRegisterWhenClientNull() throws NacosException { + assertThrows(NacosRuntimeException.class, () -> { + // Test register instance + ephemeralClientOperationServiceImpl.registerInstance(service, instance, ipPortBasedClientId); + when(clientManager.getClient(anyString())).thenReturn(null); + // Excepted exception + ephemeralClientOperationServiceImpl.registerInstance(service, instance, ipPortBasedClientId); + }); } - - @Test(expected = NacosRuntimeException.class) - public void testDeRegisterWhenClientPersistent() throws NacosException { - ephemeralClientOperationServiceImpl.registerInstance(service, instance, ipPortBasedClientId); - Client persistentClient = new IpPortBasedClient(ipPortBasedClientId, false); - when(clientManager.getClient(anyString())).thenReturn(persistentClient); - // Excepted exception - ephemeralClientOperationServiceImpl.deregisterInstance(service, instance, ipPortBasedClientId); + + @Test + void testDeRegisterWhenClientPersistent() throws NacosException { + assertThrows(NacosRuntimeException.class, () -> { + ephemeralClientOperationServiceImpl.registerInstance(service, instance, ipPortBasedClientId); + Client persistentClient = new IpPortBasedClient(ipPortBasedClientId, false); + when(clientManager.getClient(anyString())).thenReturn(persistentClient); + // Excepted exception + ephemeralClientOperationServiceImpl.deregisterInstance(service, instance, ipPortBasedClientId); + }); } - - @Test(expected = NacosRuntimeException.class) - public void testSubscribeWhenClientNull() { - when(clientManager.getClient(anyString())).thenReturn(null); - // Excepted exception - ephemeralClientOperationServiceImpl.subscribeService(service, subscriber, ipPortBasedClientId); + + @Test + void testSubscribeWhenClientNull() { + assertThrows(NacosRuntimeException.class, () -> { + when(clientManager.getClient(anyString())).thenReturn(null); + // Excepted exception + ephemeralClientOperationServiceImpl.subscribeService(service, subscriber, ipPortBasedClientId); + }); } - - @Test(expected = NacosRuntimeException.class) - public void testSubscribeWhenClientPersistent() { - Client persistentClient = new IpPortBasedClient(ipPortBasedClientId, false); - when(clientManager.getClient(anyString())).thenReturn(persistentClient); - // Excepted exception - ephemeralClientOperationServiceImpl.subscribeService(service, subscriber, ipPortBasedClientId); + + @Test + void testSubscribeWhenClientPersistent() { + assertThrows(NacosRuntimeException.class, () -> { + Client persistentClient = new IpPortBasedClient(ipPortBasedClientId, false); + when(clientManager.getClient(anyString())).thenReturn(persistentClient); + // Excepted exception + ephemeralClientOperationServiceImpl.subscribeService(service, subscriber, ipPortBasedClientId); + }); } - - @Test(expected = NacosRuntimeException.class) - public void testUnSubscribeWhenClientNull() { - when(clientManager.getClient(anyString())).thenReturn(null); - // Excepted exception - ephemeralClientOperationServiceImpl.unsubscribeService(service, subscriber, ipPortBasedClientId); + + @Test + void testUnSubscribeWhenClientNull() { + assertThrows(NacosRuntimeException.class, () -> { + when(clientManager.getClient(anyString())).thenReturn(null); + // Excepted exception + ephemeralClientOperationServiceImpl.unsubscribeService(service, subscriber, ipPortBasedClientId); + }); } - - @Test(expected = NacosRuntimeException.class) - public void testUnSubscribeWhenClientPersistent() { - Client persistentClient = new IpPortBasedClient(ipPortBasedClientId, false); - when(clientManager.getClient(anyString())).thenReturn(persistentClient); - // Excepted exception - ephemeralClientOperationServiceImpl.unsubscribeService(service, subscriber, ipPortBasedClientId); + + @Test + void testUnSubscribeWhenClientPersistent() { + assertThrows(NacosRuntimeException.class, () -> { + Client persistentClient = new IpPortBasedClient(ipPortBasedClientId, false); + when(clientManager.getClient(anyString())).thenReturn(persistentClient); + // Excepted exception + ephemeralClientOperationServiceImpl.unsubscribeService(service, subscriber, ipPortBasedClientId); + }); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/service/impl/PersistentClientOperationServiceImplTest.java b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/service/impl/PersistentClientOperationServiceImplTest.java index 65157a8ddec..60c6a0a0041 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/core/v2/service/impl/PersistentClientOperationServiceImplTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/core/v2/service/impl/PersistentClientOperationServiceImplTest.java @@ -31,25 +31,33 @@ import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.naming.pojo.Subscriber; import com.alibaba.nacos.sys.utils.ApplicationUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.context.ConfigurableApplicationContext; import java.lang.reflect.Field; import java.util.Collections; +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.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class PersistentClientOperationServiceImplTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class PersistentClientOperationServiceImplTest { + + private final String clientId = "1.1.1.1:80#false"; private PersistentClientOperationServiceImpl persistentClientOperationServiceImpl; @@ -74,37 +82,36 @@ public class PersistentClientOperationServiceImplTest { @Mock private CPProtocol cpProtocol; - private final String clientId = "1.1.1.1:80#false"; - @Mock private Serializer serializer; - + @Mock private IpPortBasedClient ipPortBasedClient; - - @Before - public void setUp() throws Exception { + + @BeforeEach + void setUp() throws Exception { when(service.getNamespace()).thenReturn("n"); when(applicationContext.getBean(ProtocolManager.class)).thenReturn(protocolManager); when(protocolManager.getCpProtocol()).thenReturn(cpProtocol); - when(serializer.serialize(any(PersistentClientOperationServiceImpl.InstanceStoreRequest.class))) - .thenReturn(new byte[1]); + when(serializer.serialize(any(PersistentClientOperationServiceImpl.InstanceStoreRequest.class))).thenReturn(new byte[1]); ApplicationUtils.injectContext(applicationContext); Field serializerField = PersistentClientOperationServiceImpl.class.getDeclaredField("serializer"); serializerField.setAccessible(true); persistentClientOperationServiceImpl = new PersistentClientOperationServiceImpl(clientManager); serializerField.set(persistentClientOperationServiceImpl, serializer); - + } - @Test(expected = NacosRuntimeException.class) - public void testRegisterPersistentInstance() { - when(service.isEphemeral()).thenReturn(true); - persistentClientOperationServiceImpl.registerInstance(service, instance, clientId); + @Test + void testRegisterPersistentInstance() { + assertThrows(NacosRuntimeException.class, () -> { + when(service.isEphemeral()).thenReturn(true); + persistentClientOperationServiceImpl.registerInstance(service, instance, clientId); + }); } @Test - public void testRegisterAndDeregisterInstance() throws Exception { + void testRegisterAndDeregisterInstance() throws Exception { Field clientManagerField = PersistentClientOperationServiceImpl.class.getDeclaredField("clientManager"); clientManagerField.setAccessible(true); // Test register instance @@ -114,33 +121,39 @@ public void testRegisterAndDeregisterInstance() throws Exception { persistentClientOperationServiceImpl.deregisterInstance(service, instance, clientId); verify(cpProtocol, times(2)).write(any(WriteRequest.class)); } - + @Test - public void updateInstance() throws Exception { + void updateInstance() throws Exception { Field clientManagerField = PersistentClientOperationServiceImpl.class.getDeclaredField("clientManager"); clientManagerField.setAccessible(true); // Test register instance persistentClientOperationServiceImpl.updateInstance(service, instance, clientId); verify(cpProtocol).write(any(WriteRequest.class)); } - - @Test(expected = UnsupportedOperationException.class) - public void testSubscribeService() { - persistentClientOperationServiceImpl.subscribeService(service, subscriber, clientId); + + @Test + void testSubscribeService() { + assertThrows(UnsupportedOperationException.class, () -> { + persistentClientOperationServiceImpl.subscribeService(service, subscriber, clientId); + }); } - @Test(expected = UnsupportedOperationException.class) - public void testUnsubscribeService() { - persistentClientOperationServiceImpl.unsubscribeService(service, subscriber, clientId); + @Test + void testUnsubscribeService() { + assertThrows(UnsupportedOperationException.class, () -> { + persistentClientOperationServiceImpl.unsubscribeService(service, subscriber, clientId); + }); } - @Test(expected = UnsupportedOperationException.class) - public void testOnRequest() { - persistentClientOperationServiceImpl.onRequest(ReadRequest.newBuilder().build()); + @Test + void testOnRequest() { + assertThrows(UnsupportedOperationException.class, () -> { + persistentClientOperationServiceImpl.onRequest(ReadRequest.newBuilder().build()); + }); } @Test - public void testOnApply() { + void testOnApply() { PersistentClientOperationServiceImpl.InstanceStoreRequest request = new PersistentClientOperationServiceImpl.InstanceStoreRequest(); Service service1 = Service.newService("A", "B", "C"); request.setService(service1); @@ -150,39 +163,31 @@ public void testOnApply() { Mockito.when(serializer.deserialize(Mockito.any())).thenReturn(request); Mockito.when(clientManager.contains(Mockito.anyString())).thenReturn(true); - + IpPortBasedClient ipPortBasedClient = Mockito.mock(IpPortBasedClient.class); Mockito.when(clientManager.getClient(Mockito.anyString())).thenReturn(ipPortBasedClient); - WriteRequest writeRequest = WriteRequest.newBuilder() - .setOperation(DataOperation.ADD.name()) - .build(); + WriteRequest writeRequest = WriteRequest.newBuilder().setOperation(DataOperation.ADD.name()).build(); Response response = persistentClientOperationServiceImpl.onApply(writeRequest); - Assert.assertTrue(response.getSuccess()); - Assert.assertTrue(ServiceManager.getInstance().containSingleton(service1)); - writeRequest = WriteRequest.newBuilder() - .setOperation(DataOperation.DELETE.name()) - .build(); + assertTrue(response.getSuccess()); + assertTrue(ServiceManager.getInstance().containSingleton(service1)); + writeRequest = WriteRequest.newBuilder().setOperation(DataOperation.DELETE.name()).build(); response = persistentClientOperationServiceImpl.onApply(writeRequest); - Assert.assertTrue(response.getSuccess()); + assertTrue(response.getSuccess()); ServiceManager.getInstance().removeSingleton(service1); - - writeRequest = WriteRequest.newBuilder() - .setOperation(DataOperation.VERIFY.name()) - .build(); + + writeRequest = WriteRequest.newBuilder().setOperation(DataOperation.VERIFY.name()).build(); response = persistentClientOperationServiceImpl.onApply(writeRequest); - Assert.assertFalse(response.getSuccess()); - - writeRequest = WriteRequest.newBuilder() - .setOperation(DataOperation.CHANGE.name()) - .build(); + assertFalse(response.getSuccess()); + + writeRequest = WriteRequest.newBuilder().setOperation(DataOperation.CHANGE.name()).build(); response = persistentClientOperationServiceImpl.onApply(writeRequest); - Assert.assertTrue(response.getSuccess()); - Assert.assertFalse(ServiceManager.getInstance().containSingleton(service1)); + assertTrue(response.getSuccess()); + assertFalse(ServiceManager.getInstance().containSingleton(service1)); } - + @Test - public void testOnApplyChange() { + void testOnApplyChange() { PersistentClientOperationServiceImpl.InstanceStoreRequest request = new PersistentClientOperationServiceImpl.InstanceStoreRequest(); Service service1 = Service.newService("A", "B", "C"); request.setService(service1); @@ -192,19 +197,13 @@ public void testOnApplyChange() { Mockito.when(clientManager.contains(Mockito.anyString())).thenReturn(true); when(clientManager.getClient(Mockito.anyString())).thenReturn(ipPortBasedClient); when(ipPortBasedClient.getAllPublishedService()).thenReturn(Collections.singletonList(service1)); - WriteRequest writeRequest = WriteRequest.newBuilder() - .setOperation(DataOperation.ADD.name()) - .build(); - writeRequest = WriteRequest.newBuilder() - .setOperation(DataOperation.ADD.name()) - .build(); + WriteRequest writeRequest = WriteRequest.newBuilder().setOperation(DataOperation.ADD.name()).build(); + writeRequest = WriteRequest.newBuilder().setOperation(DataOperation.ADD.name()).build(); Response response = persistentClientOperationServiceImpl.onApply(writeRequest); - Assert.assertTrue(response.getSuccess()); - writeRequest = WriteRequest.newBuilder() - .setOperation(DataOperation.CHANGE.name()) - .build(); + assertTrue(response.getSuccess()); + writeRequest = WriteRequest.newBuilder().setOperation(DataOperation.CHANGE.name()).build(); response = persistentClientOperationServiceImpl.onApply(writeRequest); - Assert.assertTrue(response.getSuccess()); - Assert.assertTrue(ServiceManager.getInstance().containSingleton(service1)); + assertTrue(response.getSuccess()); + assertTrue(ServiceManager.getInstance().containSingleton(service1)); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/exception/ResponseExceptionHandlerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/exception/ResponseExceptionHandlerTest.java index e1376309606..9b7d2935d71 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/exception/ResponseExceptionHandlerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/exception/ResponseExceptionHandlerTest.java @@ -19,13 +19,13 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; import com.alibaba.nacos.naming.controllers.v2.InstanceControllerV2; -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.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; @@ -38,53 +38,46 @@ import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @WebAppConfiguration @ContextConfiguration(classes = {ResponseExceptionHandler.class}) -public class ResponseExceptionHandlerTest { - +class ResponseExceptionHandlerTest { + private MockMvc mockMvc; - + @Autowired private WebApplicationContext context; - + @MockBean private InstanceControllerV2 instanceControllerV2; - - @Before - public void before() { + + @BeforeEach + void before() { mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); } - + @Test - public void testNacosRunTimeExceptionHandler() throws Exception { + void testNacosRunTimeExceptionHandler() throws Exception { // 设置InstanceControllerV2的行为,使其抛出NacosRuntimeException并被ResponseExceptionHandler捕获处理 - when(instanceControllerV2.register(any())) - .thenThrow(new NacosRuntimeException(NacosException.INVALID_PARAM)) - .thenThrow(new NacosRuntimeException(NacosException.SERVER_ERROR)) - .thenThrow(new NacosRuntimeException(503)); - + when(instanceControllerV2.register(any())).thenThrow(new NacosRuntimeException(NacosException.INVALID_PARAM)) + .thenThrow(new NacosRuntimeException(NacosException.SERVER_ERROR)).thenThrow(new NacosRuntimeException(503)); + // 执行请求并验证响应码 - ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders.post("/v2/ns/instance") - .param("namespaceId", "public").param("groupName", "G") - .param("serviceName", "s").param("ip", "192.168.0.1") - .param("port", "8080").param("ephemeral", "true")); + ResultActions resultActions = mockMvc.perform( + MockMvcRequestBuilders.post("/v2/ns/instance").param("namespaceId", "public").param("groupName", "G") + .param("serviceName", "s").param("ip", "192.168.0.1").param("port", "8080").param("ephemeral", "true")); resultActions.andExpect(MockMvcResultMatchers.status().is(NacosException.INVALID_PARAM)); - + // 执行请求并验证响应码 - ResultActions resultActions1 = mockMvc.perform(post("/v2/ns/instance") - .param("namespaceId", "public").param("groupName", "G") - .param("serviceName", "s").param("ip", "192.168.0.1") - .param("port", "8080") - .param("ephemeral", "true")); + ResultActions resultActions1 = mockMvc.perform( + post("/v2/ns/instance").param("namespaceId", "public").param("groupName", "G").param("serviceName", "s") + .param("ip", "192.168.0.1").param("port", "8080").param("ephemeral", "true")); resultActions1.andExpect(MockMvcResultMatchers.status().is(NacosException.SERVER_ERROR)); - + // 执行请求并验证响应码 - ResultActions resultActions2 = mockMvc.perform(post("/v2/ns/instance") - .param("namespaceId", "public").param("groupName", "G") - .param("serviceName", "s").param("ip", "192.168.0.1") - .param("port", "8080") - .param("ephemeral", "true")); + ResultActions resultActions2 = mockMvc.perform( + post("/v2/ns/instance").param("namespaceId", "public").param("groupName", "G").param("serviceName", "s") + .param("ip", "192.168.0.1").param("port", "8080").param("ephemeral", "true")); resultActions2.andExpect(MockMvcResultMatchers.status().is(503)); } } \ No newline at end of file diff --git a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/extend/HealthCheckExtendProviderTest.java b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/extend/HealthCheckExtendProviderTest.java index 932408f452a..26947b325ab 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/extend/HealthCheckExtendProviderTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/extend/HealthCheckExtendProviderTest.java @@ -18,43 +18,43 @@ import com.alibaba.nacos.api.naming.pojo.healthcheck.AbstractHealthChecker; import com.alibaba.nacos.naming.healthcheck.v2.processor.HealthCheckProcessorV2; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.beans.factory.config.SingletonBeanRegistry; import org.springframework.test.util.ReflectionTestUtils; import java.util.ArrayList; import java.util.Collection; -@RunWith(MockitoJUnitRunner.class) -public class HealthCheckExtendProviderTest { - +@ExtendWith(MockitoExtension.class) +class HealthCheckExtendProviderTest { + @Mock private SingletonBeanRegistry registry; - + private HealthCheckExtendProvider healthCheckExtendProvider; - - @Before - public void setUp() throws Exception { + + @BeforeEach + void setUp() throws Exception { healthCheckExtendProvider = new HealthCheckExtendProvider(); - + AbstractHealthCheckProcessorExtend checkProcessorExtend = new HealthCheckProcessorExtendV2(); Collection processors = new ArrayList<>(); processors.add(new TestHealthCheckProcessor()); ReflectionTestUtils.setField(checkProcessorExtend, "processors", processors); ReflectionTestUtils.setField(checkProcessorExtend, "registry", registry); healthCheckExtendProvider.setHealthCheckProcessorExtend(checkProcessorExtend); - + Collection checkers = new ArrayList<>(); checkers.add(new TestChecker()); ReflectionTestUtils.setField(healthCheckExtendProvider, "checkers", checkers); } - + @Test - public void init() { + void init() { healthCheckExtendProvider.init(); } } \ No newline at end of file diff --git a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/extend/HealthCheckProcessorExtendV2Test.java b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/extend/HealthCheckProcessorExtendV2Test.java index c9dc6ba3a76..5947c316f05 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/extend/HealthCheckProcessorExtendV2Test.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/extend/HealthCheckProcessorExtendV2Test.java @@ -18,11 +18,11 @@ import com.alibaba.nacos.naming.healthcheck.v2.processor.HealthCheckProcessorV2; import com.alibaba.nacos.naming.healthcheck.v2.processor.MysqlHealthCheckProcessor; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.beans.factory.config.SingletonBeanRegistry; import org.springframework.test.util.ReflectionTestUtils; @@ -33,34 +33,34 @@ import static org.mockito.Mockito.verify; -@RunWith(MockitoJUnitRunner.class) -public class HealthCheckProcessorExtendV2Test { - +@ExtendWith(MockitoExtension.class) +class HealthCheckProcessorExtendV2Test { + @Mock private SingletonBeanRegistry registry; - + @Mock private MysqlHealthCheckProcessor mysqlProcessor; - + private HealthCheckProcessorExtendV2 healthCheckProcessorExtendV2; - - @Before - public void setUp() { + + @BeforeEach + void setUp() { healthCheckProcessorExtendV2 = new HealthCheckProcessorExtendV2(); Collection processors = new ArrayList<>(); processors.add(mysqlProcessor); - + ReflectionTestUtils.setField(healthCheckProcessorExtendV2, "processors", processors); ReflectionTestUtils.setField(healthCheckProcessorExtendV2, "registry", registry); } - + @Test - public void addProcessor() { + void addProcessor() { Set origin = new HashSet<>(); origin.add("HTTP"); healthCheckProcessorExtendV2.addProcessor(origin); - - verify(registry).registerSingleton(healthCheckProcessorExtendV2 - .lowerFirstChar(mysqlProcessor.getClass().getSimpleName()), mysqlProcessor); + + verify(registry).registerSingleton(healthCheckProcessorExtendV2.lowerFirstChar(mysqlProcessor.getClass().getSimpleName()), + mysqlProcessor); } } \ No newline at end of file diff --git a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/extend/TestChecker.java b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/extend/TestChecker.java index 1df7abe916e..ef49f32e4ef 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/extend/TestChecker.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/extend/TestChecker.java @@ -24,15 +24,15 @@ * @author sunmengying */ public class TestChecker extends AbstractHealthChecker { - + public static final String TYPE = "TEST"; - + private static final long serialVersionUID = -240631834097384337L; - + public TestChecker() { super(TYPE); } - + @Override public AbstractHealthChecker clone() { return new TestChecker(); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/extend/TestHealthCheckProcessor.java b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/extend/TestHealthCheckProcessor.java index 1f22fc04812..f758bc69752 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/extend/TestHealthCheckProcessor.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/extend/TestHealthCheckProcessor.java @@ -27,14 +27,14 @@ * @author sunmengying */ public class TestHealthCheckProcessor implements HealthCheckProcessorV2 { - + public static final String TYPE = TestChecker.TYPE; - + @Override public void process(HealthCheckTaskV2 task, Service service, ClusterMetadata metadata) { - + } - + @Override public String getType() { return TYPE; diff --git a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/heartbeat/ClientBeatCheckTaskV2Test.java b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/heartbeat/ClientBeatCheckTaskV2Test.java index 5be6b05e805..860e6d37367 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/heartbeat/ClientBeatCheckTaskV2Test.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/heartbeat/ClientBeatCheckTaskV2Test.java @@ -28,24 +28,28 @@ import com.alibaba.nacos.naming.misc.GlobalConfig; import com.alibaba.nacos.naming.misc.UtilsAndCommons; import com.alibaba.nacos.sys.utils.ApplicationUtils; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.context.ConfigurableApplicationContext; import java.util.Optional; import java.util.concurrent.TimeUnit; -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; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class ClientBeatCheckTaskV2Test { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class ClientBeatCheckTaskV2Test { private static final String IP = "1.1.1.1"; @@ -75,8 +79,8 @@ public class ClientBeatCheckTaskV2Test { private IpPortBasedClient client; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { when(applicationContext.getBean(NamingMetadataManager.class)).thenReturn(namingMetadataManager); when(applicationContext.getBean(GlobalConfig.class)).thenReturn(globalConfig); when(applicationContext.getBean(DistroMapper.class)).thenReturn(distroMapper); @@ -87,19 +91,19 @@ public void setUp() throws Exception { } @Test - public void testTaskKey() { + void testTaskKey() { assertEquals(KeyBuilder.buildServiceMetaKey(CLIENT_ID, "true"), beatCheckTask.taskKey()); } @Test - public void testRunUnhealthyInstanceWithoutExpire() { + void testRunUnhealthyInstanceWithoutExpire() { injectInstance(false, 0); beatCheckTask.run(); assertFalse(client.getAllInstancePublishInfo().isEmpty()); } @Test - public void testRunHealthyInstanceWithoutExpire() { + void testRunHealthyInstanceWithoutExpire() { injectInstance(true, 0); beatCheckTask.run(); assertFalse(client.getAllInstancePublishInfo().isEmpty()); @@ -107,7 +111,7 @@ public void testRunHealthyInstanceWithoutExpire() { } @Test - public void testRunUnHealthyInstanceWithExpire() { + void testRunUnHealthyInstanceWithExpire() { injectInstance(false, 0); when(globalConfig.isExpireInstance()).thenReturn(true); beatCheckTask.run(); @@ -115,7 +119,7 @@ public void testRunUnHealthyInstanceWithExpire() { } @Test - public void testRunHealthyInstanceWithExpire() { + void testRunHealthyInstanceWithExpire() { injectInstance(true, 0); when(globalConfig.isExpireInstance()).thenReturn(true); beatCheckTask.run(); @@ -123,7 +127,7 @@ public void testRunHealthyInstanceWithExpire() { } @Test - public void testRunHealthyInstanceWithHeartBeat() { + void testRunHealthyInstanceWithHeartBeat() { injectInstance(true, System.currentTimeMillis()); when(globalConfig.isExpireInstance()).thenReturn(true); beatCheckTask.run(); @@ -132,9 +136,8 @@ public void testRunHealthyInstanceWithHeartBeat() { } @Test - public void testRunHealthyInstanceWithTimeoutFromInstance() throws InterruptedException { - injectInstance(true, System.currentTimeMillis()).getExtendDatum() - .put(PreservedMetadataKeys.HEART_BEAT_TIMEOUT, 800); + void testRunHealthyInstanceWithTimeoutFromInstance() throws InterruptedException { + injectInstance(true, System.currentTimeMillis()).getExtendDatum().put(PreservedMetadataKeys.HEART_BEAT_TIMEOUT, 800); when(globalConfig.isExpireInstance()).thenReturn(true); TimeUnit.SECONDS.sleep(1); beatCheckTask.run(); @@ -143,13 +146,13 @@ public void testRunHealthyInstanceWithTimeoutFromInstance() throws InterruptedEx } @Test - public void testRunHealthyInstanceWithTimeoutFromMetadata() throws InterruptedException { + void testRunHealthyInstanceWithTimeoutFromMetadata() throws InterruptedException { injectInstance(true, System.currentTimeMillis()); Service service = Service.newService(NAMESPACE, GROUP_NAME, SERVICE_NAME); InstanceMetadata metadata = new InstanceMetadata(); metadata.getExtendData().put(PreservedMetadataKeys.HEART_BEAT_TIMEOUT, 500L); - String address = - IP + InternetAddressUtil.IP_PORT_SPLITER + PORT + InternetAddressUtil.IP_PORT_SPLITER + UtilsAndCommons.DEFAULT_CLUSTER_NAME; + String address = IP + InternetAddressUtil.IP_PORT_SPLITER + PORT + InternetAddressUtil.IP_PORT_SPLITER + + UtilsAndCommons.DEFAULT_CLUSTER_NAME; when(namingMetadataManager.getInstanceMetadata(service, address)).thenReturn(Optional.of(metadata)); when(globalConfig.isExpireInstance()).thenReturn(true); TimeUnit.SECONDS.sleep(1); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/interceptor/HealthCheckTaskInterceptWrapperTest.java b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/interceptor/HealthCheckTaskInterceptWrapperTest.java index 2b626689481..165c2717b73 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/interceptor/HealthCheckTaskInterceptWrapperTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/interceptor/HealthCheckTaskInterceptWrapperTest.java @@ -28,24 +28,28 @@ import com.alibaba.nacos.naming.misc.GlobalConfig; import com.alibaba.nacos.naming.misc.SwitchDomain; import com.alibaba.nacos.sys.utils.ApplicationUtils; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.context.ConfigurableApplicationContext; import java.util.Optional; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class HealthCheckTaskInterceptWrapperTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class HealthCheckTaskInterceptWrapperTest { private static final String IP = "1.1.1.1"; @@ -78,8 +82,8 @@ public class HealthCheckTaskInterceptWrapperTest { private IpPortBasedClient client; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { when(applicationContext.getBean(NamingMetadataManager.class)).thenReturn(namingMetadataManager); when(applicationContext.getBean(GlobalConfig.class)).thenReturn(globalConfig); when(applicationContext.getBean(SwitchDomain.class)).thenReturn(switchDomain); @@ -93,28 +97,28 @@ public void setUp() throws Exception { } @Test - public void testRunWithDisableHealthCheck() { + void testRunWithDisableHealthCheck() { when(switchDomain.isHealthCheckEnabled()).thenReturn(false); taskWrapper.run(); verify(distroMapper, never()).responsible(client.getResponsibleId()); } @Test - public void testRunWithoutResponsibleClient() { + void testRunWithoutResponsibleClient() { when(distroMapper.responsible(client.getResponsibleId())).thenReturn(false); taskWrapper.run(); verify(globalConfig, never()).isExpireInstance(); } @Test - public void testRunUnhealthyInstanceWithoutExpire() { + void testRunUnhealthyInstanceWithoutExpire() { injectInstance(false, 0); taskWrapper.run(); assertFalse(client.getAllInstancePublishInfo().isEmpty()); } @Test - public void testRunHealthyInstanceWithoutExpire() { + void testRunHealthyInstanceWithoutExpire() { injectInstance(true, 0); taskWrapper.run(); assertFalse(client.getAllInstancePublishInfo().isEmpty()); @@ -122,7 +126,7 @@ public void testRunHealthyInstanceWithoutExpire() { } @Test - public void testRunUnHealthyInstanceWithExpire() { + void testRunUnHealthyInstanceWithExpire() { injectInstance(false, 0); when(globalConfig.isExpireInstance()).thenReturn(true); taskWrapper.run(); @@ -130,7 +134,7 @@ public void testRunUnHealthyInstanceWithExpire() { } @Test - public void testRunHealthyInstanceWithExpire() { + void testRunHealthyInstanceWithExpire() { injectInstance(true, 0); when(globalConfig.isExpireInstance()).thenReturn(true); taskWrapper.run(); @@ -138,7 +142,7 @@ public void testRunHealthyInstanceWithExpire() { } @Test - public void testRunHealthyInstanceWithHeartBeat() { + void testRunHealthyInstanceWithHeartBeat() { injectInstance(true, System.currentTimeMillis()); when(globalConfig.isExpireInstance()).thenReturn(true); taskWrapper.run(); @@ -147,9 +151,8 @@ public void testRunHealthyInstanceWithHeartBeat() { } @Test - public void testRunHealthyInstanceWithTimeoutFromInstance() throws InterruptedException { - injectInstance(true, System.currentTimeMillis()).getExtendDatum() - .put(PreservedMetadataKeys.HEART_BEAT_TIMEOUT, 1000); + void testRunHealthyInstanceWithTimeoutFromInstance() throws InterruptedException { + injectInstance(true, System.currentTimeMillis()).getExtendDatum().put(PreservedMetadataKeys.HEART_BEAT_TIMEOUT, 1000); when(globalConfig.isExpireInstance()).thenReturn(true); TimeUnit.MILLISECONDS.sleep(1100); taskWrapper.run(); @@ -158,13 +161,12 @@ public void testRunHealthyInstanceWithTimeoutFromInstance() throws InterruptedEx } @Test - public void testRunHealthyInstanceWithTimeoutFromMetadata() throws InterruptedException { + void testRunHealthyInstanceWithTimeoutFromMetadata() throws InterruptedException { InstancePublishInfo instance = injectInstance(true, System.currentTimeMillis()); Service service = Service.newService(NAMESPACE, GROUP_NAME, SERVICE_NAME); InstanceMetadata metadata = new InstanceMetadata(); metadata.getExtendData().put(PreservedMetadataKeys.HEART_BEAT_TIMEOUT, 1000L); - when(namingMetadataManager.getInstanceMetadata(service, instance.getMetadataId())) - .thenReturn(Optional.of(metadata)); + when(namingMetadataManager.getInstanceMetadata(service, instance.getMetadataId())).thenReturn(Optional.of(metadata)); when(globalConfig.isExpireInstance()).thenReturn(true); TimeUnit.SECONDS.sleep(1); taskWrapper.run(); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/v2/HealthCheckTaskV2Test.java b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/v2/HealthCheckTaskV2Test.java index c9766be3f77..64eba1931f6 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/v2/HealthCheckTaskV2Test.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/v2/HealthCheckTaskV2Test.java @@ -22,24 +22,30 @@ import com.alibaba.nacos.naming.misc.SwitchDomain; import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.utils.ApplicationUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.mock.env.MockEnvironment; import java.util.Collections; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class HealthCheckTaskV2Test { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class HealthCheckTaskV2Test { private HealthCheckTaskV2 healthCheckTaskV2; @@ -55,8 +61,8 @@ public class HealthCheckTaskV2Test { @Mock private Service service; - @Before - public void setUp() { + @BeforeEach + void setUp() { ApplicationUtils.injectContext(context); when(context.getBean(SwitchDomain.class)).thenReturn(switchDomain); when(switchDomain.getTcpHealthParams()).thenReturn(new SwitchDomain.TcpHealthParams()); @@ -66,13 +72,13 @@ public void setUp() { } @Test - public void testDoHealthCheck() { + void testDoHealthCheck() { when(ipPortBasedClient.getAllPublishedService()).thenReturn(returnService()); healthCheckTaskV2.setCheckRtWorst(1); healthCheckTaskV2.setCheckRtLastLast(1); - Assert.assertEquals(1, healthCheckTaskV2.getCheckRtWorst()); - Assert.assertEquals(1, healthCheckTaskV2.getCheckRtLastLast()); + assertEquals(1, healthCheckTaskV2.getCheckRtWorst()); + assertEquals(1, healthCheckTaskV2.getCheckRtLastLast()); healthCheckTaskV2.run(); healthCheckTaskV2.passIntercept(); @@ -87,27 +93,27 @@ private List returnService() { } @Test - public void testGetClient() { - Assert.assertNotNull(healthCheckTaskV2.getClient()); + void testGetClient() { + assertNotNull(healthCheckTaskV2.getClient()); } @Test - public void testGetAndSet() { + void testGetAndSet() { healthCheckTaskV2.setCheckRtBest(1); healthCheckTaskV2.setCheckRtNormalized(1); healthCheckTaskV2.setCheckRtLast(1); healthCheckTaskV2.setCancelled(true); healthCheckTaskV2.setStartTime(1615796485783L); - Assert.assertEquals(1, healthCheckTaskV2.getCheckRtBest()); - Assert.assertEquals(1, healthCheckTaskV2.getCheckRtNormalized()); - Assert.assertEquals(1, healthCheckTaskV2.getCheckRtLast()); - Assert.assertTrue(healthCheckTaskV2.isCancelled()); - Assert.assertEquals(1615796485783L, healthCheckTaskV2.getStartTime()); + assertEquals(1, healthCheckTaskV2.getCheckRtBest()); + assertEquals(1, healthCheckTaskV2.getCheckRtNormalized()); + assertEquals(1, healthCheckTaskV2.getCheckRtLast()); + assertTrue(healthCheckTaskV2.isCancelled()); + assertEquals(1615796485783L, healthCheckTaskV2.getStartTime()); } @Test - public void testAfterIntercept() { + void testAfterIntercept() { healthCheckTaskV2.afterIntercept(); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/v2/PersistentHealthStatusSynchronizerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/v2/PersistentHealthStatusSynchronizerTest.java index a2c4aae076c..32923317939 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/v2/PersistentHealthStatusSynchronizerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/v2/PersistentHealthStatusSynchronizerTest.java @@ -22,15 +22,15 @@ import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.naming.core.v2.service.impl.PersistentClientOperationServiceImpl; import com.alibaba.nacos.naming.utils.InstanceUtil; -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 static org.mockito.Mockito.verify; -@RunWith(MockitoJUnitRunner.class) -public class PersistentHealthStatusSynchronizerTest { +@ExtendWith(MockitoExtension.class) +class PersistentHealthStatusSynchronizerTest { @Mock private PersistentClientOperationServiceImpl persistentClientOperationService; @@ -39,7 +39,7 @@ public class PersistentHealthStatusSynchronizerTest { private Client client; @Test - public void testInstanceHealthStatusChange() { + void testInstanceHealthStatusChange() { Service service = Service.newService("public", "DEFAULT", "nacos", true); InstancePublishInfo instancePublishInfo = new InstancePublishInfo("127.0.0.1", 8080); PersistentHealthStatusSynchronizer persistentHealthStatusSynchronizer = new PersistentHealthStatusSynchronizer( diff --git a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HealthCheckCommonV2Test.java b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HealthCheckCommonV2Test.java index 2f339560fbe..cc284b02ca6 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HealthCheckCommonV2Test.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HealthCheckCommonV2Test.java @@ -21,11 +21,13 @@ import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.naming.healthcheck.v2.HealthCheckTaskV2; import com.alibaba.nacos.naming.misc.SwitchDomain; -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.concurrent.atomic.AtomicInteger; @@ -33,8 +35,10 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class HealthCheckCommonV2Test { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class HealthCheckCommonV2Test { @Mock private SwitchDomain.HealthParams healthParams; @@ -53,8 +57,8 @@ public class HealthCheckCommonV2Test { private HealthCheckCommonV2 healthCheckCommonV2; - @Before - public void setUp() { + @BeforeEach + void setUp() { healthCheckCommonV2 = new HealthCheckCommonV2(); when(healthCheckTaskV2.getClient()).thenReturn(ipPortBasedClient); when(ipPortBasedClient.getInstancePublishInfo(service)).thenReturn(healthCheckInstancePublishInfo); @@ -62,7 +66,7 @@ public void setUp() { } @Test - public void testReEvaluateCheckRT() { + void testReEvaluateCheckRT() { healthCheckCommonV2.reEvaluateCheckRT(1, healthCheckTaskV2, healthParams); verify(healthParams, times(2)).getMax(); @@ -75,7 +79,7 @@ public void testReEvaluateCheckRT() { } @Test - public void testCheckOk() { + void testCheckOk() { healthCheckCommonV2.checkOk(healthCheckTaskV2, service, "test checkOk"); verify(healthCheckTaskV2).getClient(); @@ -89,7 +93,7 @@ public void testCheckOk() { } @Test - public void testCheckFail() { + void testCheckFail() { when(healthCheckInstancePublishInfo.isHealthy()).thenReturn(true); healthCheckCommonV2.checkFail(healthCheckTaskV2, service, "test checkFail"); @@ -103,7 +107,7 @@ public void testCheckFail() { } @Test - public void testCheckFailNow() { + void testCheckFailNow() { when(healthCheckInstancePublishInfo.isHealthy()).thenReturn(true); healthCheckCommonV2.checkFailNow(healthCheckTaskV2, service, "test checkFailNow"); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HealthCheckProcessorV2DelegateTest.java b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HealthCheckProcessorV2DelegateTest.java index 63de62839fb..90e6b348391 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HealthCheckProcessorV2DelegateTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HealthCheckProcessorV2DelegateTest.java @@ -24,12 +24,11 @@ import com.alibaba.nacos.naming.healthcheck.extend.HealthCheckProcessorExtendV2; import com.alibaba.nacos.naming.healthcheck.v2.HealthCheckTaskV2; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.env.MockEnvironment; import java.lang.reflect.Field; @@ -37,15 +36,17 @@ import java.util.List; import java.util.Map; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class HealthCheckProcessorV2DelegateTest { +@ExtendWith(MockitoExtension.class) +class HealthCheckProcessorV2DelegateTest { @Mock private HealthCheckExtendProvider healthCheckExtendProvider; - + @Mock private HealthCheckProcessorExtendV2 healthCheckProcessorExtendV2; @@ -60,15 +61,15 @@ public class HealthCheckProcessorV2DelegateTest { private HealthCheckProcessorV2Delegate healthCheckProcessorV2Delegate; - @Before - public void setUp() { + @BeforeEach + void setUp() { healthCheckProcessorV2Delegate = new HealthCheckProcessorV2Delegate(healthCheckExtendProvider, healthCheckProcessorExtendV2); verify(healthCheckExtendProvider).init(); EnvUtil.setEnvironment(new MockEnvironment()); } @Test - public void testAddProcessor() throws NoSuchFieldException, IllegalAccessException { + void testAddProcessor() throws NoSuchFieldException, IllegalAccessException { List list = new ArrayList<>(); list.add(new TcpHealthCheckProcessor(null, null)); healthCheckProcessorV2Delegate.addProcessor(list); @@ -76,14 +77,13 @@ public void testAddProcessor() throws NoSuchFieldException, IllegalAccessExcepti Class healthCheckProcessorV2DelegateClass = HealthCheckProcessorV2Delegate.class; Field field = healthCheckProcessorV2DelegateClass.getDeclaredField("healthCheckProcessorMap"); field.setAccessible(true); - Map map = (Map) field - .get(healthCheckProcessorV2Delegate); + Map map = (Map) field.get(healthCheckProcessorV2Delegate); HealthCheckProcessorV2 healthCheckProcessorV2 = map.get(HealthCheckType.TCP.name()); - Assert.assertNotNull(healthCheckProcessorV2); + assertNotNull(healthCheckProcessorV2); } @Test - public void testProcess() throws NoSuchFieldException, IllegalAccessException { + void testProcess() throws NoSuchFieldException, IllegalAccessException { testAddProcessor(); when(clusterMetadata.getHealthyCheckType()).thenReturn(HealthCheckType.TCP.name()); when(healthCheckTaskV2.getClient()).thenReturn(new IpPortBasedClient("127.0.0.1:80#true", true)); @@ -95,7 +95,7 @@ public void testProcess() throws NoSuchFieldException, IllegalAccessException { } @Test - public void testGetType() { - Assert.assertNull(healthCheckProcessorV2Delegate.getType()); + void testGetType() { + assertNull(healthCheckProcessorV2Delegate.getType()); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HttpHealthCheckProcessorTest.java b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HttpHealthCheckProcessorTest.java index 83a60181f4c..d7996b43539 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HttpHealthCheckProcessorTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/healthcheck/v2/processor/HttpHealthCheckProcessorTest.java @@ -25,12 +25,13 @@ import com.alibaba.nacos.naming.healthcheck.v2.HealthCheckTaskV2; import com.alibaba.nacos.naming.misc.SwitchDomain; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.mock.env.MockEnvironment; import java.lang.reflect.Constructor; @@ -43,11 +44,15 @@ import java.util.stream.Collectors; import java.util.stream.Stream; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class HttpHealthCheckProcessorTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class HttpHealthCheckProcessorTest { @Mock private HealthCheckCommonV2 healthCheckCommon; @@ -78,8 +83,8 @@ public class HttpHealthCheckProcessorTest { private HttpHealthCheckProcessor httpHealthCheckProcessor; - @Before - public void setUp() { + @BeforeEach + void setUp() { EnvUtil.setEnvironment(new MockEnvironment()); when(switchDomain.getHttpHealthParams()).thenReturn(new SwitchDomain.HttpHealthParams()); when(healthCheckTaskV2.getClient()).thenReturn(ipPortBasedClient); @@ -88,7 +93,7 @@ public void setUp() { } @Test - public void testProcess() { + void testProcess() { httpHealthCheckProcessor.process(healthCheckTaskV2, service, clusterMetadata); verify(healthCheckTaskV2).getClient(); @@ -96,36 +101,31 @@ public void testProcess() { } @Test - public void testGetType() { - Assert.assertEquals(httpHealthCheckProcessor.getType(), HealthCheckType.HTTP.name()); + void testGetType() { + assertEquals(httpHealthCheckProcessor.getType(), HealthCheckType.HTTP.name()); } @Test - public void testConstructor() - throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { + void testConstructor() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Class healthCheckProcessorClass = HttpHealthCheckProcessor.class; Class[] classes = healthCheckProcessorClass.getDeclaredClasses(); Class aClass = Arrays.stream(classes).findFirst().get(); - Constructor constructor = aClass - .getConstructor(HttpHealthCheckProcessor.class, HealthCheckInstancePublishInfo.class, - HealthCheckTaskV2.class, Service.class); - Object objects = constructor - .newInstance(httpHealthCheckProcessor, healthCheckInstancePublishInfo, healthCheckTaskV2, service); + Constructor constructor = aClass.getConstructor(HttpHealthCheckProcessor.class, HealthCheckInstancePublishInfo.class, + HealthCheckTaskV2.class, Service.class); + Object objects = constructor.newInstance(httpHealthCheckProcessor, healthCheckInstancePublishInfo, healthCheckTaskV2, service); - Assert.assertNotNull(objects); + assertNotNull(objects); } @Test - public void testOnReceiveWithOK() + void testOnReceiveWithOK() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, InterruptedException { Class healthCheckProcessorClass = HttpHealthCheckProcessor.class; Class[] classes = healthCheckProcessorClass.getDeclaredClasses(); Class aClass = Arrays.stream(classes).findFirst().get(); - Constructor constructor = aClass - .getConstructor(HttpHealthCheckProcessor.class, HealthCheckInstancePublishInfo.class, - HealthCheckTaskV2.class, Service.class); - Object objects = constructor - .newInstance(httpHealthCheckProcessor, healthCheckInstancePublishInfo, healthCheckTaskV2, service); + Constructor constructor = aClass.getConstructor(HttpHealthCheckProcessor.class, HealthCheckInstancePublishInfo.class, + HealthCheckTaskV2.class, Service.class); + Object objects = constructor.newInstance(httpHealthCheckProcessor, healthCheckInstancePublishInfo, healthCheckTaskV2, service); int code = HttpURLConnection.HTTP_OK; when(restResult.getCode()).thenReturn(code); Method onReceive = aClass.getMethod("onReceive", RestResult.class); @@ -137,16 +137,14 @@ public void testOnReceiveWithOK() } @Test - public void testOnReceiveWithUnavailable() + void testOnReceiveWithUnavailable() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, InterruptedException { Class healthCheckProcessorClass = HttpHealthCheckProcessor.class; Class[] classes = healthCheckProcessorClass.getDeclaredClasses(); Class aClass = Arrays.stream(classes).findFirst().get(); - Constructor constructor = aClass - .getConstructor(HttpHealthCheckProcessor.class, HealthCheckInstancePublishInfo.class, - HealthCheckTaskV2.class, Service.class); - Object objects = constructor - .newInstance(httpHealthCheckProcessor, healthCheckInstancePublishInfo, healthCheckTaskV2, service); + Constructor constructor = aClass.getConstructor(HttpHealthCheckProcessor.class, HealthCheckInstancePublishInfo.class, + HealthCheckTaskV2.class, Service.class); + Object objects = constructor.newInstance(httpHealthCheckProcessor, healthCheckInstancePublishInfo, healthCheckTaskV2, service); int code = HttpURLConnection.HTTP_UNAVAILABLE; when(restResult.getCode()).thenReturn(code); Method onReceive = aClass.getMethod("onReceive", RestResult.class); @@ -156,16 +154,14 @@ public void testOnReceiveWithUnavailable() } @Test - public void testOnReceiveWithNotFound() + void testOnReceiveWithNotFound() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, InterruptedException { Class healthCheckProcessorClass = HttpHealthCheckProcessor.class; Class[] classes = healthCheckProcessorClass.getDeclaredClasses(); Class aClass = Arrays.stream(classes).findFirst().get(); - Constructor constructor = aClass - .getConstructor(HttpHealthCheckProcessor.class, HealthCheckInstancePublishInfo.class, - HealthCheckTaskV2.class, Service.class); - Object objects = constructor - .newInstance(httpHealthCheckProcessor, healthCheckInstancePublishInfo, healthCheckTaskV2, service); + Constructor constructor = aClass.getConstructor(HttpHealthCheckProcessor.class, HealthCheckInstancePublishInfo.class, + HealthCheckTaskV2.class, Service.class); + Object objects = constructor.newInstance(httpHealthCheckProcessor, healthCheckInstancePublishInfo, healthCheckTaskV2, service); int code = HttpURLConnection.HTTP_NOT_FOUND; when(restResult.getCode()).thenReturn(code); Method onReceive = aClass.getMethod("onReceive", RestResult.class); @@ -181,36 +177,30 @@ private void verifyCall(int code) { break; case HttpURLConnection.HTTP_UNAVAILABLE: verify(healthCheckCommon).checkFail(healthCheckTaskV2, service, "http:" + restResult.getCode()); - verify(healthCheckCommon) - .reEvaluateCheckRT(healthCheckTaskV2.getCheckRtNormalized() * 2, healthCheckTaskV2, - switchDomain.getHttpHealthParams()); + verify(healthCheckCommon).reEvaluateCheckRT(healthCheckTaskV2.getCheckRtNormalized() * 2, healthCheckTaskV2, + switchDomain.getHttpHealthParams()); break; case HttpURLConnection.HTTP_NOT_FOUND: verify(healthCheckCommon).checkFailNow(healthCheckTaskV2, service, "http:" + restResult.getCode()); - verify(healthCheckCommon) - .reEvaluateCheckRT(switchDomain.getHttpHealthParams().getMax(), healthCheckTaskV2, - switchDomain.getHttpHealthParams()); + verify(healthCheckCommon).reEvaluateCheckRT(switchDomain.getHttpHealthParams().getMax(), healthCheckTaskV2, + switchDomain.getHttpHealthParams()); break; default: } } @Test - public void testOnError() - throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { + void testOnError() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Class healthCheckProcessorClass = HttpHealthCheckProcessor.class; Class[] classes = healthCheckProcessorClass.getDeclaredClasses(); Class aClass = Arrays.stream(classes).findFirst().get(); - Constructor constructor = aClass - .getConstructor(HttpHealthCheckProcessor.class, HealthCheckInstancePublishInfo.class, - HealthCheckTaskV2.class, Service.class); - Object objects = constructor - .newInstance(httpHealthCheckProcessor, healthCheckInstancePublishInfo, healthCheckTaskV2, service); + Constructor constructor = aClass.getConstructor(HttpHealthCheckProcessor.class, HealthCheckInstancePublishInfo.class, + HealthCheckTaskV2.class, Service.class); + Object objects = constructor.newInstance(httpHealthCheckProcessor, healthCheckInstancePublishInfo, healthCheckTaskV2, service); Method onReceive = aClass.getMethod("onError", Throwable.class); onReceive.invoke(objects, connectException); - verify(healthCheckCommon) - .checkFailNow(healthCheckTaskV2, service, "http:unable2connect:" + connectException.getMessage()); + verify(healthCheckCommon).checkFailNow(healthCheckTaskV2, service, "http:unable2connect:" + connectException.getMessage()); verify(healthCheckCommon).reEvaluateCheckRT(switchDomain.getHttpHealthParams().getMax(), healthCheckTaskV2, switchDomain.getHttpHealthParams()); } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/misc/ClientConfigTest.java b/naming/src/test/java/com/alibaba/nacos/naming/misc/ClientConfigTest.java index 8c4e0172cfe..a7dc2f67292 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/misc/ClientConfigTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/misc/ClientConfigTest.java @@ -20,18 +20,17 @@ import com.alibaba.nacos.common.notify.NotifyCenter; import com.alibaba.nacos.naming.constants.ClientConstants; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.mock.env.MockEnvironment; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class ClientConfigTest { +class ClientConfigTest { private static final long EXPIRED_TIME = 10000L; @@ -39,15 +38,15 @@ public class ClientConfigTest { private MockEnvironment mockEnvironment; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { mockEnvironment = new MockEnvironment(); EnvUtil.setEnvironment(mockEnvironment); clientConfig = ClientConfig.getInstance(); } @Test - public void testUpgradeConfig() throws InterruptedException { + void testUpgradeConfig() throws InterruptedException { mockEnvironment.setProperty(ClientConstants.CLIENT_EXPIRED_TIME_CONFIG_KEY, String.valueOf(EXPIRED_TIME)); NotifyCenter.publishEvent(ServerConfigChangeEvent.newEvent()); TimeUnit.SECONDS.sleep(1); @@ -55,12 +54,11 @@ public void testUpgradeConfig() throws InterruptedException { } @Test - public void testInitConfigFormEnv() - throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { + void testInitConfigFormEnv() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { mockEnvironment.setProperty(ClientConstants.CLIENT_EXPIRED_TIME_CONFIG_KEY, String.valueOf(EXPIRED_TIME)); Constructor declaredConstructor = ClientConfig.class.getDeclaredConstructor(); declaredConstructor.setAccessible(true); ClientConfig clientConfig = declaredConstructor.newInstance(); - Assert.assertEquals(clientConfig.getClientExpiredTime(), EXPIRED_TIME); + assertEquals(EXPIRED_TIME, clientConfig.getClientExpiredTime()); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/misc/UtilsAndCommonsTest.java b/naming/src/test/java/com/alibaba/nacos/naming/misc/UtilsAndCommonsTest.java index 0041ff85ad1..0b066233b7b 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/misc/UtilsAndCommonsTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/misc/UtilsAndCommonsTest.java @@ -16,32 +16,35 @@ package com.alibaba.nacos.naming.misc; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.mock.env.MockEnvironment; import static com.alibaba.nacos.naming.misc.UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT; import static com.alibaba.nacos.naming.misc.UtilsAndCommons.NACOS_NAMING_CONTEXT; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; -public class UtilsAndCommonsTest { +class UtilsAndCommonsTest { @Test - public void testControllerPathsDefaultValues() { + void testControllerPathsDefaultValues() { MockEnvironment environment = new MockEnvironment(); - Assert.assertEquals(DEFAULT_NACOS_NAMING_CONTEXT, environment.resolvePlaceholders(NACOS_NAMING_CONTEXT)); + assertEquals(DEFAULT_NACOS_NAMING_CONTEXT, environment.resolvePlaceholders(NACOS_NAMING_CONTEXT)); } - @Test(expected = IllegalArgumentException.class) - public void testShakeUpException() { - UtilsAndCommons.shakeUp(null, 0); + @Test + void testShakeUpException() { + assertThrows(IllegalArgumentException.class, () -> { + UtilsAndCommons.shakeUp(null, 0); + }); } @Test - public void testShakeUp() { - Assert.assertEquals(0, UtilsAndCommons.shakeUp(null, 1)); + void testShakeUp() { + assertEquals(0, UtilsAndCommons.shakeUp(null, 1)); char[] chars = new char[] {2325, 9, 30, 12, 2}; - Assert.assertEquals(0, UtilsAndCommons.shakeUp(new String(chars), 1)); + assertEquals(0, UtilsAndCommons.shakeUp(new String(chars), 1)); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/monitor/MetricsMonitorTest.java b/naming/src/test/java/com/alibaba/nacos/naming/monitor/MetricsMonitorTest.java index 0bf77f487f0..1e454c4102e 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/monitor/MetricsMonitorTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/monitor/MetricsMonitorTest.java @@ -22,51 +22,53 @@ import com.alibaba.nacos.sys.utils.ApplicationUtils; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import io.micrometer.prometheus.PrometheusMeterRegistry; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.context.ConfigurableApplicationContext; import java.util.LinkedList; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.Silent.class) -public class MetricsMonitorTest { +@MockitoSettings(strictness = Strictness.LENIENT) +@ExtendWith(MockitoExtension.class) +class MetricsMonitorTest { @Mock private ConfigurableApplicationContext context; - @Before - public void setUp() { + @BeforeEach + void setUp() { ApplicationUtils.injectContext(context); when(context.getBean(PrometheusMeterRegistry.class)).thenReturn(null); // add simple meterRegistry. - NacosMeterRegistryCenter.getMeterRegistry(NacosMeterRegistryCenter.NAMING_STABLE_REGISTRY) - .add(new SimpleMeterRegistry()); + NacosMeterRegistryCenter.getMeterRegistry(NacosMeterRegistryCenter.NAMING_STABLE_REGISTRY).add(new SimpleMeterRegistry()); MetricsMonitor.resetPush(); MetricsMonitor.getIpCountMonitor().set(0); } @Test - public void testGetTotalPush() { + void testGetTotalPush() { assertEquals(0, MetricsMonitor.getTotalPushMonitor().get()); assertEquals(1, MetricsMonitor.getTotalPushMonitor().incrementAndGet()); } @Test - public void testGetFailedPush() { + void testGetFailedPush() { assertEquals(0, MetricsMonitor.getFailedPushMonitor().get()); assertEquals(1, MetricsMonitor.getFailedPushMonitor().incrementAndGet()); } @Test - public void testIncrementIpCountWithBatchRegister() { + void testIncrementIpCountWithBatchRegister() { BatchInstancePublishInfo test = new BatchInstancePublishInfo(); List instancePublishInfos = new LinkedList<>(); instancePublishInfos.add(new InstancePublishInfo()); @@ -87,7 +89,7 @@ public void testIncrementIpCountWithBatchRegister() { } @Test - public void testIncrementIpCountWithBatchRegisterAfterNormalRegister() { + void testIncrementIpCountWithBatchRegisterAfterNormalRegister() { // mock normal register MetricsMonitor.incrementInstanceCount(); BatchInstancePublishInfo newTest = new BatchInstancePublishInfo(); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/paramcheck/ParamExtractorTest.java b/naming/src/test/java/com/alibaba/nacos/naming/paramcheck/ParamExtractorTest.java index e84c252ee6b..d4fd1dd4f82 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/paramcheck/ParamExtractorTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/paramcheck/ParamExtractorTest.java @@ -22,13 +22,13 @@ import com.alibaba.nacos.core.paramcheck.ParamCheckerFilter; import com.alibaba.nacos.naming.controllers.InstanceController; import com.alibaba.nacos.sys.env.EnvUtil; -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.MockedStatic; import org.mockito.Mockito; import org.mockito.internal.verification.Times; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; @@ -37,7 +37,7 @@ import java.io.IOException; import java.lang.reflect.Method; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Param Naming ExtractorTest. @@ -45,7 +45,7 @@ * @author 985492783@qq.com * @date 2023/11/9 17:18 */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class ParamExtractorTest { @Mock @@ -54,47 +54,47 @@ public class ParamExtractorTest { private ParamCheckerFilter filter; @Test - public void testBatchUpdateFilter() throws Exception { - AbstractHttpParamExtractor httpExtractor = testExtractor(methodsCache, InstanceController.class, - "batchUpdateInstanceMetadata", HttpServletRequest.class); - assertEquals(httpExtractor.getClass(), NamingInstanceMetadataBatchHttpParamExtractor.class); + void testBatchUpdateFilter() throws Exception { + AbstractHttpParamExtractor httpExtractor = testExtractor(methodsCache, InstanceController.class, "batchUpdateInstanceMetadata", + HttpServletRequest.class); + assertEquals(NamingInstanceMetadataBatchHttpParamExtractor.class, httpExtractor.getClass()); Mockito.verify(httpExtractor, new Times(1)).extractParam(Mockito.any()); } @Test - public void testListFilter() throws Exception { - AbstractHttpParamExtractor httpExtractor = testExtractor(methodsCache, InstanceController.class, "list", - HttpServletRequest.class); - assertEquals(httpExtractor.getClass(), NamingInstanceListHttpParamExtractor.class); + void testListFilter() throws Exception { + AbstractHttpParamExtractor httpExtractor = testExtractor(methodsCache, InstanceController.class, "list", HttpServletRequest.class); + assertEquals(NamingInstanceListHttpParamExtractor.class, httpExtractor.getClass()); Mockito.verify(httpExtractor, new Times(1)).extractParam(Mockito.any()); } @Test - public void testMetadataFilter() throws Exception { - AbstractHttpParamExtractor httpExtractor = testExtractor(methodsCache, InstanceController.class, - "batchDeleteInstanceMetadata", HttpServletRequest.class); - assertEquals(httpExtractor.getClass(), NamingInstanceMetadataBatchHttpParamExtractor.class); + void testMetadataFilter() throws Exception { + AbstractHttpParamExtractor httpExtractor = testExtractor(methodsCache, InstanceController.class, "batchDeleteInstanceMetadata", + HttpServletRequest.class); + assertEquals(NamingInstanceMetadataBatchHttpParamExtractor.class, httpExtractor.getClass()); Mockito.verify(httpExtractor, new Times(1)).extractParam(Mockito.any()); } @Test - public void testDefaultFilter() throws Exception { + void testDefaultFilter() throws Exception { AbstractHttpParamExtractor httpExtractor = testExtractor(methodsCache, InstanceController.class, "register", HttpServletRequest.class); - assertEquals(httpExtractor.getClass(), NamingDefaultHttpParamExtractor.class); + assertEquals(NamingDefaultHttpParamExtractor.class, httpExtractor.getClass()); Mockito.verify(httpExtractor, new Times(1)).extractParam(Mockito.any()); } /** * Create mock method about AbstractHttpParamExtractor to verify. - * @param methodsCache methodsCache - * @param clazz clazz - * @param methodName methodName + * + * @param methodsCache methodsCache + * @param clazz clazz + * @param methodName methodName * @param parameterTypes parameterTypes * @return AbstractHttpParamExtractor */ - public AbstractHttpParamExtractor testExtractor(ControllerMethodsCache methodsCache, Class clazz, - String methodName, Class... parameterTypes) throws NoSuchMethodException, ServletException, IOException { + public AbstractHttpParamExtractor testExtractor(ControllerMethodsCache methodsCache, Class clazz, String methodName, + Class... parameterTypes) throws NoSuchMethodException, ServletException, IOException { MockedStatic mockedStatic = Mockito.mockStatic(EnvUtil.class); final Method check = clazz.getMethod(methodName, parameterTypes); ExtractorManager.Extractor annotation = check.getAnnotation(ExtractorManager.Extractor.class); @@ -104,8 +104,7 @@ public AbstractHttpParamExtractor testExtractor(ControllerMethodsCache methodsCa AbstractHttpParamExtractor httpExtractor = Mockito.spy(ExtractorManager.getHttpExtractor(annotation)); MockedStatic managerMockedStatic = Mockito.mockStatic(ExtractorManager.class); - mockedStatic.when(() -> EnvUtil.getProperty(Mockito.any(), Mockito.any(), Mockito.any())) - .thenAnswer((k) -> k.getArgument(2)); + mockedStatic.when(() -> EnvUtil.getProperty(Mockito.any(), Mockito.any(), Mockito.any())).thenAnswer((k) -> k.getArgument(2)); ParamCheckerFilter filter = new ParamCheckerFilter(methodsCache); ExtractorManager.Extractor finalAnnotation = annotation; diff --git a/naming/src/test/java/com/alibaba/nacos/naming/paramcheck/RpcParamCheckTest.java b/naming/src/test/java/com/alibaba/nacos/naming/paramcheck/RpcParamCheckTest.java index 16785d82a8d..7f79afe7758 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/paramcheck/RpcParamCheckTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/paramcheck/RpcParamCheckTest.java @@ -23,30 +23,31 @@ import com.alibaba.nacos.core.remote.grpc.RemoteParamCheckFilter; import com.alibaba.nacos.naming.remote.rpc.handler.InstanceRequestHandler; import com.alibaba.nacos.sys.env.EnvUtil; -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.MockedStatic; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; + import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -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; /** * RpcParamCheckTest. + * * @author 985492783@qq.com * @date 2023/11/7 21:44 */ -@RunWith(MockitoJUnitRunner.class) -public class RpcParamCheckTest { +@ExtendWith(MockitoExtension.class) +class RpcParamCheckTest { + @Test - public void testFilter() - throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + void testFilter() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { MockedStatic mockedStatic = Mockito.mockStatic(EnvUtil.class); - mockedStatic.when(() -> EnvUtil.getProperty(Mockito.any(), Mockito.any(), Mockito.any())) - .thenAnswer((k) -> k.getArgument(2)); + mockedStatic.when(() -> EnvUtil.getProperty(Mockito.any(), Mockito.any(), Mockito.any())).thenAnswer((k) -> k.getArgument(2)); RemoteParamCheckFilter filter = new RemoteParamCheckFilter(); Method method = filter.getClass().getDeclaredMethod("filter", Request.class, RequestMeta.class, Class.class); method.setAccessible(true); @@ -56,7 +57,7 @@ public void testFilter() assertNull(response); request.setNamespace("test@@@"); Response response2 = (Response) method.invoke(filter, request, null, InstanceRequestHandler.class); - assertEquals(response2.getErrorCode(), 400); + assertEquals(400, response2.getErrorCode()); mockedStatic.close(); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/pojo/SubscriberTest.java b/naming/src/test/java/com/alibaba/nacos/naming/pojo/SubscriberTest.java index a9011233d7a..76fe68cb98a 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/pojo/SubscriberTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/pojo/SubscriberTest.java @@ -16,16 +16,18 @@ package com.alibaba.nacos.naming.pojo; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; -public class SubscriberTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class SubscriberTest { @Test - public void subscriberBeanTest() { + void subscriberBeanTest() { Subscriber subscriber = new Subscriber("127.0.0.1:8080", "agent", "app", "127.0.0.1", "public", "test", 0); subscriber.setAddrStr("127.0.0.1:8080"); subscriber.setIp("127.0.0.1"); @@ -47,13 +49,13 @@ public void subscriberBeanTest() { subscribers.setSubscribers(subscriberList); subscribers.getSubscribers(); - Assert.assertNotNull(subscriberList); - Assert.assertEquals(1, subscriberList.size()); - Assert.assertEquals("127.0.0.1:8080", subscriberList.get(0).getAddrStr()); - Assert.assertEquals("127.0.0.1", subscriberList.get(0).getIp()); - Assert.assertEquals("app", subscriberList.get(0).getApp()); - Assert.assertEquals("agent", subscriberList.get(0).getAgent()); - Assert.assertEquals("public", subscriberList.get(0).getNamespaceId()); - Assert.assertEquals("test", subscriberList.get(0).getServiceName()); + assertNotNull(subscriberList); + assertEquals(1, subscriberList.size()); + assertEquals("127.0.0.1:8080", subscriberList.get(0).getAddrStr()); + assertEquals("127.0.0.1", subscriberList.get(0).getIp()); + assertEquals("app", subscriberList.get(0).getApp()); + assertEquals("agent", subscriberList.get(0).getAgent()); + assertEquals("public", subscriberList.get(0).getNamespaceId()); + assertEquals("test", subscriberList.get(0).getServiceName()); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/pojo/instance/BeatInfoInstanceBuilderTest.java b/naming/src/test/java/com/alibaba/nacos/naming/pojo/instance/BeatInfoInstanceBuilderTest.java index b2c0fac59ee..867ab5433a5 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/pojo/instance/BeatInfoInstanceBuilderTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/pojo/instance/BeatInfoInstanceBuilderTest.java @@ -19,23 +19,23 @@ import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.common.spi.NacosServiceLoader; import com.alibaba.nacos.naming.healthcheck.RsInfo; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeAll; +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 javax.servlet.http.HttpServletRequest; import java.util.HashMap; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.verify; -@RunWith(MockitoJUnitRunner.class) -public class BeatInfoInstanceBuilderTest { +@ExtendWith(MockitoExtension.class) +class BeatInfoInstanceBuilderTest { @Mock private HttpServletRequest request; @@ -44,13 +44,13 @@ public class BeatInfoInstanceBuilderTest { private BeatInfoInstanceBuilder builder; - @BeforeClass - public static void setUpBeforeClass() { + @BeforeAll + static void setUpBeforeClass() { NacosServiceLoader.load(InstanceExtensionHandler.class); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { builder = BeatInfoInstanceBuilder.newBuilder(); builder.setRequest(request); beatInfo = new RsInfo(); @@ -63,7 +63,7 @@ public void setUp() throws Exception { } @Test - public void testBuild() { + void testBuild() { Instance actual = builder.setServiceName("g@@s").setBeatInfo(beatInfo).build(); assertThat(actual.getServiceName(), is("g@@s")); assertThat(actual.getIp(), is("1.1.1.1")); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/pojo/instance/DefaultInstanceInstanceIdGeneratorTest.java b/naming/src/test/java/com/alibaba/nacos/naming/pojo/instance/DefaultInstanceInstanceIdGeneratorTest.java index 17005bc3d76..8c5fab06432 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/pojo/instance/DefaultInstanceInstanceIdGeneratorTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/pojo/instance/DefaultInstanceInstanceIdGeneratorTest.java @@ -17,15 +17,15 @@ package com.alibaba.nacos.naming.pojo.instance; import com.alibaba.nacos.api.naming.pojo.Instance; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; -public class DefaultInstanceInstanceIdGeneratorTest { +class DefaultInstanceInstanceIdGeneratorTest { @Test - public void testGenerateInstanceId() { + void testGenerateInstanceId() { final DefaultInstanceIdGenerator instanceIdGenerator = new DefaultInstanceIdGenerator(); Instance instance = new Instance(); instance.setServiceName("service"); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/pojo/instance/HttpRequestInstanceBuilderTest.java b/naming/src/test/java/com/alibaba/nacos/naming/pojo/instance/HttpRequestInstanceBuilderTest.java index 2c1d9dfa754..c8b58d1d1d4 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/pojo/instance/HttpRequestInstanceBuilderTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/pojo/instance/HttpRequestInstanceBuilderTest.java @@ -22,25 +22,30 @@ import com.alibaba.nacos.common.spi.NacosServiceLoader; import com.alibaba.nacos.naming.misc.UtilsAndCommons; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.core.env.StandardEnvironment; import javax.servlet.http.HttpServletRequest; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.hamcrest.MatcherAssert.assertThat; +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.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class HttpRequestInstanceBuilderTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class HttpRequestInstanceBuilderTest { private static final String SERVICE = "service"; @@ -53,14 +58,14 @@ public class HttpRequestInstanceBuilderTest { private HttpRequestInstanceBuilder builder; - @BeforeClass - public static void setUpBeforeClass() { + @BeforeAll + static void setUpBeforeClass() { NacosServiceLoader.load(InstanceExtensionHandler.class); EnvUtil.setEnvironment(new StandardEnvironment()); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { builder = HttpRequestInstanceBuilder.newBuilder(); when(request.getParameter(CommonParams.SERVICE_NAME)).thenReturn("service"); when(request.getParameter("ip")).thenReturn(IP); @@ -69,7 +74,7 @@ public void setUp() throws Exception { } @Test - public void testBuildSimple() throws NacosException { + void testBuildSimple() throws NacosException { Instance actual = builder.setRequest(request).build(); assertThat(actual.getServiceName(), is(SERVICE)); assertThat(actual.getIp(), is(IP)); @@ -79,15 +84,14 @@ public void testBuildSimple() throws NacosException { assertTrue(actual.isEphemeral()); assertTrue(actual.isEnabled()); assertTrue(actual.isHealthy()); - assertThat(actual.getInstanceId(), - is(IP + "#" + PORT + "#" + UtilsAndCommons.DEFAULT_CLUSTER_NAME + "#" + SERVICE)); + assertThat(actual.getInstanceId(), is(IP + "#" + PORT + "#" + UtilsAndCommons.DEFAULT_CLUSTER_NAME + "#" + SERVICE)); assertThat(actual.getMetadata().size(), is(1)); assertThat(actual.getMetadata().get("mock"), is("mock")); verify(request).getParameter("mock"); } @Test - public void testBuildFull() throws NacosException { + void testBuildFull() throws NacosException { when(request.getParameter("weight")).thenReturn("2"); when(request.getParameter("healthy")).thenReturn("false"); when(request.getParameter("enabled")).thenReturn("false"); @@ -110,9 +114,11 @@ public void testBuildFull() throws NacosException { verify(request).getParameter("mock"); } - @Test(expected = NacosException.class) - public void testBuildWithIllegalWeight() throws NacosException { - when(request.getParameter("weight")).thenReturn("10001"); - Instance actual = builder.setRequest(request).build(); + @Test + void testBuildWithIllegalWeight() throws NacosException { + assertThrows(NacosException.class, () -> { + when(request.getParameter("weight")).thenReturn("10001"); + Instance actual = builder.setRequest(request).build(); + }); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/pojo/instance/InstanceIdGeneratorManagerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/pojo/instance/InstanceIdGeneratorManagerTest.java index e2e95fd3b8b..f4ff2f9cad3 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/pojo/instance/InstanceIdGeneratorManagerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/pojo/instance/InstanceIdGeneratorManagerTest.java @@ -19,9 +19,9 @@ import com.alibaba.nacos.api.naming.PreservedMetadataKeys; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.env.MockEnvironment; import java.util.HashMap; @@ -29,11 +29,11 @@ import static com.alibaba.nacos.api.common.Constants.SNOWFLAKE_INSTANCE_ID_GENERATOR; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; -@RunWith(MockitoJUnitRunner.class) -public class InstanceIdGeneratorManagerTest { +@ExtendWith(MockitoExtension.class) +class InstanceIdGeneratorManagerTest { static { MockEnvironment environment = new MockEnvironment(); @@ -42,7 +42,7 @@ public class InstanceIdGeneratorManagerTest { } @Test - public void testGenerateSnowFlakeInstanceId() { + void testGenerateSnowFlakeInstanceId() { Instance instance = new Instance(); Map metaData = new HashMap<>(1); metaData.put(PreservedMetadataKeys.INSTANCE_ID_GENERATOR, SNOWFLAKE_INSTANCE_ID_GENERATOR); @@ -56,7 +56,7 @@ public void testGenerateSnowFlakeInstanceId() { } @Test - public void testGenerateInstanceId() { + void testGenerateInstanceId() { Instance instance = new Instance(); instance.setServiceName("service"); instance.setClusterName("cluster"); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/pojo/instance/SnowFlakeInstanceIdGeneratorTest.java b/naming/src/test/java/com/alibaba/nacos/naming/pojo/instance/SnowFlakeInstanceIdGeneratorTest.java index f22b053562d..d200f205d14 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/pojo/instance/SnowFlakeInstanceIdGeneratorTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/pojo/instance/SnowFlakeInstanceIdGeneratorTest.java @@ -19,19 +19,19 @@ import com.alibaba.nacos.api.naming.PreservedMetadataKeys; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.env.MockEnvironment; import java.util.HashMap; import java.util.Map; import static com.alibaba.nacos.api.common.Constants.SNOWFLAKE_INSTANCE_ID_GENERATOR; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; -@RunWith(MockitoJUnitRunner.class) -public class SnowFlakeInstanceIdGeneratorTest { +@ExtendWith(MockitoExtension.class) +class SnowFlakeInstanceIdGeneratorTest { static { MockEnvironment environment = new MockEnvironment(); @@ -41,7 +41,7 @@ public class SnowFlakeInstanceIdGeneratorTest { } @Test - public void testGenerateInstanceId() { + void testGenerateInstanceId() { final SnowFlakeInstanceIdGenerator instanceIdGenerator = new SnowFlakeInstanceIdGenerator(); Instance instance = new Instance(); Map metaData = new HashMap<>(1); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/push/ClientInfoTest.java b/naming/src/test/java/com/alibaba/nacos/naming/push/ClientInfoTest.java index 1f19d9b9586..fff62ae2af3 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/push/ClientInfoTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/push/ClientInfoTest.java @@ -17,16 +17,16 @@ package com.alibaba.nacos.naming.push; import com.alibaba.nacos.naming.misc.UtilsAndCommons; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class ClientInfoTest { +class ClientInfoTest { private final String testVersionString = "2.0.0-ALPHA"; @Test - public void testGetClientInfoForJava() { + void testGetClientInfoForJava() { String userAgent = getUserAgent(ClientInfo.ClientTypeDescription.JAVA_CLIENT); ClientInfo actual = new ClientInfo(userAgent); assertEquals(ClientInfo.ClientType.JAVA, actual.type); @@ -34,7 +34,7 @@ public void testGetClientInfoForJava() { } @Test - public void testGetClientInfoForGo() { + void testGetClientInfoForGo() { String userAgent = getUserAgent(ClientInfo.ClientTypeDescription.GO_CLIENT); ClientInfo actual = new ClientInfo(userAgent); assertEquals(ClientInfo.ClientType.GO, actual.type); @@ -42,7 +42,7 @@ public void testGetClientInfoForGo() { } @Test - public void testGetClientInfoForC() { + void testGetClientInfoForC() { String userAgent = getUserAgent(ClientInfo.ClientTypeDescription.C_CLIENT); ClientInfo actual = new ClientInfo(userAgent); assertEquals(ClientInfo.ClientType.C, actual.type); @@ -50,7 +50,7 @@ public void testGetClientInfoForC() { } @Test - public void testGetClientInfoForCpp() { + void testGetClientInfoForCpp() { String userAgent = getUserAgent(ClientInfo.ClientTypeDescription.CPP_CLIENT); ClientInfo actual = new ClientInfo(userAgent); assertEquals(ClientInfo.ClientType.C, actual.type); @@ -58,7 +58,7 @@ public void testGetClientInfoForCpp() { } @Test - public void testGetClientInfoForDns() { + void testGetClientInfoForDns() { String userAgent = getUserAgent(ClientInfo.ClientTypeDescription.DNSF_CLIENT); ClientInfo actual = new ClientInfo(userAgent); assertEquals(ClientInfo.ClientType.DNS, actual.type); @@ -66,7 +66,7 @@ public void testGetClientInfoForDns() { } @Test - public void testGetClientInfoForSdk() { + void testGetClientInfoForSdk() { String userAgent = getUserAgent(ClientInfo.ClientTypeDescription.SDK_CLIENT); ClientInfo actual = new ClientInfo(userAgent); assertEquals(ClientInfo.ClientType.JAVA_SDK, actual.type); @@ -74,7 +74,7 @@ public void testGetClientInfoForSdk() { } @Test - public void testGetClientInfoForServer() { + void testGetClientInfoForServer() { String userAgent = getUserAgent(UtilsAndCommons.NACOS_SERVER_HEADER); ClientInfo actual = new ClientInfo(userAgent); assertEquals(ClientInfo.ClientType.NACOS_SERVER, actual.type); @@ -82,7 +82,7 @@ public void testGetClientInfoForServer() { } @Test - public void testGetClientInfoForNginx() { + void testGetClientInfoForNginx() { String userAgent = getUserAgent(ClientInfo.ClientTypeDescription.NGINX_CLIENT); ClientInfo actual = new ClientInfo(userAgent); assertEquals(ClientInfo.ClientType.TENGINE, actual.type); @@ -90,7 +90,7 @@ public void testGetClientInfoForNginx() { } @Test - public void testGetClientInfoForUnknown() { + void testGetClientInfoForUnknown() { String userAgent = getUserAgent("TestClient"); ClientInfo actual = new ClientInfo(userAgent); assertEquals(ClientInfo.ClientType.UNKNOWN, actual.type); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/push/NamingSubscriberServiceAggregationImplTest.java b/naming/src/test/java/com/alibaba/nacos/naming/push/NamingSubscriberServiceAggregationImplTest.java index 9f32aa9078e..bfadaf5748b 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/push/NamingSubscriberServiceAggregationImplTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/push/NamingSubscriberServiceAggregationImplTest.java @@ -20,23 +20,27 @@ import com.alibaba.nacos.core.cluster.ServerMemberManager; import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.naming.pojo.Subscriber; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.core.env.ConfigurableEnvironment; import java.util.Collection; import java.util.Collections; import java.util.HashMap; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class NamingSubscriberServiceAggregationImplTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class NamingSubscriberServiceAggregationImplTest { private final String namespace = "N"; @@ -57,8 +61,8 @@ public class NamingSubscriberServiceAggregationImplTest { private NamingSubscriberServiceAggregationImpl aggregation; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { aggregation = new NamingSubscriberServiceAggregationImpl(local, memberManager); Subscriber subscriber = new Subscriber("local", "", "", "", namespace, serviceName, 0); when(local.getSubscribers(namespace, serviceName)).thenReturn(Collections.singletonList(subscriber)); @@ -71,38 +75,38 @@ public void setUp() throws Exception { } @Test - public void testGetSubscribersByStringWithLocal() { + void testGetSubscribersByStringWithLocal() { Collection actual = aggregation.getSubscribers(namespace, serviceName); assertEquals(1, actual.size()); assertEquals("local", actual.iterator().next().getAddrStr()); } @Test - public void testGetSubscribersByStringWithRemote() { + void testGetSubscribersByStringWithRemote() { // TODO } @Test - public void testGetSubscribersByServiceWithLocal() { + void testGetSubscribersByServiceWithLocal() { Collection actual = aggregation.getSubscribers(service); assertEquals(1, actual.size()); assertEquals("local", actual.iterator().next().getAddrStr()); } @Test - public void testGetSubscribersByServiceWithRemote() { + void testGetSubscribersByServiceWithRemote() { // TODO } @Test - public void testGetFuzzySubscribersByStringWithLocal() { + void testGetFuzzySubscribersByStringWithLocal() { Collection actual = aggregation.getFuzzySubscribers(namespace, serviceName); assertEquals(1, actual.size()); assertEquals("local", actual.iterator().next().getAddrStr()); } @Test - public void testGetFuzzySubscribersByServiceWithLocal() { + void testGetFuzzySubscribersByServiceWithLocal() { Collection actual = aggregation.getFuzzySubscribers(service); assertEquals(1, actual.size()); assertEquals("local", actual.iterator().next().getAddrStr()); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/push/v2/NamingSubscriberServiceV2ImplTest.java b/naming/src/test/java/com/alibaba/nacos/naming/push/v2/NamingSubscriberServiceV2ImplTest.java index cb5a7dfb73a..84db805b5e5 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/push/v2/NamingSubscriberServiceV2ImplTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/push/v2/NamingSubscriberServiceV2ImplTest.java @@ -25,25 +25,29 @@ import com.alibaba.nacos.naming.pojo.Subscriber; import com.alibaba.nacos.naming.push.v2.task.PushDelayTask; import com.alibaba.nacos.naming.push.v2.task.PushDelayTaskExecuteEngine; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.test.util.ReflectionTestUtils; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class NamingSubscriberServiceV2ImplTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class NamingSubscriberServiceV2ImplTest { private final String testClientId = "testClientId"; @@ -68,14 +72,12 @@ public class NamingSubscriberServiceV2ImplTest { private NamingSubscriberServiceV2Impl subscriberService; - @Before - public void setUp() throws Exception { - subscriberService = new NamingSubscriberServiceV2Impl(clientManager, indexesManager, null, null, null, - switchDomain); + @BeforeEach + void setUp() throws Exception { + subscriberService = new NamingSubscriberServiceV2Impl(clientManager, indexesManager, null, null, null, switchDomain); ReflectionTestUtils.setField(subscriberService, "delayTaskEngine", delayTaskEngine); when(indexesManager.getAllClientsSubscribeService(service)).thenReturn(Collections.singletonList(testClientId)); - when(indexesManager.getAllClientsSubscribeService(service1)) - .thenReturn(Collections.singletonList(testClientId)); + when(indexesManager.getAllClientsSubscribeService(service1)).thenReturn(Collections.singletonList(testClientId)); Collection services = new LinkedList<>(); services.add(service); services.add(service1); @@ -88,35 +90,33 @@ public void setUp() throws Exception { } @Test - public void testGetSubscribersByString() { - Collection actual = subscriberService - .getSubscribers(service.getNamespace(), service.getGroupedServiceName()); + void testGetSubscribersByString() { + Collection actual = subscriberService.getSubscribers(service.getNamespace(), service.getGroupedServiceName()); assertEquals(1, actual.size()); assertEquals(service.getGroupedServiceName(), actual.iterator().next().getServiceName()); } @Test - public void testGetSubscribersByService() { + void testGetSubscribersByService() { Collection actual = subscriberService.getSubscribers(service); assertEquals(1, actual.size()); assertEquals(service.getGroupedServiceName(), actual.iterator().next().getServiceName()); } @Test - public void testGetFuzzySubscribersByString() { - Collection actual = subscriberService - .getFuzzySubscribers(service.getNamespace(), service.getGroupedServiceName()); + void testGetFuzzySubscribersByString() { + Collection actual = subscriberService.getFuzzySubscribers(service.getNamespace(), service.getGroupedServiceName()); assertEquals(2, actual.size()); } @Test - public void testGetFuzzySubscribersByService() { + void testGetFuzzySubscribersByService() { Collection actual = subscriberService.getFuzzySubscribers(service); assertEquals(2, actual.size()); } @Test - public void onEvent() { + void onEvent() { subscriberService.onEvent(new ServiceEvent.ServiceChangedEvent(service)); verify(delayTaskEngine).addTask(eq(service), any(PushDelayTask.class)); } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/push/v2/PushConfigTest.java b/naming/src/test/java/com/alibaba/nacos/naming/push/v2/PushConfigTest.java index 2c3ab86d873..1c76c4ab674 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/push/v2/PushConfigTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/push/v2/PushConfigTest.java @@ -16,21 +16,21 @@ package com.alibaba.nacos.naming.push.v2; -import com.alibaba.nacos.common.notify.NotifyCenter; import com.alibaba.nacos.common.event.ServerConfigChangeEvent; +import com.alibaba.nacos.common.notify.NotifyCenter; import com.alibaba.nacos.naming.constants.PushConstants; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.mock.env.MockEnvironment; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class PushConfigTest { +class PushConfigTest { private PushConfig pushConfig; @@ -42,15 +42,15 @@ public class PushConfigTest { private long pushTaskRetryDelay = PushConstants.DEFAULT_PUSH_TASK_RETRY_DELAY * 2; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { mockEnvironment = new MockEnvironment(); EnvUtil.setEnvironment(mockEnvironment); pushConfig = PushConfig.getInstance(); } @Test - public void testUpgradeConfig() throws InterruptedException { + void testUpgradeConfig() throws InterruptedException { mockEnvironment.setProperty(PushConstants.PUSH_TASK_DELAY, String.valueOf(pushTaskDelay)); mockEnvironment.setProperty(PushConstants.PUSH_TASK_TIMEOUT, String.valueOf(pushTaskTimeout)); mockEnvironment.setProperty(PushConstants.PUSH_TASK_RETRY_DELAY, String.valueOf(pushTaskRetryDelay)); @@ -62,8 +62,7 @@ public void testUpgradeConfig() throws InterruptedException { } @Test - public void testInitConfigFormEnv() - throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { + void testInitConfigFormEnv() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { mockEnvironment.setProperty(PushConstants.PUSH_TASK_DELAY, String.valueOf(pushTaskDelay)); mockEnvironment.setProperty(PushConstants.PUSH_TASK_TIMEOUT, String.valueOf(pushTaskTimeout)); mockEnvironment.setProperty(PushConstants.PUSH_TASK_RETRY_DELAY, String.valueOf(pushTaskRetryDelay)); @@ -73,6 +72,6 @@ public void testInitConfigFormEnv() assertEquals(pushTaskDelay, pushConfig.getPushTaskDelay()); assertEquals(pushTaskTimeout, pushConfig.getPushTaskTimeout()); assertEquals(pushTaskRetryDelay, pushConfig.getPushTaskRetryDelay()); - + } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/push/v2/executor/PushExecutorDelegateTest.java b/naming/src/test/java/com/alibaba/nacos/naming/push/v2/executor/PushExecutorDelegateTest.java index 85ed9d03a93..9827f3f4959 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/push/v2/executor/PushExecutorDelegateTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/push/v2/executor/PushExecutorDelegateTest.java @@ -21,18 +21,18 @@ import com.alibaba.nacos.naming.pojo.Subscriber; import com.alibaba.nacos.naming.push.v2.PushDataWrapper; import com.alibaba.nacos.naming.push.v2.task.NamingPushCallback; -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.UUID; import static org.mockito.Mockito.verify; -@RunWith(MockitoJUnitRunner.class) -public class PushExecutorDelegateTest { +@ExtendWith(MockitoExtension.class) +class PushExecutorDelegateTest { private final String udpClientId = "1.1.1.1:60000#true"; @@ -56,33 +56,33 @@ public class PushExecutorDelegateTest { private ServiceMetadata serviceMetadata; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { serviceMetadata = new ServiceMetadata(); pushdata = new PushDataWrapper(serviceMetadata, new ServiceInfo("G@@S")); delegate = new PushExecutorDelegate(pushExecutorRpc, pushExecutorUdp); } @Test - public void testDoPushForUdp() { + void testDoPushForUdp() { delegate.doPush(udpClientId, subscriber, pushdata); verify(pushExecutorUdp).doPush(udpClientId, subscriber, pushdata); } @Test - public void testDoPushForRpc() { + void testDoPushForRpc() { delegate.doPush(rpcClientId, subscriber, pushdata); verify(pushExecutorRpc).doPush(rpcClientId, subscriber, pushdata); } @Test - public void doPushWithCallbackForUdp() { + void doPushWithCallbackForUdp() { delegate.doPushWithCallback(udpClientId, subscriber, pushdata, pushCallBack); verify(pushExecutorUdp).doPushWithCallback(udpClientId, subscriber, pushdata, pushCallBack); } @Test - public void doPushWithCallbackForRpc() { + void doPushWithCallbackForRpc() { delegate.doPushWithCallback(rpcClientId, subscriber, pushdata, pushCallBack); verify(pushExecutorRpc).doPushWithCallback(rpcClientId, subscriber, pushdata, pushCallBack); } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/push/v2/executor/PushExecutorRpcImplTest.java b/naming/src/test/java/com/alibaba/nacos/naming/push/v2/executor/PushExecutorRpcImplTest.java index 84fae38501a..a49f10a91ab 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/push/v2/executor/PushExecutorRpcImplTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/push/v2/executor/PushExecutorRpcImplTest.java @@ -29,12 +29,12 @@ import com.alibaba.nacos.naming.selector.SelectorManager; import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.utils.ApplicationUtils; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.mock.env.MockEnvironment; @@ -42,15 +42,15 @@ import java.util.List; import java.util.UUID; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class PushExecutorRpcImplTest { +@ExtendWith(MockitoExtension.class) +class PushExecutorRpcImplTest { private final String rpcClientId = UUID.randomUUID().toString(); @@ -75,30 +75,30 @@ public class PushExecutorRpcImplTest { private ServiceMetadata serviceMetadata; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { EnvUtil.setEnvironment(new MockEnvironment()); serviceMetadata = new ServiceMetadata(); pushData = new PushDataWrapper(serviceMetadata, new ServiceInfo("G@@S")); pushExecutor = new PushExecutorRpcImpl(pushService); EnvUtil.setEnvironment(new MockEnvironment()); - doAnswer(new CallbackAnswer()).when(pushService) - .pushWithCallback(eq(rpcClientId), any(NotifySubscriberRequest.class), eq(pushCallBack), - eq(GlobalExecutor.getCallbackExecutor())); ApplicationUtils.injectContext(context); when(context.getBean(SelectorManager.class)).thenReturn(selectorManager); - when(selectorManager.select(any(), any(), any())) - .then((Answer>) invocationOnMock -> invocationOnMock.getArgument(2)); + when(selectorManager.select(any(), any(), any())).then( + (Answer>) invocationOnMock -> invocationOnMock.getArgument(2)); } @Test - public void testDoPush() { + void testDoPush() { pushExecutor.doPush(rpcClientId, subscriber, pushData); verify(pushService).pushWithoutAck(eq(rpcClientId), any(NotifySubscriberRequest.class)); } @Test - public void testDoPushWithCallback() { + void testDoPushWithCallback() { + doAnswer(new CallbackAnswer()).when(pushService) + .pushWithCallback(eq(rpcClientId), any(NotifySubscriberRequest.class), eq(pushCallBack), + eq(GlobalExecutor.getCallbackExecutor())); pushExecutor.doPushWithCallback(rpcClientId, subscriber, pushData, pushCallBack); verify(pushCallBack).onSuccess(); } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/push/v2/executor/PushExecutorUdpImplTest.java b/naming/src/test/java/com/alibaba/nacos/naming/push/v2/executor/PushExecutorUdpImplTest.java index b1c570d43e0..29fa4a33689 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/push/v2/executor/PushExecutorUdpImplTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/push/v2/executor/PushExecutorUdpImplTest.java @@ -26,26 +26,26 @@ import com.alibaba.nacos.naming.push.v2.task.NamingPushCallback; import com.alibaba.nacos.naming.selector.SelectorManager; import com.alibaba.nacos.sys.utils.ApplicationUtils; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; import org.springframework.context.ConfigurableApplicationContext; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class PushExecutorUdpImplTest { +@ExtendWith(MockitoExtension.class) +class PushExecutorUdpImplTest { private final String rpcClientId = "1.1.1.1:10000"; @@ -70,27 +70,26 @@ public class PushExecutorUdpImplTest { private ServiceMetadata serviceMetadata; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { serviceMetadata = new ServiceMetadata(); pushData = new PushDataWrapper(serviceMetadata, new ServiceInfo("G@@S")); pushExecutor = new PushExecutorUdpImpl(pushService); - doAnswer(new CallbackAnswer()).when(pushService) - .pushDataWithCallback(eq(subscriber), any(ServiceInfo.class), eq(pushCallBack)); ApplicationUtils.injectContext(context); when(context.getBean(SelectorManager.class)).thenReturn(selectorManager); - when(selectorManager.select(any(), any(), any())) - .then((Answer>) invocationOnMock -> invocationOnMock.getArgument(2)); + when(selectorManager.select(any(), any(), any())).then( + (Answer>) invocationOnMock -> invocationOnMock.getArgument(2)); } @Test - public void testDoPush() { + void testDoPush() { pushExecutor.doPush(rpcClientId, subscriber, pushData); verify(pushService).pushDataWithoutCallback(eq(subscriber), any(ServiceInfo.class)); } @Test - public void testDoPushWithCallback() { + void testDoPushWithCallback() { + doAnswer(new CallbackAnswer()).when(pushService).pushDataWithCallback(eq(subscriber), any(ServiceInfo.class), eq(pushCallBack)); pushExecutor.doPushWithCallback(rpcClientId, subscriber, pushData, pushCallBack); verify(pushCallBack).onSuccess(); } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/push/v2/executor/SpiImplPushExecutorHolderTest.java b/naming/src/test/java/com/alibaba/nacos/naming/push/v2/executor/SpiImplPushExecutorHolderTest.java index 1846f8ba2f5..56dec3af1db 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/push/v2/executor/SpiImplPushExecutorHolderTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/push/v2/executor/SpiImplPushExecutorHolderTest.java @@ -17,20 +17,24 @@ package com.alibaba.nacos.naming.push.v2.executor; import com.alibaba.nacos.naming.pojo.Subscriber; -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.Optional; import java.util.Set; -@RunWith(MockitoJUnitRunner.class) -public class SpiImplPushExecutorHolderTest { +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@ExtendWith(MockitoExtension.class) +class SpiImplPushExecutorHolderTest { + + private static final String CLIENT_ID = "CLIENT_ID"; @Mock private Subscriber subscriber; @@ -40,10 +44,8 @@ public class SpiImplPushExecutorHolderTest { private SpiImplPushExecutorHolder spiImplPushExecutorHolder; - private static final String CLIENT_ID = "CLIENT_ID"; - - @Before - public void setUp() throws NoSuchFieldException, IllegalAccessException { + @BeforeEach + void setUp() throws NoSuchFieldException, IllegalAccessException { spiImplPushExecutorHolder = SpiImplPushExecutorHolder.getInstance(); Class spiImplPushExecutorHolderClass = SpiImplPushExecutorHolder.class; Field pushExecutors = spiImplPushExecutorHolderClass.getDeclaredField("pushExecutors"); @@ -53,18 +55,17 @@ public void setUp() throws NoSuchFieldException, IllegalAccessException { } @Test - public void testGetInstance() { + void testGetInstance() { SpiImplPushExecutorHolder instance = SpiImplPushExecutorHolder.getInstance(); - Assert.assertNotNull(instance); + assertNotNull(instance); } @Test - public void testFindPushExecutorSpiImpl() { + void testFindPushExecutorSpiImpl() { Mockito.when(spiPushExecutor.isInterest(CLIENT_ID, subscriber)).thenReturn(true); - Optional pushExecutorSpiImpl = spiImplPushExecutorHolder - .findPushExecutorSpiImpl(CLIENT_ID, subscriber); + Optional pushExecutorSpiImpl = spiImplPushExecutorHolder.findPushExecutorSpiImpl(CLIENT_ID, subscriber); - Assert.assertTrue(pushExecutorSpiImpl.isPresent()); + assertTrue(pushExecutorSpiImpl.isPresent()); } } \ No newline at end of file diff --git a/naming/src/test/java/com/alibaba/nacos/naming/push/v2/hook/NacosMonitorPushResultHookTest.java b/naming/src/test/java/com/alibaba/nacos/naming/push/v2/hook/NacosMonitorPushResultHookTest.java index 7310a976392..8baf0f124e5 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/push/v2/hook/NacosMonitorPushResultHookTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/push/v2/hook/NacosMonitorPushResultHookTest.java @@ -23,17 +23,19 @@ import com.alibaba.nacos.plugin.control.tps.TpsControlManager; import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.utils.ApplicationUtils; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.mock.env.MockEnvironment; import java.util.ArrayList; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; /** @@ -41,8 +43,13 @@ * * @author liuyixiao */ -@RunWith(MockitoJUnitRunner.Silent.class) -public class NacosMonitorPushResultHookTest { +@MockitoSettings(strictness = Strictness.LENIENT) +@ExtendWith(MockitoExtension.class) +class NacosMonitorPushResultHookTest { + + private final ServiceInfo serviceInfo = new ServiceInfo("name", "cluster"); + + private final long allCost = 100L; @Mock private PushResult pushResult; @@ -59,12 +66,8 @@ public class NacosMonitorPushResultHookTest { @Mock private Instance instance; - private final ServiceInfo serviceInfo = new ServiceInfo("name", "cluster"); - - private final long allCost = 100L; - - @Before - public void setUp() { + @BeforeEach + void setUp() { EnvUtil.setEnvironment(new MockEnvironment()); MetricsMonitor.resetAll(); serviceInfo.setHosts(new ArrayList<>()); @@ -79,7 +82,7 @@ public void setUp() { } @Test - public void testPushSuccessForEmptyPush() { + void testPushSuccessForEmptyPush() { new NacosMonitorPushResultHook().pushSuccess(pushResult); assertEquals(1, MetricsMonitor.getTotalPushMonitor().get()); assertEquals(1, MetricsMonitor.getEmptyPushMonitor().get()); @@ -87,7 +90,7 @@ public void testPushSuccessForEmptyPush() { } @Test - public void testPushSuccessForNoEmptyPush() { + void testPushSuccessForNoEmptyPush() { ArrayList hosts = new ArrayList<>(); hosts.add(instance); serviceInfo.setHosts(hosts); @@ -98,7 +101,7 @@ public void testPushSuccessForNoEmptyPush() { } @Test - public void testPushFailed() { + void testPushFailed() { new NacosMonitorPushResultHook().pushFailed(pushResult); assertEquals(1, MetricsMonitor.getFailedPushMonitor().get()); assertEquals(1, MetricsMonitor.getTotalPushMonitor().get()); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/push/v2/task/FixturePushExecutor.java b/naming/src/test/java/com/alibaba/nacos/naming/push/v2/task/FixturePushExecutor.java index 021dc619518..f26fb516a50 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/push/v2/task/FixturePushExecutor.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/push/v2/task/FixturePushExecutor.java @@ -31,8 +31,7 @@ public void doPush(String clientId, Subscriber subscriber, PushDataWrapper data) } @Override - public void doPushWithCallback(String clientId, Subscriber subscriber, PushDataWrapper data, - NamingPushCallback callBack) { + public void doPushWithCallback(String clientId, Subscriber subscriber, PushDataWrapper data, NamingPushCallback callBack) { if (shouldSuccess) { callBack.onSuccess(); } else { diff --git a/naming/src/test/java/com/alibaba/nacos/naming/push/v2/task/PushDelayTaskExecuteEngineTest.java b/naming/src/test/java/com/alibaba/nacos/naming/push/v2/task/PushDelayTaskExecuteEngineTest.java index cf400673d15..e3ed6b8d5ed 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/push/v2/task/PushDelayTaskExecuteEngineTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/push/v2/task/PushDelayTaskExecuteEngineTest.java @@ -27,12 +27,12 @@ import com.alibaba.nacos.naming.pojo.Subscriber; import com.alibaba.nacos.naming.push.v2.PushDataWrapper; import com.alibaba.nacos.naming.push.v2.executor.PushExecutor; -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.util.Collections; import java.util.concurrent.TimeUnit; @@ -42,8 +42,12 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class PushDelayTaskExecuteEngineTest { +@ExtendWith(MockitoExtension.class) +class PushDelayTaskExecuteEngineTest { + + private final Service service = Service.newService("N", "G", "S"); + + private final String clientId = "testClient"; @Mock private ClientManager clientManager; @@ -69,30 +73,26 @@ public class PushDelayTaskExecuteEngineTest { @Mock private SwitchDomain switchDomain; - private final Service service = Service.newService("N", "G", "S"); - - private final String clientId = "testClient"; - private PushDelayTaskExecuteEngine executeEngine; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { when(serviceStorage.getPushData(service)).thenReturn(new ServiceInfo("G@@S")); when(indexesManager.getAllClientsSubscribeService(service)).thenReturn(Collections.singletonList(clientId)); when(clientManager.getClient(clientId)).thenReturn(client); when(client.getSubscriber(service)).thenReturn(subscriber); when(switchDomain.isPushEnabled()).thenReturn(true); - executeEngine = new PushDelayTaskExecuteEngine(clientManager, indexesManager, serviceStorage, metadataManager, - pushExecutor, switchDomain); + executeEngine = new PushDelayTaskExecuteEngine(clientManager, indexesManager, serviceStorage, metadataManager, pushExecutor, + switchDomain); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { executeEngine.shutdown(); } @Test - public void testAddTask() throws InterruptedException { + void testAddTask() throws InterruptedException { PushDelayTask pushDelayTask = new PushDelayTask(service, 0L); executeEngine.addTask(service, pushDelayTask); TimeUnit.MILLISECONDS.sleep(200L); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/push/v2/task/PushDelayTaskTest.java b/naming/src/test/java/com/alibaba/nacos/naming/push/v2/task/PushDelayTaskTest.java index 8b1579b08c1..a2e00a4fb4a 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/push/v2/task/PushDelayTaskTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/push/v2/task/PushDelayTaskTest.java @@ -18,24 +18,24 @@ import com.alibaba.nacos.common.task.AbstractDelayTask; import com.alibaba.nacos.naming.core.v2.pojo.Service; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; -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.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; /** - * For Understand this test case, Please Read {@link com.alibaba.nacos.common.task.engine.NacosDelayTaskExecuteEngine#addTask(Object, - * AbstractDelayTask)}. + * For Understand this test case, Please Read + * {@link com.alibaba.nacos.common.task.engine.NacosDelayTaskExecuteEngine#addTask(Object, AbstractDelayTask)}. * * @author xiweng.yy */ -public class PushDelayTaskTest { +class PushDelayTaskTest { private final Service service = Service.newService("N", "G", "S"); @@ -45,14 +45,14 @@ public class PushDelayTaskTest { private PushDelayTask singlePushTask; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { pushToAllTask = new PushDelayTask(service, 0L); singlePushTask = new PushDelayTask(service, 0L, singleTargetClientId); } @Test - public void testMergeAllToSingle() { + void testMergeAllToSingle() { PushDelayTask newTask = singlePushTask; PushDelayTask oldTask = pushToAllTask; newTask.merge(oldTask); @@ -61,7 +61,7 @@ public void testMergeAllToSingle() { } @Test - public void testMergeSingleToAll() { + void testMergeSingleToAll() { PushDelayTask newTask = pushToAllTask; PushDelayTask oldTask = singlePushTask; newTask.merge(oldTask); @@ -70,7 +70,7 @@ public void testMergeSingleToAll() { } @Test - public void testMergeSingleToSingle() { + void testMergeSingleToSingle() { PushDelayTask oldTask = singlePushTask; PushDelayTask newTask = new PushDelayTask(service, 0L, "newClient"); newTask.merge(oldTask); @@ -83,7 +83,7 @@ public void testMergeSingleToSingle() { } @Test - public void testMergeAllToAll() throws InterruptedException { + void testMergeAllToAll() throws InterruptedException { PushDelayTask oldTask = pushToAllTask; TimeUnit.MILLISECONDS.sleep(10); PushDelayTask newTask = new PushDelayTask(service, 0L); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/push/v2/task/PushExecuteTaskTest.java b/naming/src/test/java/com/alibaba/nacos/naming/push/v2/task/PushExecuteTaskTest.java index f7723e2b22f..c998f95ad36 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/push/v2/task/PushExecuteTaskTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/push/v2/task/PushExecuteTaskTest.java @@ -28,26 +28,29 @@ import com.alibaba.nacos.naming.push.v2.NoRequiredRetryException; import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.utils.ApplicationUtils; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.mock.env.MockEnvironment; import java.util.Collections; import java.util.Optional; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.Silent.class) -public class PushExecuteTaskTest { +@MockitoSettings(strictness = Strictness.LENIENT) +@ExtendWith(MockitoExtension.class) +class PushExecuteTaskTest { private final Service service = Service.newService("N", "G", "S"); @@ -79,8 +82,8 @@ public class PushExecuteTaskTest { @Mock private Subscriber subscriber; - @Before - public void setUp() { + @BeforeEach + void setUp() { EnvUtil.setEnvironment(new MockEnvironment()); MetricsMonitor.resetAll(); when(indexesManager.getAllClientsSubscribeService(service)).thenReturn(Collections.singletonList(clientId)); @@ -97,7 +100,7 @@ public void setUp() { } @Test - public void testRunSuccessForPushAll() { + void testRunSuccessForPushAll() { PushDelayTask delayTask = new PushDelayTask(service, 0L); PushExecuteTask executeTask = new PushExecuteTask(service, delayTaskExecuteEngine, delayTask); executeTask.run(); @@ -105,7 +108,7 @@ public void testRunSuccessForPushAll() { } @Test - public void testRunSuccessForPushSingle() { + void testRunSuccessForPushSingle() { PushDelayTask delayTask = new PushDelayTask(service, 0L, clientId); PushExecuteTask executeTask = new PushExecuteTask(service, delayTaskExecuteEngine, delayTask); executeTask.run(); @@ -113,7 +116,7 @@ public void testRunSuccessForPushSingle() { } @Test - public void testRunFailedWithHandleException() { + void testRunFailedWithHandleException() { PushDelayTask delayTask = new PushDelayTask(service, 0L); PushExecuteTask executeTask = new PushExecuteTask(service, delayTaskExecuteEngine, delayTask); when(delayTaskExecuteEngine.getServiceStorage()).thenThrow(new RuntimeException()); @@ -123,7 +126,7 @@ public void testRunFailedWithHandleException() { } @Test - public void testRunFailedWithNoRetry() { + void testRunFailedWithNoRetry() { PushDelayTask delayTask = new PushDelayTask(service, 0L); PushExecuteTask executeTask = new PushExecuteTask(service, delayTaskExecuteEngine, delayTask); pushExecutor.setShouldSuccess(false); @@ -134,7 +137,7 @@ public void testRunFailedWithNoRetry() { } @Test - public void testRunFailedWithRetry() { + void testRunFailedWithRetry() { PushDelayTask delayTask = new PushDelayTask(service, 0L); PushExecuteTask executeTask = new PushExecuteTask(service, delayTaskExecuteEngine, delayTask); pushExecutor.setShouldSuccess(false); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/BatchInstanceRequestHandlerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/BatchInstanceRequestHandlerTest.java index 83f5617da12..832d3fc755e 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/BatchInstanceRequestHandlerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/BatchInstanceRequestHandlerTest.java @@ -23,25 +23,26 @@ import com.alibaba.nacos.api.naming.remote.request.BatchInstanceRequest; import com.alibaba.nacos.api.remote.request.RequestMeta; import com.alibaba.nacos.naming.core.v2.service.impl.EphemeralClientOperationServiceImpl; -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.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.ArrayList; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * {@link BatchInstanceRequestHandler} unit tests. * * @author chenhao26 * @date 2022-07-07 */ -@RunWith(MockitoJUnitRunner.class) -public class BatchInstanceRequestHandlerTest { +@ExtendWith(MockitoExtension.class) +class BatchInstanceRequestHandlerTest { @InjectMocks private BatchInstanceRequestHandler batchInstanceRequestHandler; @@ -50,7 +51,7 @@ public class BatchInstanceRequestHandlerTest { private EphemeralClientOperationServiceImpl clientOperationService; @Test - public void testHandle() throws NacosException { + void testHandle() throws NacosException { BatchInstanceRequest batchInstanceRequest = new BatchInstanceRequest(); batchInstanceRequest.setType(NamingRemoteConstants.BATCH_REGISTER_INSTANCE); batchInstanceRequest.setServiceName("service1"); @@ -66,7 +67,7 @@ public void testHandle() throws NacosException { try { batchInstanceRequestHandler.handle(batchInstanceRequest, requestMeta); } catch (Exception e) { - Assert.assertEquals(((NacosException) e).getErrCode(), NacosException.INVALID_PARAM); + assertEquals(NacosException.INVALID_PARAM, ((NacosException) e).getErrCode()); } } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/DistroDataRequestHandlerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/DistroDataRequestHandlerTest.java index e7a33c42d8c..b2a3c50bbad 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/DistroDataRequestHandlerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/DistroDataRequestHandlerTest.java @@ -24,19 +24,20 @@ import com.alibaba.nacos.core.distributed.distro.entity.DistroData; import com.alibaba.nacos.naming.cluster.remote.request.DistroDataRequest; import com.alibaba.nacos.naming.cluster.remote.response.DistroDataResponse; -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.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import static com.alibaba.nacos.consistency.DataOperation.ADD; import static com.alibaba.nacos.consistency.DataOperation.DELETE; import static com.alibaba.nacos.consistency.DataOperation.QUERY; import static com.alibaba.nacos.consistency.DataOperation.SNAPSHOT; import static com.alibaba.nacos.consistency.DataOperation.VERIFY; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * {@link DistroDataRequestHandler} unit tests. @@ -44,8 +45,8 @@ * @author chenglu * @date 2021-09-17 20:50 */ -@RunWith(MockitoJUnitRunner.class) -public class DistroDataRequestHandlerTest { +@ExtendWith(MockitoExtension.class) +class DistroDataRequestHandlerTest { @InjectMocks private DistroDataRequestHandler distroDataRequestHandler; @@ -54,33 +55,33 @@ public class DistroDataRequestHandlerTest { private DistroProtocol distroProtocol; @Test - public void testHandle() throws NacosException { + void testHandle() throws NacosException { Mockito.when(distroProtocol.onVerify(Mockito.any(), Mockito.anyString())).thenReturn(false); DistroDataRequest distroDataRequest = new DistroDataRequest(); distroDataRequest.setDataOperation(VERIFY); RequestMeta requestMeta = new RequestMeta(); DistroDataResponse response = distroDataRequestHandler.handle(distroDataRequest, requestMeta); - Assert.assertEquals(response.getErrorCode(), ResponseCode.FAIL.getCode()); - + assertEquals(response.getErrorCode(), ResponseCode.FAIL.getCode()); + DistroData distroData = new DistroData(); Mockito.when(distroProtocol.onSnapshot(Mockito.any())).thenReturn(distroData); distroDataRequest.setDataOperation(SNAPSHOT); DistroDataResponse response1 = distroDataRequestHandler.handle(distroDataRequest, requestMeta); - Assert.assertEquals(response1.getDistroData(), distroData); + assertEquals(response1.getDistroData(), distroData); distroDataRequest.setDataOperation(DELETE); Mockito.when(distroProtocol.onReceive(Mockito.any())).thenReturn(false); DistroDataResponse response2 = distroDataRequestHandler.handle(distroDataRequest, requestMeta); - Assert.assertEquals(response2.getErrorCode(), ResponseCode.FAIL.getCode()); + assertEquals(response2.getErrorCode(), ResponseCode.FAIL.getCode()); distroDataRequest.setDataOperation(QUERY); Mockito.when(distroProtocol.onQuery(Mockito.any())).thenReturn(distroData); distroDataRequest.setDistroData(new DistroData()); DistroDataResponse response3 = distroDataRequestHandler.handle(distroDataRequest, requestMeta); - Assert.assertEquals(response3.getDistroData(), distroData); + assertEquals(response3.getDistroData(), distroData); distroDataRequest.setDataOperation(ADD); DistroDataResponse response4 = distroDataRequestHandler.handle(distroDataRequest, requestMeta); - Assert.assertNull(response4.getDistroData()); + assertNull(response4.getDistroData()); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/InstanceRequestHandlerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/InstanceRequestHandlerTest.java index 97fd9c4dc99..17990078154 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/InstanceRequestHandlerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/InstanceRequestHandlerTest.java @@ -23,13 +23,14 @@ import com.alibaba.nacos.api.naming.remote.request.InstanceRequest; import com.alibaba.nacos.api.remote.request.RequestMeta; import com.alibaba.nacos.naming.core.v2.service.impl.EphemeralClientOperationServiceImpl; -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.InjectMocks; 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; /** * {@link InstanceRequestHandler} unit tests. @@ -37,8 +38,8 @@ * @author chenglu * @date 2021-09-17 12:49 */ -@RunWith(MockitoJUnitRunner.class) -public class InstanceRequestHandlerTest { +@ExtendWith(MockitoExtension.class) +class InstanceRequestHandlerTest { @InjectMocks private InstanceRequestHandler instanceRequestHandler; @@ -47,7 +48,7 @@ public class InstanceRequestHandlerTest { private EphemeralClientOperationServiceImpl clientOperationService; @Test - public void testHandle() throws NacosException { + void testHandle() throws NacosException { InstanceRequest instanceRequest = new InstanceRequest(); instanceRequest.setType(NamingRemoteConstants.REGISTER_INSTANCE); instanceRequest.setServiceName("service1"); @@ -66,7 +67,7 @@ public void testHandle() throws NacosException { try { instanceRequestHandler.handle(instanceRequest, requestMeta); } catch (Exception e) { - Assert.assertEquals(((NacosException) e).getErrCode(), NacosException.INVALID_PARAM); + assertEquals(NacosException.INVALID_PARAM, ((NacosException) e).getErrCode()); } } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/PersistentInstanceRequestHandlerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/PersistentInstanceRequestHandlerTest.java index 215d931640b..5984037eb45 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/PersistentInstanceRequestHandlerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/PersistentInstanceRequestHandlerTest.java @@ -23,30 +23,31 @@ import com.alibaba.nacos.api.naming.remote.request.PersistentInstanceRequest; import com.alibaba.nacos.api.remote.request.RequestMeta; import com.alibaba.nacos.naming.core.v2.service.impl.PersistentClientOperationServiceImpl; -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.InjectMocks; 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; /** * {@link PersistentInstanceRequestHandler} unit tests. * * @author blake.qiu */ -@RunWith(MockitoJUnitRunner.class) -public class PersistentInstanceRequestHandlerTest { - +@ExtendWith(MockitoExtension.class) +class PersistentInstanceRequestHandlerTest { + @InjectMocks private PersistentInstanceRequestHandler persistentInstanceRequestHandler; - + @Mock private PersistentClientOperationServiceImpl clientOperationService; - + @Test - public void testHandle() throws NacosException { + void testHandle() throws NacosException { PersistentInstanceRequest instanceRequest = new PersistentInstanceRequest(); instanceRequest.setType(NamingRemoteConstants.REGISTER_INSTANCE); instanceRequest.setServiceName("service1"); @@ -56,16 +57,16 @@ public void testHandle() throws NacosException { RequestMeta requestMeta = new RequestMeta(); persistentInstanceRequestHandler.handle(instanceRequest, requestMeta); Mockito.verify(clientOperationService).registerInstance(Mockito.any(), Mockito.any(), Mockito.anyString()); - + instanceRequest.setType(NamingRemoteConstants.DE_REGISTER_INSTANCE); persistentInstanceRequestHandler.handle(instanceRequest, requestMeta); Mockito.verify(clientOperationService).deregisterInstance(Mockito.any(), Mockito.any(), Mockito.anyString()); - + instanceRequest.setType("xxx"); try { persistentInstanceRequestHandler.handle(instanceRequest, requestMeta); } catch (Exception e) { - Assert.assertEquals(((NacosException) e).getErrCode(), NacosException.INVALID_PARAM); + assertEquals(NacosException.INVALID_PARAM, ((NacosException) e).getErrCode()); } } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/ServiceListRequestHandlerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/ServiceListRequestHandlerTest.java index a0be4db63ba..0bd83750ca2 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/ServiceListRequestHandlerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/ServiceListRequestHandlerTest.java @@ -23,10 +23,12 @@ import com.alibaba.nacos.api.remote.request.RequestMeta; import com.alibaba.nacos.naming.core.v2.ServiceManager; import com.alibaba.nacos.naming.core.v2.pojo.Service; -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 static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link ServiceListRequestHandler} unit tests. @@ -34,23 +36,23 @@ * @author chenglu * @date 2021-09-17 20:59 */ -public class ServiceListRequestHandlerTest { +class ServiceListRequestHandlerTest { private Service service; - @Before - public void setUp() { + @BeforeEach + void setUp() { service = Service.newService("A", "B", "C"); ServiceManager.getInstance().getSingleton(service); } - @After - public void tearDown() { + @AfterEach + void tearDown() { ServiceManager.getInstance().removeSingleton(service); } @Test - public void testHandle() throws NacosException { + void testHandle() throws NacosException { ServiceListRequest serviceListRequest = new ServiceListRequest(); serviceListRequest.setNamespace("A"); serviceListRequest.setPageNo(1); @@ -58,7 +60,7 @@ public void testHandle() throws NacosException { serviceListRequest.setGroupName("B"); ServiceListRequestHandler serviceListRequestHandler = new ServiceListRequestHandler(); ServiceListResponse serviceListResponse = serviceListRequestHandler.handle(serviceListRequest, new RequestMeta()); - Assert.assertEquals(serviceListResponse.getCount(), 1); - Assert.assertTrue(serviceListResponse.getServiceNames().contains("C")); + assertEquals(1, serviceListResponse.getCount()); + assertTrue(serviceListResponse.getServiceNames().contains("C")); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/ServiceQueryRequestHandlerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/ServiceQueryRequestHandlerTest.java index b9b5fb56209..0d72fb4c40b 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/ServiceQueryRequestHandlerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/ServiceQueryRequestHandlerTest.java @@ -28,29 +28,30 @@ import com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata; import com.alibaba.nacos.naming.selector.SelectorManager; import com.alibaba.nacos.sys.utils.ApplicationUtils; -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.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.context.ConfigurableApplicationContext; import java.util.Arrays; import java.util.List; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * {@link ServiceQueryRequestHandler} unit tests. * * @author chenglu * @date 2021-09-17 19:11 */ -@RunWith(MockitoJUnitRunner.class) -public class ServiceQueryRequestHandlerTest { - +@ExtendWith(MockitoExtension.class) +class ServiceQueryRequestHandlerTest { + @InjectMocks private ServiceQueryRequestHandler serviceQueryRequestHandler; @@ -66,15 +67,15 @@ public class ServiceQueryRequestHandlerTest { @Mock private SelectorManager selectorManager; - @Before - public void setUp() { + @BeforeEach + void setUp() { ApplicationUtils applicationUtils = new ApplicationUtils(); applicationUtils.initialize(applicationContext); Mockito.when(applicationContext.getBean(SelectorManager.class)).thenReturn(selectorManager); } @Test - public void testHandle() throws NacosException { + void testHandle() throws NacosException { Instance instance = new Instance(); instance.setIp("1.1.1.1"); List instances = Arrays.asList(instance); @@ -94,7 +95,7 @@ public void testHandle() throws NacosException { serviceQueryRequest.setServiceName("C"); serviceQueryRequest.setHealthyOnly(false); QueryServiceResponse queryServiceResponse = serviceQueryRequestHandler.handle(serviceQueryRequest, new RequestMeta()); - - Assert.assertEquals(queryServiceResponse.getServiceInfo().getName(), "C"); + + assertEquals("C", queryServiceResponse.getServiceInfo().getName()); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/SubscribeServiceRequestHandlerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/SubscribeServiceRequestHandlerTest.java index a8eb1fe12a7..673792f30dd 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/SubscribeServiceRequestHandlerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/SubscribeServiceRequestHandlerTest.java @@ -23,34 +23,37 @@ import com.alibaba.nacos.api.naming.remote.request.SubscribeServiceRequest; import com.alibaba.nacos.api.naming.remote.response.SubscribeServiceResponse; import com.alibaba.nacos.api.remote.request.RequestMeta; +import com.alibaba.nacos.core.context.RequestContextHolder; import com.alibaba.nacos.naming.core.v2.index.ServiceStorage; import com.alibaba.nacos.naming.core.v2.metadata.NamingMetadataManager; import com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata; import com.alibaba.nacos.naming.core.v2.service.impl.EphemeralClientOperationServiceImpl; import com.alibaba.nacos.naming.selector.SelectorManager; import com.alibaba.nacos.sys.utils.ApplicationUtils; -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.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.context.ConfigurableApplicationContext; import java.util.Arrays; import java.util.List; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * {@link SubscribeServiceRequestHandler} unit tests. * * @author chenglu * @date 2021-09-18 18:25 */ -@RunWith(MockitoJUnitRunner.class) -public class SubscribeServiceRequestHandlerTest { +@ExtendWith(MockitoExtension.class) +class SubscribeServiceRequestHandlerTest { @InjectMocks private SubscribeServiceRequestHandler subscribeServiceRequestHandler; @@ -70,15 +73,20 @@ public class SubscribeServiceRequestHandlerTest { @Mock private SelectorManager selectorManager; - @Before - public void setUp() { + @BeforeEach + void setUp() { ApplicationUtils applicationUtils = new ApplicationUtils(); applicationUtils.initialize(applicationContext); Mockito.when(applicationContext.getBean(SelectorManager.class)).thenReturn(selectorManager); } + @AfterEach + void tearDown() { + RequestContextHolder.removeContext(); + } + @Test - public void testHandle() throws NacosException { + void testHandle() throws NacosException { Instance instance = new Instance(); instance.setIp("1.1.1.1"); List instances = Arrays.asList(instance); @@ -88,7 +96,7 @@ public void testHandle() throws NacosException { serviceInfo.setName("C"); serviceInfo.setHosts(instances); Mockito.when(serviceStorage.getData(Mockito.any())).thenReturn(serviceInfo); - + ServiceMetadata serviceMetadata = new ServiceMetadata(); Mockito.when(metadataManager.getServiceMetadata(Mockito.any())).thenReturn(Optional.of(serviceMetadata)); @@ -97,13 +105,14 @@ public void testHandle() throws NacosException { subscribeServiceRequest.setGroupName("B"); subscribeServiceRequest.setServiceName("C"); subscribeServiceRequest.setSubscribe(true); - SubscribeServiceResponse subscribeServiceResponse = subscribeServiceRequestHandler.handle(subscribeServiceRequest, new RequestMeta()); - Assert.assertEquals(subscribeServiceResponse.getServiceInfo().getName(), "C"); + SubscribeServiceResponse subscribeServiceResponse = subscribeServiceRequestHandler.handle(subscribeServiceRequest, + new RequestMeta()); + assertEquals("C", subscribeServiceResponse.getServiceInfo().getName()); Mockito.verify(clientOperationService).subscribeService(Mockito.any(), Mockito.any(), Mockito.anyString()); - + subscribeServiceRequest.setSubscribe(false); subscribeServiceResponse = subscribeServiceRequestHandler.handle(subscribeServiceRequest, new RequestMeta()); - Assert.assertEquals(subscribeServiceResponse.getServiceInfo().getName(), "C"); + assertEquals("C", subscribeServiceResponse.getServiceInfo().getName()); Mockito.verify(clientOperationService).subscribeService(Mockito.any(), Mockito.any(), Mockito.anyString()); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/remote/udp/UdpConnectorTest.java b/naming/src/test/java/com/alibaba/nacos/naming/remote/udp/UdpConnectorTest.java index 18469bc4dd7..df3e9990607 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/remote/udp/UdpConnectorTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/remote/udp/UdpConnectorTest.java @@ -20,16 +20,15 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.remote.PushCallBack; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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 org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.env.MockEnvironment; import org.springframework.test.util.ReflectionTestUtils; @@ -39,6 +38,8 @@ import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; +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.Mockito.doAnswer; import static org.mockito.Mockito.when; @@ -49,8 +50,8 @@ * @author chenglu * @date 2021-09-15 19:52 */ -@RunWith(MockitoJUnitRunner.class) -public class UdpConnectorTest { +@ExtendWith(MockitoExtension.class) +class UdpConnectorTest { @InjectMocks private UdpConnector udpConnector; @@ -64,13 +65,13 @@ public class UdpConnectorTest { @Mock private DatagramSocket udpSocket; - @BeforeClass - public static void setEnv() { + @BeforeAll + static void setEnv() { EnvUtil.setEnvironment(new MockEnvironment()); } - @Before - public void setUp() throws IOException, InterruptedException { + @BeforeEach + void setUp() throws IOException, InterruptedException { ReflectionTestUtils.setField(udpConnector, "ackMap", ackMap); ReflectionTestUtils.setField(udpConnector, "callbackMap", callbackMap); DatagramSocket oldSocket = (DatagramSocket) ReflectionTestUtils.getField(udpConnector, "udpSocket"); @@ -83,20 +84,20 @@ public void setUp() throws IOException, InterruptedException { TimeUnit.SECONDS.sleep(1); } - @After - public void tearDown() throws InterruptedException { + @AfterEach + void tearDown() throws InterruptedException { udpConnector.shutdown(); TimeUnit.SECONDS.sleep(1); } @Test - public void testContainAck() { + void testContainAck() { when(ackMap.containsKey("1111")).thenReturn(true); - Assert.assertTrue(udpConnector.containAck("1111")); + assertTrue(udpConnector.containAck("1111")); } @Test - public void testSendData() throws NacosException, IOException { + void testSendData() throws NacosException, IOException { when(udpSocket.isClosed()).thenReturn(false); AckEntry ackEntry = new AckEntry("A", new DatagramPacket(new byte[2], 2)); udpConnector.sendData(ackEntry); @@ -104,7 +105,7 @@ public void testSendData() throws NacosException, IOException { } @Test - public void testSendDataWithCallback() throws IOException, InterruptedException { + void testSendDataWithCallback() throws IOException, InterruptedException { when(udpSocket.isClosed()).thenReturn(false); AckEntry ackEntry = new AckEntry("A", new DatagramPacket(new byte[2], 2)); udpConnector.sendDataWithCallback(ackEntry, new PushCallBack() { @@ -120,7 +121,7 @@ public void onSuccess() { @Override public void onFail(Throwable e) { - Assert.fail(e.getMessage()); + fail(e.getMessage()); } }); Thread.sleep(100); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/selector/LabelSelectorTest.java b/naming/src/test/java/com/alibaba/nacos/naming/selector/LabelSelectorTest.java index bb85cbc4a1e..67c7a320f07 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/selector/LabelSelectorTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/selector/LabelSelectorTest.java @@ -19,9 +19,11 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.selector.Selector; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link LabelSelector} unit test. @@ -29,24 +31,24 @@ * @author chenglu * @date 2021-07-16 17:41 */ -public class LabelSelectorTest { +class LabelSelectorTest { private SelectorManager selectorManager; - @Before - public void setUp() { + @BeforeEach + void setUp() { selectorManager = new SelectorManager(); selectorManager.init(); } @Test - public void testParseSelector() throws NacosException { + void testParseSelector() throws NacosException { Selector selector = selectorManager.parseSelector("label", "CONSUMER.label.A=PROVIDER.label.A &CONSUMER.label.B=PROVIDER.label.B"); - Assert.assertTrue(selector instanceof LabelSelector); - + assertTrue(selector instanceof LabelSelector); + LabelSelector labelSelector = (LabelSelector) selector; - Assert.assertEquals(2, labelSelector.getLabels().size()); - Assert.assertTrue(labelSelector.getLabels().contains("A")); - Assert.assertTrue(labelSelector.getLabels().contains("B")); + assertEquals(2, labelSelector.getLabels().size()); + assertTrue(labelSelector.getLabels().contains("A")); + assertTrue(labelSelector.getLabels().contains("B")); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/selector/MockCmdbContextBuilder.java b/naming/src/test/java/com/alibaba/nacos/naming/selector/MockCmdbContextBuilder.java index de35856ef32..22f4940f11d 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/selector/MockCmdbContextBuilder.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/selector/MockCmdbContextBuilder.java @@ -44,22 +44,19 @@ public CmdbContext build(String consumerIp, List provider) { CmdbContext cmdbContext = new CmdbContext(); cmdbContext.setConsumer(con); - List providers = provider - .stream() - .map(p -> { - Entity entity = new Entity(); - entity.setType("mockType"); - entity.setName("mockName"); - Map labels = new HashMap<>(); - labels.put("key", "value"); - entity.setLabels(labels); - - CmdbContext.CmdbInstance pro = new CmdbContext.CmdbInstance<>(); - pro.setInstance(p); - pro.setEntity(entity); - return pro; - }) - .collect(Collectors.toList()); + List providers = provider.stream().map(p -> { + Entity entity = new Entity(); + entity.setType("mockType"); + entity.setName("mockName"); + Map labels = new HashMap<>(); + labels.put("key", "value"); + entity.setLabels(labels); + + CmdbContext.CmdbInstance pro = new CmdbContext.CmdbInstance<>(); + pro.setInstance(p); + pro.setEntity(entity); + return pro; + }).collect(Collectors.toList()); cmdbContext.setProviders(providers); return cmdbContext; } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/selector/MockSelector.java b/naming/src/test/java/com/alibaba/nacos/naming/selector/MockSelector.java index 9b18116bd81..74b62c1f3a4 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/selector/MockSelector.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/selector/MockSelector.java @@ -59,17 +59,13 @@ protected List doSelect(CmdbContext context) { if (context.getProviders() == null) { return null; } - return context.getProviders() - .stream() - .filter(provider -> { - Map labels = provider.getEntity().getLabels(); - if (labels == null) { - return false; - } - return value.equals(labels.get(key)); - }) - .map(CmdbContext.CmdbInstance::getInstance) - .collect(Collectors.toList()); + return context.getProviders().stream().filter(provider -> { + Map labels = provider.getEntity().getLabels(); + if (labels == null) { + return false; + } + return value.equals(labels.get(key)); + }).map(CmdbContext.CmdbInstance::getInstance).collect(Collectors.toList()); } @Override diff --git a/naming/src/test/java/com/alibaba/nacos/naming/selector/NoneSelectorTest.java b/naming/src/test/java/com/alibaba/nacos/naming/selector/NoneSelectorTest.java index 9663767664b..0cdbf94ed9e 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/selector/NoneSelectorTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/selector/NoneSelectorTest.java @@ -18,24 +18,25 @@ package com.alibaba.nacos.naming.selector; 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.Collections; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * {@link NoneSelector} unit tests. * * @author chenglu * @date 2021-08-05 19:47 */ -public class NoneSelectorTest { +class NoneSelectorTest { @Test - public void testSelect() { + void testSelect() { NoneSelector noneSelector = new NoneSelector<>(); List providers = Collections.emptyList(); - Assert.assertEquals(providers, noneSelector.select(providers)); + assertEquals(providers, noneSelector.select(providers)); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/selector/SelectorManagerTest.java b/naming/src/test/java/com/alibaba/nacos/naming/selector/SelectorManagerTest.java index 5dc897ddb7b..b71b90d795b 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/selector/SelectorManagerTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/selector/SelectorManagerTest.java @@ -22,70 +22,72 @@ import com.alibaba.nacos.api.selector.Selector; import com.alibaba.nacos.consistency.SerializeFactory; import com.alibaba.nacos.consistency.Serializer; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * {@link SelectorManager} unit test. * * @author chenglu * @date 2021-07-14 18:58 */ -public class SelectorManagerTest { +class SelectorManagerTest { private SelectorManager selectorManager; - @Before - public void setUp() { + @BeforeEach + void setUp() { selectorManager = new SelectorManager(); selectorManager.init(); } @Test - public void testGetAllSelectorTypes() { + void testGetAllSelectorTypes() { List selectorTypes = selectorManager.getAllSelectorTypes(); - Assert.assertTrue(selectorTypes.contains("mock")); + assertTrue(selectorTypes.contains("mock")); } @Test - public void testParseSelector() throws NacosException { + void testParseSelector() throws NacosException { Selector selector = selectorManager.parseSelector("mock", "key=value"); - Assert.assertTrue(selector instanceof MockSelector); + assertTrue(selector instanceof MockSelector); - Assert.assertEquals("mock", selector.getType()); + assertEquals("mock", selector.getType()); } @Test - public void testSelect() throws NacosException { + void testSelect() throws NacosException { Selector selector = selectorManager.parseSelector("mock", "key=value"); Instance instance = new Instance(); instance.setIp("2.2.2.2"); List providers = Collections.singletonList(instance); List instances0 = selectorManager.select(selector, "1.1.1.1", providers); - Assert.assertEquals(1, instances0.size()); - Assert.assertEquals("2.2.2.2", instances0.get(0).getIp()); - + assertEquals(1, instances0.size()); + assertEquals("2.2.2.2", instances0.get(0).getIp()); + // test json serial for Selector Serializer serializer0 = SerializeFactory.getSerializer("JSON"); byte[] bytes = serializer0.serialize(selector); Selector jsonSelector = serializer0.deserialize(bytes, Selector.class); List instances1 = selectorManager.select(jsonSelector, "1.1.1.1", providers); - Assert.assertEquals(1, instances1.size()); - Assert.assertEquals("2.2.2.2", instances1.get(0).getIp()); + assertEquals(1, instances1.size()); + assertEquals("2.2.2.2", instances1.get(0).getIp()); // test hessian serial for Selector Serializer serializer1 = SerializeFactory.getDefault(); byte[] bytes1 = serializer1.serialize(selector); Selector hessianSelector = serializer1.deserialize(bytes1); - + List instances2 = selectorManager.select(hessianSelector, "1.1.1.1", providers); - Assert.assertEquals(1, instances2.size()); - Assert.assertEquals("2.2.2.2", instances2.get(0).getIp()); + assertEquals(1, instances2.size()); + assertEquals("2.2.2.2", instances2.get(0).getIp()); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/selector/context/NoneSelectorContextBuilderTest.java b/naming/src/test/java/com/alibaba/nacos/naming/selector/context/NoneSelectorContextBuilderTest.java index dd6edb5c392..b72599901d6 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/selector/context/NoneSelectorContextBuilderTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/selector/context/NoneSelectorContextBuilderTest.java @@ -18,24 +18,25 @@ package com.alibaba.nacos.naming.selector.context; 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.Collections; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * {@link NoneSelectorContextBuilder} unit tests. * * @author chenglu * @date 2021-08-05 19:44 */ -public class NoneSelectorContextBuilderTest { +class NoneSelectorContextBuilderTest { @Test - public void testBuild() { + void testBuild() { NoneSelectorContextBuilder contextBuilder = new NoneSelectorContextBuilder<>(); List providers = Collections.emptyList(); - Assert.assertEquals(providers, contextBuilder.build("1.1.1.1", providers)); + assertEquals(providers, contextBuilder.build("1.1.1.1", providers)); } } diff --git a/naming/src/test/java/com/alibaba/nacos/naming/utils/DistroUtilsTest.java b/naming/src/test/java/com/alibaba/nacos/naming/utils/DistroUtilsTest.java index 2930b3db461..7438e7c72af 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/utils/DistroUtilsTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/utils/DistroUtilsTest.java @@ -21,21 +21,20 @@ import com.alibaba.nacos.naming.core.v2.client.impl.IpPortBasedClient; import com.alibaba.nacos.naming.core.v2.pojo.InstancePublishInfo; import com.alibaba.nacos.naming.core.v2.pojo.Service; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.HashMap; import static com.alibaba.nacos.api.common.Constants.DEFAULT_CLUSTER_NAME; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests for {@link DistroUtils}. * - * @author Pixy Yuan - * on 2021/10/9 + * @author Pixy Yuan on 2021/10/9 */ -public class DistroUtilsTest { +class DistroUtilsTest { private static final String NAMESPACE = "testNamespace-"; @@ -49,27 +48,25 @@ public class DistroUtilsTest { private IpPortBasedClient client1; - @Before - public void setUp() throws Exception { - client0 = buildClient("127.0.0.1", 8848, false, true, DEFAULT_CLUSTER_NAME, - null); + @BeforeEach + void setUp() throws Exception { + client0 = buildClient("127.0.0.1", 8848, false, true, DEFAULT_CLUSTER_NAME, null); HashMap metadata = new HashMap<>(); metadata.put(Constants.PUBLISH_INSTANCE_WEIGHT, 2L); metadata.put(Constants.PUBLISH_INSTANCE_ENABLE, false); metadata.put("Custom.metadataId1", "abc"); metadata.put("Custom.metadataId2", 123); metadata.put("Custom.metadataId3", null); - client1 = buildClient("127.0.0.2", 8848, true, true, "cluster1", - metadata, 20); + client1 = buildClient("127.0.0.2", 8848, true, true, "cluster1", metadata, 20); } private IpPortBasedClient buildClient(String ip, int port, boolean ephemeral, boolean healthy, String cluster, - HashMap extendDatum) { + HashMap extendDatum) { return buildClient(ip, port, ephemeral, healthy, cluster, extendDatum, 1); } private IpPortBasedClient buildClient(String ip, int port, boolean ephemeral, boolean healthy, String cluster, - HashMap extendDatum, int serviceCount) { + HashMap extendDatum, int serviceCount) { InstancePublishInfo instance = new InstancePublishInfo(ip, port); instance.setCluster(cluster); instance.setHealthy(healthy); @@ -78,73 +75,67 @@ private IpPortBasedClient buildClient(String ip, int port, boolean ephemeral, bo instance.setExtendDatum(extendDatum); } for (int i = 1; i < serviceCount + 1; i++) { - client.putServiceInstance(Service.newService(DistroUtilsTest.NAMESPACE + i, - DistroUtilsTest.GROUP + i, DistroUtilsTest.SERVICE + i, ephemeral), + client.putServiceInstance( + Service.newService(DistroUtilsTest.NAMESPACE + i, DistroUtilsTest.GROUP + i, DistroUtilsTest.SERVICE + i, ephemeral), instance); } return client; } @Test - public void testHash0() { + void testHash0() { assertEquals(-1320954445, DistroUtils.hash(client0)); } @Test - public void testRevision0() { + void testRevision0() { assertEquals(-1713189600L, DistroUtils.stringHash(client0)); } @Test - public void testChecksum0() { + void testChecksum0() { for (int i = 0; i < 3; i++) { assertEquals("2a3f62f84a4b6f2a979434276d546ac1", DistroUtils.checksum(client0)); } } @Test - public void testBuildUniqueString0() { + void testBuildUniqueString0() { assertEquals("127.0.0.1:8848#false|testNamespace-1##testGroup-1@@testName-1##false_127.0.0.1:8848_1.0_true_true_DEFAULT_,", DistroUtils.buildUniqueString(client0)); } @Test - public void testBuildUniqueString1() { + void testBuildUniqueString1() { HashMap metadata = new HashMap<>(); metadata.put(Constants.PUBLISH_INSTANCE_WEIGHT, 2L); metadata.put(Constants.PUBLISH_INSTANCE_ENABLE, false); metadata.put("Custom.metadataId1", "abc"); metadata.put("Custom.metadataId2", 123); metadata.put("Custom.metadataId3", null); - Client client = buildClient("128.0.0.1", 8848, false, false, DEFAULT_CLUSTER_NAME, - metadata); - assertEquals("128.0.0.1:8848#false|" - + "testNamespace-1##testGroup-1@@testName-1##false_128.0.0.1:8848_2.0_false_false_DEFAULT_" - + "Custom.metadataId1:abc,Custom.metadataId2:123,Custom.metadataId3:null," - + "publishInstanceEnable:false,publishInstanceWeight:2,,", - DistroUtils.buildUniqueString(client)); + Client client = buildClient("128.0.0.1", 8848, false, false, DEFAULT_CLUSTER_NAME, metadata); + assertEquals("128.0.0.1:8848#false|" + "testNamespace-1##testGroup-1@@testName-1##false_128.0.0.1:8848_2.0_false_false_DEFAULT_" + + "Custom.metadataId1:abc,Custom.metadataId2:123,Custom.metadataId3:null," + + "publishInstanceEnable:false,publishInstanceWeight:2,,", DistroUtils.buildUniqueString(client)); assertEquals(2128732271L, DistroUtils.stringHash(client)); assertEquals("ac9bf94dc4bd6a35e5ff9734868eafea", DistroUtils.checksum(client)); } @Test - public void testBuildUniqueString2() { + void testBuildUniqueString2() { HashMap metadata = new HashMap<>(); metadata.put(Constants.PUBLISH_INSTANCE_WEIGHT, 2L); metadata.put(Constants.PUBLISH_INSTANCE_ENABLE, true); metadata.put("Custom.metadataId1", "abc"); - Client client = buildClient("128.0.0.2", 7001, true, false, "cluster1", - metadata); - assertEquals("128.0.0.2:7001#true|" - + "testNamespace-1##testGroup-1@@testName-1##true_128.0.0.2:7001_2.0_false_true_cluster1_" - + "Custom.metadataId1:abc,publishInstanceEnable:true,publishInstanceWeight:2,,", - DistroUtils.buildUniqueString(client)); + Client client = buildClient("128.0.0.2", 7001, true, false, "cluster1", metadata); + assertEquals("128.0.0.2:7001#true|" + "testNamespace-1##testGroup-1@@testName-1##true_128.0.0.2:7001_2.0_false_true_cluster1_" + + "Custom.metadataId1:abc,publishInstanceEnable:true,publishInstanceWeight:2,,", DistroUtils.buildUniqueString(client)); assertEquals(775352583L, DistroUtils.stringHash(client)); assertEquals("82d8e086a880f088320349b895b22948", DistroUtils.checksum(client)); } @Test - public void performanceTestOfChecksum() { + void performanceTestOfChecksum() { long start = System.nanoTime(); for (int i = 0; i < N; i++) { DistroUtils.checksum(client1); @@ -153,7 +144,7 @@ public void performanceTestOfChecksum() { } @Test - public void performanceTestOfStringHash() { + void performanceTestOfStringHash() { long start = System.nanoTime(); for (int i = 0; i < N; i++) { DistroUtils.stringHash(client1); @@ -162,7 +153,7 @@ public void performanceTestOfStringHash() { } @Test - public void performanceTestOfHash() { + void performanceTestOfHash() { long start = System.nanoTime(); for (int i = 0; i < N; i++) { DistroUtils.hash(client1); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/utils/InstanceUtilTest.java b/naming/src/test/java/com/alibaba/nacos/naming/utils/InstanceUtilTest.java index 113f13faa5d..3f66149d7a5 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/utils/InstanceUtilTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/utils/InstanceUtilTest.java @@ -22,8 +22,8 @@ import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.naming.pojo.instance.InstanceIdGeneratorManager; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.mock.env.MockEnvironment; import java.util.ArrayList; @@ -32,30 +32,30 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -public class InstanceUtilTest { +class InstanceUtilTest { private Service service; private InstancePublishInfo instancePublishInfo; - @Before - public void init() { + @BeforeEach + void init() { EnvUtil.setEnvironment(new MockEnvironment()); service = Service.newService("namespace", "group", "serviceName"); instancePublishInfo = new InstancePublishInfo("1.1.1.1", 8080); } @Test - public void testParseToApiInstance() { + void testParseToApiInstance() { Instance instance = InstanceUtil.parseToApiInstance(service, instancePublishInfo); assertNotNull(instance); } @Test - public void testUpdateInstanceMetadata() { + void testUpdateInstanceMetadata() { InstanceMetadata metaData = new InstanceMetadata(); Map extendData = new ConcurrentHashMap<>(1); extendData.put("k1", "v1"); @@ -67,11 +67,11 @@ public void testUpdateInstanceMetadata() { InstanceUtil.updateInstanceMetadata(instance, metaData); assertNotNull(instance.getMetadata()); - assertEquals(metaData.getExtendData().size(), 2); + assertEquals(2, metaData.getExtendData().size()); } @Test - public void testDeepCopy() { + void testDeepCopy() { Instance source = new Instance(); source.setInstanceId("instanceId"); source.setIp("1.1.1.1"); @@ -91,7 +91,7 @@ public void testDeepCopy() { } @Test - public void testSetInstanceIdIfEmpty() { + void testSetInstanceIdIfEmpty() { Instance instance = new Instance(); instance.setIp("1.1.1.1"); instance.setPort(8890); @@ -108,7 +108,7 @@ public void testSetInstanceIdIfEmpty() { } @Test - public void testBatchSetInstanceIdIfEmpty() { + void testBatchSetInstanceIdIfEmpty() { final List instances = new ArrayList<>(); Instance instance1 = new Instance(); instance1.setServiceName("test"); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/utils/NamingRequestUtilTest.java b/naming/src/test/java/com/alibaba/nacos/naming/utils/NamingRequestUtilTest.java new file mode 100644 index 00000000000..cf1e6e8581c --- /dev/null +++ b/naming/src/test/java/com/alibaba/nacos/naming/utils/NamingRequestUtilTest.java @@ -0,0 +1,82 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.naming.utils; + +import com.alibaba.nacos.api.remote.request.RequestMeta; +import com.alibaba.nacos.core.context.RequestContextHolder; +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.jupiter.MockitoExtension; + +import javax.servlet.http.HttpServletRequest; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class NamingRequestUtilTest { + + @Mock + HttpServletRequest request; + + @Mock + RequestMeta meta; + + @BeforeEach + void setUp() { + RequestContextHolder.getContext().getBasicContext().getAddressContext().setRemoteIp("1.1.1.1"); + RequestContextHolder.getContext().getBasicContext().getAddressContext().setSourceIp("2.2.2.2"); + } + + @AfterEach + void tearDown() { + RequestContextHolder.removeContext(); + } + + @Test + void testGetSourceIp() { + assertEquals("2.2.2.2", NamingRequestUtil.getSourceIp()); + RequestContextHolder.getContext().getBasicContext().getAddressContext().setSourceIp(null); + assertEquals("1.1.1.1", NamingRequestUtil.getSourceIp()); + RequestContextHolder.getContext().getBasicContext().getAddressContext().setRemoteIp(null); + assertNull(NamingRequestUtil.getSourceIp()); + } + + @Test + void getSourceIpForHttpRequest() { + when(request.getRemoteAddr()).thenReturn("3.3.3.3"); + assertEquals("2.2.2.2", NamingRequestUtil.getSourceIpForHttpRequest(request)); + RequestContextHolder.getContext().getBasicContext().getAddressContext().setSourceIp(null); + assertEquals("1.1.1.1", NamingRequestUtil.getSourceIpForHttpRequest(request)); + RequestContextHolder.getContext().getBasicContext().getAddressContext().setRemoteIp(null); + assertEquals("3.3.3.3", NamingRequestUtil.getSourceIpForHttpRequest(request)); + } + + @Test + void getSourceIpForGrpcRequest() { + when(meta.getClientIp()).thenReturn("3.3.3.3"); + assertEquals("2.2.2.2", NamingRequestUtil.getSourceIpForGrpcRequest(meta)); + RequestContextHolder.getContext().getBasicContext().getAddressContext().setSourceIp(null); + assertEquals("1.1.1.1", NamingRequestUtil.getSourceIpForGrpcRequest(meta)); + RequestContextHolder.getContext().getBasicContext().getAddressContext().setRemoteIp(null); + assertEquals("3.3.3.3", NamingRequestUtil.getSourceIpForGrpcRequest(meta)); + } +} \ No newline at end of file diff --git a/naming/src/test/java/com/alibaba/nacos/naming/utils/ServiceUtilTest.java b/naming/src/test/java/com/alibaba/nacos/naming/utils/ServiceUtilTest.java index c6883013def..a5dccd96e8b 100644 --- a/naming/src/test/java/com/alibaba/nacos/naming/utils/ServiceUtilTest.java +++ b/naming/src/test/java/com/alibaba/nacos/naming/utils/ServiceUtilTest.java @@ -17,14 +17,14 @@ package com.alibaba.nacos.naming.utils; import com.alibaba.nacos.api.naming.pojo.ServiceInfo; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; -public class ServiceUtilTest { +class ServiceUtilTest { @Test - public void testSelectInstances() { + void testSelectInstances() { ServiceInfo serviceInfo = new ServiceInfo(); serviceInfo.setGroupName("groupName"); serviceInfo.setName("serviceName"); diff --git a/naming/src/test/java/com/alibaba/nacos/naming/web/ClientAttributesFilterTest.java b/naming/src/test/java/com/alibaba/nacos/naming/web/ClientAttributesFilterTest.java new file mode 100644 index 00000000000..d8d92b8a95f --- /dev/null +++ b/naming/src/test/java/com/alibaba/nacos/naming/web/ClientAttributesFilterTest.java @@ -0,0 +1,121 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.naming.web; + +import com.alibaba.nacos.common.constant.HttpHeaderConsts; +import com.alibaba.nacos.core.context.RequestContextHolder; +import com.alibaba.nacos.naming.core.v2.client.ClientAttributes; +import com.alibaba.nacos.naming.core.v2.client.impl.IpPortBasedClient; +import com.alibaba.nacos.naming.core.v2.client.manager.ClientManager; +import com.alibaba.nacos.naming.misc.UtilsAndCommons; +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.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.mock.web.MockFilterChain; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.Servlet; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Optional; + +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.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class ClientAttributesFilterTest { + + @Mock + ClientManager clientManager; + + @Mock + IpPortBasedClient client; + + @Mock + HttpServletRequest request; + + @Mock + HttpServletResponse response; + + @Mock + Servlet servlet; + + @InjectMocks + ClientAttributesFilter filter; + + @BeforeEach + void setUp() { + RequestContextHolder.getContext().getBasicContext().setUserAgent("Nacos-Java-Client:v2.4.0"); + RequestContextHolder.getContext().getBasicContext().setApp("testApp"); + RequestContextHolder.getContext().getBasicContext().getAddressContext().setRemoteIp("1.1.1.1"); + RequestContextHolder.getContext().getBasicContext().getAddressContext().setSourceIp("2.2.2.2"); + } + + @AfterEach + void tearDown() { + RequestContextHolder.removeContext(); + } + + @Test + void testDoFilterForRegisterUri() throws IOException { + when(request.getRequestURI()).thenReturn( + UtilsAndCommons.NACOS_SERVER_CONTEXT + UtilsAndCommons.NACOS_NAMING_CONTEXT + + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT); + when(request.getMethod()).thenReturn("POST"); + filter.doFilter(request, response, new MockFilterChain(servlet, new MockRegisterFilter())); + } + + @Test + void testDoFilterForBeatUri() throws IOException { + when(request.getParameter("ip")).thenReturn("127.0.0.1"); + when(request.getParameter("port")).thenReturn("8848"); + when(request.getParameter("encoding")).thenReturn("utf-8"); + when(clientManager.getClient("127.0.0.1:8848#true")).thenReturn(client); + when(request.getRequestURI()).thenReturn( + UtilsAndCommons.NACOS_SERVER_CONTEXT + UtilsAndCommons.NACOS_NAMING_CONTEXT + + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT + "/beat"); + when(request.getMethod()).thenReturn("PUT"); + filter.doFilter(request, response, new MockFilterChain()); + verify(client).setAttributes(any(ClientAttributes.class)); + } + + private static class MockRegisterFilter implements Filter { + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) + throws IOException, ServletException { + Optional clientAttributes = ClientAttributesFilter.getCurrentClientAttributes(); + assertTrue(clientAttributes.isPresent()); + assertEquals("Nacos-Java-Client:v2.4.0", + clientAttributes.get().getClientAttribute(HttpHeaderConsts.CLIENT_VERSION_HEADER)); + assertEquals("testApp", clientAttributes.get().getClientAttribute(HttpHeaderConsts.APP_FILED)); + assertEquals("2.2.2.2", clientAttributes.get().getClientAttribute(HttpHeaderConsts.CLIENT_IP)); + } + } +} \ No newline at end of file diff --git a/persistence/pom.xml b/persistence/pom.xml index a72c2f3f23a..fee4f4eba4a 100644 --- a/persistence/pom.xml +++ b/persistence/pom.xml @@ -62,6 +62,11 @@ org.apache.derby derby + + org.springframework + spring-test + test + - \ No newline at end of file + diff --git a/persistence/src/main/java/com/alibaba/nacos/persistence/repository/embedded/operate/StandaloneDatabaseOperateImpl.java b/persistence/src/main/java/com/alibaba/nacos/persistence/repository/embedded/operate/StandaloneDatabaseOperateImpl.java index 200dc04cad8..225b001fe4e 100644 --- a/persistence/src/main/java/com/alibaba/nacos/persistence/repository/embedded/operate/StandaloneDatabaseOperateImpl.java +++ b/persistence/src/main/java/com/alibaba/nacos/persistence/repository/embedded/operate/StandaloneDatabaseOperateImpl.java @@ -24,6 +24,8 @@ import com.alibaba.nacos.persistence.datasource.DataSourceService; import com.alibaba.nacos.persistence.datasource.DynamicDataSource; import com.alibaba.nacos.persistence.repository.embedded.sql.ModifyRequest; +import com.alibaba.nacos.persistence.repository.embedded.sql.limiter.SqlLimiter; +import com.alibaba.nacos.persistence.repository.embedded.sql.limiter.SqlTypeLimiter; import com.alibaba.nacos.sys.utils.DiskUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -54,10 +56,16 @@ public class StandaloneDatabaseOperateImpl implements BaseDatabaseOperate { private static final Logger LOGGER = LoggerFactory.getLogger(StandaloneDatabaseOperateImpl.class); + private final SqlLimiter sqlLimiter; + private JdbcTemplate jdbcTemplate; private TransactionTemplate transactionTemplate; + public StandaloneDatabaseOperateImpl() { + this.sqlLimiter = new SqlTypeLimiter(); + } + @PostConstruct protected void init() { DataSourceService dataSourceService = DynamicDataSource.getInstance().getDataSource(); @@ -107,6 +115,7 @@ public CompletableFuture> dataImport(File file) { while (iterator.hasNext()) { String sql = iterator.next(); if (StringUtils.isNotBlank(sql)) { + sqlLimiter.doLimit(sql); batchUpdate.add(sql); } if (batchUpdate.size() == batchSize || !iterator.hasNext()) { diff --git a/persistence/src/main/java/com/alibaba/nacos/persistence/repository/embedded/sql/limiter/SqlLimiter.java b/persistence/src/main/java/com/alibaba/nacos/persistence/repository/embedded/sql/limiter/SqlLimiter.java new file mode 100644 index 00000000000..15d5da56803 --- /dev/null +++ b/persistence/src/main/java/com/alibaba/nacos/persistence/repository/embedded/sql/limiter/SqlLimiter.java @@ -0,0 +1,79 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.persistence.repository.embedded.sql.limiter; + +import com.alibaba.nacos.persistence.repository.embedded.sql.ModifyRequest; +import com.alibaba.nacos.persistence.repository.embedded.sql.SelectRequest; + +import java.sql.SQLException; +import java.util.List; + +/** + * SQL limiter. + * + * @author xiweng.yy + */ +public interface SqlLimiter { + + /** + * Do SQL limit for modify request. + * + * @param modifyRequest modify request + * @throws SQLException when SQL match the limit rule. + */ + void doLimitForModifyRequest(ModifyRequest modifyRequest) throws SQLException; + + /** + * Do SQL limit for modify request. + * + * @param modifyRequests modify request + * @throws SQLException when SQL match the limit rule. + */ + void doLimitForModifyRequest(List modifyRequests) throws SQLException; + + /** + * Do SQL limit for select request. + * + * @param selectRequest select request + * @throws SQLException when SQL match the limit rule. + */ + void doLimitForSelectRequest(SelectRequest selectRequest) throws SQLException; + + /** + * Do SQL limit for select request. + * + * @param selectRequests select request + * @throws SQLException when SQL match the limit rule. + */ + void doLimitForSelectRequest(List selectRequests) throws SQLException; + + /** + * Do SQL limit for sql. + * + * @param sql SQL + * @throws SQLException when SQL match the limit rule. + */ + void doLimit(String sql) throws SQLException; + + /** + * Do SQL limit for sql. + * + * @param sql SQL + * @throws SQLException when SQL match the limit rule. + */ + void doLimit(List sql) throws SQLException; +} diff --git a/persistence/src/main/java/com/alibaba/nacos/persistence/repository/embedded/sql/limiter/SqlTypeLimiter.java b/persistence/src/main/java/com/alibaba/nacos/persistence/repository/embedded/sql/limiter/SqlTypeLimiter.java new file mode 100644 index 00000000000..1461607fcde --- /dev/null +++ b/persistence/src/main/java/com/alibaba/nacos/persistence/repository/embedded/sql/limiter/SqlTypeLimiter.java @@ -0,0 +1,146 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.persistence.repository.embedded.sql.limiter; + +import com.alibaba.nacos.common.utils.StringUtils; +import com.alibaba.nacos.persistence.repository.embedded.sql.ModifyRequest; +import com.alibaba.nacos.persistence.repository.embedded.sql.SelectRequest; +import com.alibaba.nacos.sys.env.EnvUtil; + +import java.sql.SQLException; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * SQL Type Limiter, Nacos only allow `INSERT`, `UPDATE`, `DELETE`, `SELECT`, `CREATE SCHEMA`, `CREATE TABLE`, `CREATE + * INDEX` and `ALTER TABLE`. + * + * @author xiweng.yy + */ +public class SqlTypeLimiter implements SqlLimiter { + + private static final String ENABLED_SQL_LIMIT = "nacos.persistence.sql.derby.limit.enabled"; + + private final Set allowedDmlSqls; + + private final Set allowedDdlSqls; + + private final Set allowedDdlScopes; + + private final boolean enabledLimit; + + public SqlTypeLimiter() { + this.enabledLimit = EnvUtil.getProperty(ENABLED_SQL_LIMIT, Boolean.class, true); + this.allowedDmlSqls = new HashSet<>(4); + this.allowedDmlSqls.add("INSERT"); + this.allowedDmlSqls.add("UPDATE"); + this.allowedDmlSqls.add("DELETE"); + this.allowedDmlSqls.add("SELECT"); + this.allowedDdlSqls = new HashSet<>(2); + this.allowedDdlSqls.add("CREATE"); + this.allowedDdlSqls.add("ALTER"); + this.allowedDdlScopes = new HashSet<>(3); + this.allowedDdlScopes.add("SCHEMA"); + this.allowedDdlScopes.add("TABLE"); + this.allowedDdlScopes.add("INDEX"); + } + + @Override + public void doLimitForModifyRequest(ModifyRequest modifyRequest) throws SQLException { + if (null == modifyRequest || !enabledLimit) { + return; + } + doLimit(modifyRequest.getSql()); + } + + @Override + public void doLimitForModifyRequest(List modifyRequests) throws SQLException { + if (null == modifyRequests || !enabledLimit) { + return; + } + for (ModifyRequest each : modifyRequests) { + doLimitForModifyRequest(each); + } + } + + @Override + public void doLimitForSelectRequest(SelectRequest selectRequest) throws SQLException { + if (null == selectRequest || !enabledLimit) { + return; + } + doLimit(selectRequest.getSql()); + } + + @Override + public void doLimitForSelectRequest(List selectRequests) throws SQLException { + if (null == selectRequests || !enabledLimit) { + return; + } + for (SelectRequest each : selectRequests) { + doLimitForSelectRequest(each); + } + } + + @Override + public void doLimit(String sql) throws SQLException { + if (!enabledLimit) { + return; + } + String trimmedSql = sql.trim(); + if (StringUtils.isEmpty(trimmedSql)) { + return; + } + int firstTokenIndex = trimmedSql.indexOf(" "); + if (-1 == firstTokenIndex) { + throwException(trimmedSql); + } + String firstToken = trimmedSql.substring(0, firstTokenIndex).toUpperCase(); + if (allowedDmlSqls.contains(firstToken)) { + return; + } + if (!allowedDdlSqls.contains(firstToken)) { + throwException(trimmedSql); + } + checkSqlForSecondToken(firstTokenIndex, trimmedSql); + } + + @Override + public void doLimit(List sql) throws SQLException { + if (null == sql || !enabledLimit) { + return; + } + for (String each : sql) { + doLimit(each); + } + } + + private void throwException(String sql) throws SQLException { + throw new SQLException(String.format("Unsupported SQL: %s. Nacos only support DML and some DDL SQL.", sql)); + } + + private void checkSqlForSecondToken(int firstTokenIndex, String trimmedSql) throws SQLException { + int secondTokenIndex = trimmedSql.indexOf(" ", firstTokenIndex + 1); + if (-1 == secondTokenIndex) { + secondTokenIndex = trimmedSql.length(); + } + String secondToken = trimmedSql.substring(firstTokenIndex + 1, secondTokenIndex).toUpperCase(); + if (!allowedDdlScopes.contains(secondToken)) { + throwException(trimmedSql); + } + } +} diff --git a/persistence/src/test/java/com/alibaba/nacos/persistence/configuration/condition/ConditionDistributedEmbedStorageTest.java b/persistence/src/test/java/com/alibaba/nacos/persistence/configuration/condition/ConditionDistributedEmbedStorageTest.java index 37f7eb95391..6c1e62a96e1 100644 --- a/persistence/src/test/java/com/alibaba/nacos/persistence/configuration/condition/ConditionDistributedEmbedStorageTest.java +++ b/persistence/src/test/java/com/alibaba/nacos/persistence/configuration/condition/ConditionDistributedEmbedStorageTest.java @@ -18,18 +18,18 @@ import com.alibaba.nacos.persistence.configuration.DatasourceConfiguration; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; -public class ConditionDistributedEmbedStorageTest { - - private ConditionDistributedEmbedStorage conditionDistributedEmbedStorage; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ConditionDistributedEmbedStorageTest { @Mock ConditionContext context; @@ -37,35 +37,36 @@ public class ConditionDistributedEmbedStorageTest { @Mock AnnotatedTypeMetadata metadata; - @Before - public void init() { + private ConditionDistributedEmbedStorage conditionDistributedEmbedStorage; + + @BeforeEach + void init() { conditionDistributedEmbedStorage = new ConditionDistributedEmbedStorage(); } @Test - public void testMatches() { - MockedStatic propertyUtilMockedStatic = Mockito - .mockStatic(DatasourceConfiguration.class); + void testMatches() { + MockedStatic propertyUtilMockedStatic = Mockito.mockStatic(DatasourceConfiguration.class); MockedStatic envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); propertyUtilMockedStatic.when(DatasourceConfiguration::isEmbeddedStorage).thenReturn(true); envUtilMockedStatic.when(EnvUtil::getStandaloneMode).thenReturn(true); - Assert.assertFalse(conditionDistributedEmbedStorage.matches(context, metadata)); + assertFalse(conditionDistributedEmbedStorage.matches(context, metadata)); Mockito.when(DatasourceConfiguration.isEmbeddedStorage()).thenReturn(true); Mockito.when(EnvUtil.getStandaloneMode()).thenReturn(false); propertyUtilMockedStatic.when(DatasourceConfiguration::isEmbeddedStorage).thenReturn(true); envUtilMockedStatic.when(EnvUtil::getStandaloneMode).thenReturn(false); - Assert.assertTrue(conditionDistributedEmbedStorage.matches(context, metadata)); + assertTrue(conditionDistributedEmbedStorage.matches(context, metadata)); propertyUtilMockedStatic.when(DatasourceConfiguration::isEmbeddedStorage).thenReturn(false); envUtilMockedStatic.when(EnvUtil::getStandaloneMode).thenReturn(true); - Assert.assertFalse(conditionDistributedEmbedStorage.matches(context, metadata)); + assertFalse(conditionDistributedEmbedStorage.matches(context, metadata)); propertyUtilMockedStatic.when(DatasourceConfiguration::isEmbeddedStorage).thenReturn(false); envUtilMockedStatic.when(EnvUtil::getStandaloneMode).thenReturn(false); - Assert.assertFalse(conditionDistributedEmbedStorage.matches(context, metadata)); + assertFalse(conditionDistributedEmbedStorage.matches(context, metadata)); propertyUtilMockedStatic.close(); envUtilMockedStatic.close(); diff --git a/persistence/src/test/java/com/alibaba/nacos/persistence/configuration/condition/ConditionOnEmbeddedStorageTest.java b/persistence/src/test/java/com/alibaba/nacos/persistence/configuration/condition/ConditionOnEmbeddedStorageTest.java index 6aa9523bb4b..2d16e8b9e2f 100644 --- a/persistence/src/test/java/com/alibaba/nacos/persistence/configuration/condition/ConditionOnEmbeddedStorageTest.java +++ b/persistence/src/test/java/com/alibaba/nacos/persistence/configuration/condition/ConditionOnEmbeddedStorageTest.java @@ -17,18 +17,18 @@ package com.alibaba.nacos.persistence.configuration.condition; import com.alibaba.nacos.persistence.configuration.DatasourceConfiguration; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; -public class ConditionOnEmbeddedStorageTest { - - private ConditionOnEmbeddedStorage conditionOnEmbeddedStorage; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ConditionOnEmbeddedStorageTest { @Mock ConditionContext context; @@ -36,19 +36,21 @@ public class ConditionOnEmbeddedStorageTest { @Mock AnnotatedTypeMetadata metadata; - @Before - public void init() { + private ConditionOnEmbeddedStorage conditionOnEmbeddedStorage; + + @BeforeEach + void init() { conditionOnEmbeddedStorage = new ConditionOnEmbeddedStorage(); } @Test - public void testMatches() { + void testMatches() { MockedStatic mockedStatic = Mockito.mockStatic(DatasourceConfiguration.class); mockedStatic.when(DatasourceConfiguration::isEmbeddedStorage).thenReturn(true); - Assert.assertTrue(conditionOnEmbeddedStorage.matches(context, metadata)); + assertTrue(conditionOnEmbeddedStorage.matches(context, metadata)); mockedStatic.when(DatasourceConfiguration::isEmbeddedStorage).thenReturn(false); - Assert.assertFalse(conditionOnEmbeddedStorage.matches(context, metadata)); + assertFalse(conditionOnEmbeddedStorage.matches(context, metadata)); mockedStatic.close(); } diff --git a/persistence/src/test/java/com/alibaba/nacos/persistence/configuration/condition/ConditionOnExternalStorageTest.java b/persistence/src/test/java/com/alibaba/nacos/persistence/configuration/condition/ConditionOnExternalStorageTest.java index b4f0b7b585f..a281341ff86 100644 --- a/persistence/src/test/java/com/alibaba/nacos/persistence/configuration/condition/ConditionOnExternalStorageTest.java +++ b/persistence/src/test/java/com/alibaba/nacos/persistence/configuration/condition/ConditionOnExternalStorageTest.java @@ -17,18 +17,18 @@ package com.alibaba.nacos.persistence.configuration.condition; import com.alibaba.nacos.persistence.configuration.DatasourceConfiguration; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; -public class ConditionOnExternalStorageTest { - - private ConditionOnExternalStorage conditionOnExternalStorage; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ConditionOnExternalStorageTest { @Mock ConditionContext context; @@ -36,20 +36,22 @@ public class ConditionOnExternalStorageTest { @Mock AnnotatedTypeMetadata metadata; - @Before - public void init() { + private ConditionOnExternalStorage conditionOnExternalStorage; + + @BeforeEach + void init() { conditionOnExternalStorage = new ConditionOnExternalStorage(); } @Test - public void testMatches() { + void testMatches() { MockedStatic mockedStatic = Mockito.mockStatic(DatasourceConfiguration.class); mockedStatic.when(DatasourceConfiguration::isEmbeddedStorage).thenReturn(true); - Assert.assertFalse(conditionOnExternalStorage.matches(context, metadata)); + assertFalse(conditionOnExternalStorage.matches(context, metadata)); mockedStatic.when(DatasourceConfiguration::isEmbeddedStorage).thenReturn(false); - Assert.assertTrue(conditionOnExternalStorage.matches(context, metadata)); + assertTrue(conditionOnExternalStorage.matches(context, metadata)); mockedStatic.close(); } diff --git a/persistence/src/test/java/com/alibaba/nacos/persistence/configuration/condition/ConditionStandaloneEmbedStorageTest.java b/persistence/src/test/java/com/alibaba/nacos/persistence/configuration/condition/ConditionStandaloneEmbedStorageTest.java index dd88bcd45a0..bb3f7541c94 100644 --- a/persistence/src/test/java/com/alibaba/nacos/persistence/configuration/condition/ConditionStandaloneEmbedStorageTest.java +++ b/persistence/src/test/java/com/alibaba/nacos/persistence/configuration/condition/ConditionStandaloneEmbedStorageTest.java @@ -18,18 +18,18 @@ import com.alibaba.nacos.persistence.configuration.DatasourceConfiguration; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; -public class ConditionStandaloneEmbedStorageTest { - - private ConditionStandaloneEmbedStorage conditionStandaloneEmbedStorage; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ConditionStandaloneEmbedStorageTest { @Mock ConditionContext context; @@ -37,32 +37,33 @@ public class ConditionStandaloneEmbedStorageTest { @Mock AnnotatedTypeMetadata metadata; - @Before - public void init() { + private ConditionStandaloneEmbedStorage conditionStandaloneEmbedStorage; + + @BeforeEach + void init() { conditionStandaloneEmbedStorage = new ConditionStandaloneEmbedStorage(); } @Test - public void testMatches() { - MockedStatic propertyUtilMockedStatic = Mockito - .mockStatic(DatasourceConfiguration.class); + void testMatches() { + MockedStatic propertyUtilMockedStatic = Mockito.mockStatic(DatasourceConfiguration.class); MockedStatic envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class); propertyUtilMockedStatic.when(DatasourceConfiguration::isEmbeddedStorage).thenReturn(true); envUtilMockedStatic.when(EnvUtil::getStandaloneMode).thenReturn(true); - Assert.assertTrue(conditionStandaloneEmbedStorage.matches(context, metadata)); + assertTrue(conditionStandaloneEmbedStorage.matches(context, metadata)); propertyUtilMockedStatic.when(DatasourceConfiguration::isEmbeddedStorage).thenReturn(true); envUtilMockedStatic.when(EnvUtil::getStandaloneMode).thenReturn(false); - Assert.assertFalse(conditionStandaloneEmbedStorage.matches(context, metadata)); + assertFalse(conditionStandaloneEmbedStorage.matches(context, metadata)); propertyUtilMockedStatic.when(DatasourceConfiguration::isEmbeddedStorage).thenReturn(false); envUtilMockedStatic.when(EnvUtil::getStandaloneMode).thenReturn(true); - Assert.assertFalse(conditionStandaloneEmbedStorage.matches(context, metadata)); + assertFalse(conditionStandaloneEmbedStorage.matches(context, metadata)); propertyUtilMockedStatic.when(DatasourceConfiguration::isEmbeddedStorage).thenReturn(false); envUtilMockedStatic.when(EnvUtil::getStandaloneMode).thenReturn(false); - Assert.assertFalse(conditionStandaloneEmbedStorage.matches(context, metadata)); + assertFalse(conditionStandaloneEmbedStorage.matches(context, metadata)); propertyUtilMockedStatic.close(); envUtilMockedStatic.close(); diff --git a/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/ClusterExternalStorageTest.java b/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/ClusterExternalStorageTest.java index 439cf6042e0..be9b78a7177 100644 --- a/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/ClusterExternalStorageTest.java +++ b/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/ClusterExternalStorageTest.java @@ -20,27 +20,31 @@ import com.alibaba.nacos.persistence.constants.PersistenceConstant; import com.alibaba.nacos.sys.env.Constants; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.env.MockEnvironment; import org.springframework.test.util.ReflectionTestUtils; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * ClusterExternalStorage unit test. * * @author Long Yu * @since 2.2.0 */ -@RunWith(MockitoJUnitRunner.class) -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class ClusterExternalStorageTest { +@ExtendWith(MockitoExtension.class) +@TestMethodOrder(MethodName.class) +class ClusterExternalStorageTest { + + DatasourceConfiguration datasourceConfig; @InjectMocks private DynamicDataSource dataSource; @@ -53,10 +57,8 @@ public class ClusterExternalStorageTest { @Mock private ExternalDataSourceServiceImpl basicDataSourceService; - DatasourceConfiguration datasourceConfig; - - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { environment = new MockEnvironment(); EnvUtil.setEnvironment(environment); datasourceConfig = new DatasourceConfiguration(); @@ -67,7 +69,7 @@ public void setUp() throws Exception { } @Test - public void test005WithClusterAndNullDatabase() { + void test005WithClusterAndNullDatabase() { // 模拟设置环境05:指定集群,未指定数据库,UseExternalDB是true,数据库类型是"" System.setProperty(Constants.STANDALONE_MODE_PROPERTY_NAME, "false"); environment.setProperty(PersistenceConstant.DATASOURCE_PLATFORM_PROPERTY_OLD, ""); @@ -77,13 +79,13 @@ public void test005WithClusterAndNullDatabase() { // 模拟初始化 datasourceConfig.initialize(null); - Assert.assertFalse(EnvUtil.getStandaloneMode()); - Assert.assertTrue(DatasourceConfiguration.isUseExternalDB()); - Assert.assertTrue(dataSource.getDataSource() instanceof ExternalDataSourceServiceImpl); + assertFalse(EnvUtil.getStandaloneMode()); + assertTrue(DatasourceConfiguration.isUseExternalDB()); + assertTrue(dataSource.getDataSource() instanceof ExternalDataSourceServiceImpl); } @Test - public void test006WithClusterAndMysqlDatabase() { + void test006WithClusterAndMysqlDatabase() { // 模拟设置环境06:指定集群,指定数据库mysql,UseExternalDB是true,数据库类型是mysql System.setProperty(Constants.STANDALONE_MODE_PROPERTY_NAME, "false"); environment.setProperty(PersistenceConstant.DATASOURCE_PLATFORM_PROPERTY_OLD, "mysql"); @@ -93,13 +95,13 @@ public void test006WithClusterAndMysqlDatabase() { // 模拟初始化 datasourceConfig.initialize(null); - Assert.assertFalse(EnvUtil.getStandaloneMode()); - Assert.assertTrue(DatasourceConfiguration.isUseExternalDB()); - Assert.assertTrue(dataSource.getDataSource() instanceof ExternalDataSourceServiceImpl); + assertFalse(EnvUtil.getStandaloneMode()); + assertTrue(DatasourceConfiguration.isUseExternalDB()); + assertTrue(dataSource.getDataSource() instanceof ExternalDataSourceServiceImpl); } @Test - public void test007WithClusterAndDerbyDatabase() { + void test007WithClusterAndDerbyDatabase() { // 模拟设置环境07:指定集群,指定数据库derby,UseExternalDB是false,数据库类型是derby System.setProperty(Constants.STANDALONE_MODE_PROPERTY_NAME, "false"); environment.setProperty(PersistenceConstant.DATASOURCE_PLATFORM_PROPERTY_OLD, "derby"); @@ -109,13 +111,13 @@ public void test007WithClusterAndDerbyDatabase() { // 模拟初始化 datasourceConfig.initialize(null); - Assert.assertFalse(EnvUtil.getStandaloneMode()); - Assert.assertFalse(DatasourceConfiguration.isUseExternalDB()); - Assert.assertTrue(dataSource.getDataSource() instanceof LocalDataSourceServiceImpl); + assertFalse(EnvUtil.getStandaloneMode()); + assertFalse(DatasourceConfiguration.isUseExternalDB()); + assertTrue(dataSource.getDataSource() instanceof LocalDataSourceServiceImpl); } @Test - public void test008WithClusterAndOtherDatabase() { + void test008WithClusterAndOtherDatabase() { // 模拟设置环境08: 指定集群,指定数据库其他,UseExternalDB是true,数据库类型是其他 System.setProperty(Constants.STANDALONE_MODE_PROPERTY_NAME, "false"); environment.setProperty(PersistenceConstant.DATASOURCE_PLATFORM_PROPERTY_OLD, "postgresql"); @@ -125,9 +127,9 @@ public void test008WithClusterAndOtherDatabase() { // 模拟初始化 datasourceConfig.initialize(null); - Assert.assertFalse(EnvUtil.getStandaloneMode()); - Assert.assertTrue(DatasourceConfiguration.isUseExternalDB()); - Assert.assertTrue(dataSource.getDataSource() instanceof ExternalDataSourceServiceImpl); + assertFalse(EnvUtil.getStandaloneMode()); + assertTrue(DatasourceConfiguration.isUseExternalDB()); + assertTrue(dataSource.getDataSource() instanceof ExternalDataSourceServiceImpl); } } diff --git a/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/DataSourcePoolPropertiesTest.java b/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/DataSourcePoolPropertiesTest.java index 923f897888f..253e0de6862 100644 --- a/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/DataSourcePoolPropertiesTest.java +++ b/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/DataSourcePoolPropertiesTest.java @@ -17,13 +17,13 @@ package com.alibaba.nacos.persistence.datasource; import com.zaxxer.hikari.HikariDataSource; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.mock.env.MockEnvironment; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class DataSourcePoolPropertiesTest { +class DataSourcePoolPropertiesTest { private static final String JDBC_URL = "jdbc:derby://127.0.0.1:3306/nacos_devtest?characterEncoding=utf8&serverTimezone=UTC"; @@ -39,8 +39,8 @@ public class DataSourcePoolPropertiesTest { private MockEnvironment environment; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { environment = new MockEnvironment(); environment.setProperty("db.user", USERNAME); environment.setProperty("db.password", PASSWORD); @@ -49,7 +49,7 @@ public void setUp() throws Exception { } @Test - public void testBuild() { + void testBuild() { DataSourcePoolProperties poolProperties = DataSourcePoolProperties.build(environment); poolProperties.setJdbcUrl(JDBC_URL); poolProperties.setDriverClassName(JDBC_DRIVER_CLASS_NAME); diff --git a/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/DynamicDataSourceTest.java b/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/DynamicDataSourceTest.java index b9e3a1acc3a..6bf4c37c669 100644 --- a/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/DynamicDataSourceTest.java +++ b/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/DynamicDataSourceTest.java @@ -17,17 +17,18 @@ package com.alibaba.nacos.persistence.datasource; import com.alibaba.nacos.persistence.configuration.DatasourceConfiguration; -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.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.util.ReflectionTestUtils; -@RunWith(MockitoJUnitRunner.class) -public class DynamicDataSourceTest { +import static org.junit.jupiter.api.Assertions.assertTrue; + +@ExtendWith(MockitoExtension.class) +class DynamicDataSourceTest { @InjectMocks private DynamicDataSource dataSource; @@ -38,20 +39,20 @@ public class DynamicDataSourceTest { @Mock private ExternalDataSourceServiceImpl basicDataSourceService; - @Before - public void setUp() { + @BeforeEach + void setUp() { dataSource = DynamicDataSource.getInstance(); ReflectionTestUtils.setField(dataSource, "localDataSourceService", localDataSourceService); ReflectionTestUtils.setField(dataSource, "basicDataSourceService", basicDataSourceService); } @Test - public void testGetDataSource() { + void testGetDataSource() { DatasourceConfiguration.setEmbeddedStorage(true); - Assert.assertTrue(dataSource.getDataSource() instanceof LocalDataSourceServiceImpl); + assertTrue(dataSource.getDataSource() instanceof LocalDataSourceServiceImpl); DatasourceConfiguration.setEmbeddedStorage(false); - Assert.assertTrue(dataSource.getDataSource() instanceof ExternalDataSourceServiceImpl); + assertTrue(dataSource.getDataSource() instanceof ExternalDataSourceServiceImpl); } } diff --git a/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/ExternalDataSourcePropertiesTest.java b/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/ExternalDataSourcePropertiesTest.java index f9e51274288..9680b8f508f 100644 --- a/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/ExternalDataSourcePropertiesTest.java +++ b/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/ExternalDataSourcePropertiesTest.java @@ -17,12 +17,14 @@ package com.alibaba.nacos.persistence.datasource; import com.zaxxer.hikari.HikariDataSource; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.mock.env.MockEnvironment; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + public class ExternalDataSourcePropertiesTest { @SuppressWarnings("checkstyle:linelength") @@ -33,7 +35,7 @@ public class ExternalDataSourcePropertiesTest { public static final String USERNAME = "nacos_devtest"; @Test - public void externalDatasourceNormally() { + void externalDatasourceNormally() { HikariDataSource expectedDataSource = new HikariDataSource(); expectedDataSource.setJdbcUrl(JDBC_URL); expectedDataSource.setUsername(USERNAME); @@ -44,16 +46,16 @@ public void externalDatasourceNormally() { environment.setProperty("db.password", PASSWORD); environment.setProperty("db.url.0", JDBC_URL); List dataSources = new ExternalDataSourceProperties().build(environment, (dataSource -> { - Assert.assertEquals(dataSource.getJdbcUrl(), expectedDataSource.getJdbcUrl()); - Assert.assertEquals(dataSource.getUsername(), expectedDataSource.getUsername()); - Assert.assertEquals(dataSource.getPassword(), expectedDataSource.getPassword()); + assertEquals(dataSource.getJdbcUrl(), expectedDataSource.getJdbcUrl()); + assertEquals(dataSource.getUsername(), expectedDataSource.getUsername()); + assertEquals(dataSource.getPassword(), expectedDataSource.getPassword()); })); - Assert.assertEquals(dataSources.size(), 1); + assertEquals(1, dataSources.size()); } @Test - public void externalDatasourceToAssertMultiJdbcUrl() { + void externalDatasourceToAssertMultiJdbcUrl() { HikariDataSource expectedDataSource = new HikariDataSource(); expectedDataSource.setJdbcUrl(JDBC_URL); @@ -66,16 +68,16 @@ public void externalDatasourceToAssertMultiJdbcUrl() { environment.setProperty("db.url.0", JDBC_URL); environment.setProperty("db.url.1", JDBC_URL); List dataSources = new ExternalDataSourceProperties().build(environment, (dataSource -> { - Assert.assertEquals(dataSource.getJdbcUrl(), expectedDataSource.getJdbcUrl()); - Assert.assertEquals(dataSource.getUsername(), expectedDataSource.getUsername()); - Assert.assertEquals(dataSource.getPassword(), expectedDataSource.getPassword()); + assertEquals(dataSource.getJdbcUrl(), expectedDataSource.getJdbcUrl()); + assertEquals(dataSource.getUsername(), expectedDataSource.getUsername()); + assertEquals(dataSource.getPassword(), expectedDataSource.getPassword()); })); - Assert.assertEquals(dataSources.size(), 2); + assertEquals(2, dataSources.size()); } @Test - public void externalDatasourceToAssertMultiPasswordAndUsername() { + void externalDatasourceToAssertMultiPasswordAndUsername() { HikariDataSource expectedDataSource = new HikariDataSource(); expectedDataSource.setJdbcUrl(JDBC_URL); @@ -90,16 +92,16 @@ public void externalDatasourceToAssertMultiPasswordAndUsername() { environment.setProperty("db.url.0", JDBC_URL); environment.setProperty("db.url.1", JDBC_URL); List dataSources = new ExternalDataSourceProperties().build(environment, (dataSource -> { - Assert.assertEquals(dataSource.getJdbcUrl(), expectedDataSource.getJdbcUrl()); - Assert.assertEquals(dataSource.getUsername(), expectedDataSource.getUsername()); - Assert.assertEquals(dataSource.getPassword(), expectedDataSource.getPassword()); + assertEquals(dataSource.getJdbcUrl(), expectedDataSource.getJdbcUrl()); + assertEquals(dataSource.getUsername(), expectedDataSource.getUsername()); + assertEquals(dataSource.getPassword(), expectedDataSource.getPassword()); })); - Assert.assertEquals(dataSources.size(), 2); + assertEquals(2, dataSources.size()); } @Test - public void externalDatasourceToAssertMinIdle() { + void externalDatasourceToAssertMinIdle() { MockEnvironment environment = new MockEnvironment(); environment.setProperty("db.num", "1"); environment.setProperty("db.user", USERNAME); @@ -107,38 +109,43 @@ public void externalDatasourceToAssertMinIdle() { environment.setProperty("db.url.0", JDBC_URL); List dataSources = new ExternalDataSourceProperties().build(environment, (dataSource -> { dataSource.validate(); - Assert.assertEquals(dataSource.getMinimumIdle(), DataSourcePoolProperties.DEFAULT_MINIMUM_IDLE); + assertEquals(DataSourcePoolProperties.DEFAULT_MINIMUM_IDLE, dataSource.getMinimumIdle()); })); - Assert.assertEquals(dataSources.size(), 1); + assertEquals(1, dataSources.size()); } - @Test(expected = IllegalArgumentException.class) - public void externalDatasourceFailureWithLarkInfo() { - - MockEnvironment environment = new MockEnvironment(); - new ExternalDataSourceProperties().build(environment, null); + @Test + void externalDatasourceFailureWithLarkInfo() { + assertThrows(IllegalArgumentException.class, () -> { + + MockEnvironment environment = new MockEnvironment(); + new ExternalDataSourceProperties().build(environment, null); + + }); } - @Test(expected = IllegalArgumentException.class) - public void externalDatasourceFailureWithErrorInfo() { - - HikariDataSource expectedDataSource = new HikariDataSource(); - expectedDataSource.setJdbcUrl(JDBC_URL); - expectedDataSource.setUsername(USERNAME); - expectedDataSource.setPassword(PASSWORD); - MockEnvironment environment = new MockEnvironment(); - // error num of db - environment.setProperty("db.num", "2"); - environment.setProperty("db.user", USERNAME); - environment.setProperty("db.password", PASSWORD); - environment.setProperty("db.url.0", JDBC_URL); - List dataSources = new ExternalDataSourceProperties().build(environment, (dataSource -> { - Assert.assertEquals(dataSource.getJdbcUrl(), expectedDataSource.getJdbcUrl()); - Assert.assertEquals(dataSource.getUsername(), expectedDataSource.getUsername()); - Assert.assertEquals(dataSource.getPassword(), expectedDataSource.getPassword()); + @Test + void externalDatasourceFailureWithErrorInfo() { + assertThrows(IllegalArgumentException.class, () -> { - })); + HikariDataSource expectedDataSource = new HikariDataSource(); + expectedDataSource.setJdbcUrl(JDBC_URL); + expectedDataSource.setUsername(USERNAME); + expectedDataSource.setPassword(PASSWORD); + MockEnvironment environment = new MockEnvironment(); + // error num of db + environment.setProperty("db.num", "2"); + environment.setProperty("db.user", USERNAME); + environment.setProperty("db.password", PASSWORD); + environment.setProperty("db.url.0", JDBC_URL); + List dataSources = new ExternalDataSourceProperties().build(environment, (dataSource -> { + assertEquals(dataSource.getJdbcUrl(), expectedDataSource.getJdbcUrl()); + assertEquals(dataSource.getUsername(), expectedDataSource.getUsername()); + assertEquals(dataSource.getPassword(), expectedDataSource.getPassword()); + + })); + }); } } diff --git a/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/ExternalDataSourceServiceImplTest.java b/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/ExternalDataSourceServiceImplTest.java index 1781a6cacaa..5c41a0ca991 100644 --- a/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/ExternalDataSourceServiceImplTest.java +++ b/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/ExternalDataSourceServiceImplTest.java @@ -17,13 +17,12 @@ package com.alibaba.nacos.persistence.datasource; import com.zaxxer.hikari.HikariDataSource; -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.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.UncategorizedSQLException; import org.springframework.jdbc.core.JdbcTemplate; @@ -35,12 +34,15 @@ import java.util.ArrayList; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class ExternalDataSourceServiceImplTest { +@ExtendWith(MockitoExtension.class) +class ExternalDataSourceServiceImplTest { @InjectMocks private ExternalDataSourceServiceImpl service; @@ -60,8 +62,8 @@ public class ExternalDataSourceServiceImplTest { @Mock private JdbcTemplate testMasterWritableJT; - @Before - public void setUp() { + @BeforeEach + void setUp() { service = new ExternalDataSourceServiceImpl(); ReflectionTestUtils.setField(service, "jt", jt); ReflectionTestUtils.setField(service, "tm", tm); @@ -74,32 +76,32 @@ public void setUp() { } @Test - public void testCheckMasterWritable() { + void testCheckMasterWritable() { when(testMasterWritableJT.queryForObject(eq(" SELECT @@read_only "), eq(Integer.class))).thenReturn(0); - Assert.assertTrue(service.checkMasterWritable()); + assertTrue(service.checkMasterWritable()); } @Test - public void testGetCurrentDbUrl() { + void testGetCurrentDbUrl() { HikariDataSource bds = new HikariDataSource(); bds.setJdbcUrl("test.jdbc.url"); when(jt.getDataSource()).thenReturn(bds); - Assert.assertEquals("test.jdbc.url", service.getCurrentDbUrl()); + assertEquals("test.jdbc.url", service.getCurrentDbUrl()); } @Test - public void testGetHealth() { + void testGetHealth() { List isHealthList = new ArrayList<>(); ReflectionTestUtils.setField(service, "isHealthList", isHealthList); - Assert.assertEquals("UP", service.getHealth()); + assertEquals("UP", service.getHealth()); } @Test - public void testCheckDbHealthTaskRun() { + void testCheckDbHealthTaskRun() { List testJtList = new ArrayList<>(); testJtList.add(jt); @@ -110,12 +112,12 @@ public void testCheckDbHealthTaskRun() { ReflectionTestUtils.setField(service, "isHealthList", isHealthList); service.new CheckDbHealthTask().run(); - Assert.assertEquals(1, isHealthList.size()); - Assert.assertTrue(isHealthList.get(0)); + assertEquals(1, isHealthList.size()); + assertTrue(isHealthList.get(0)); } @Test - public void testCheckDbHealthTaskRunWhenEmptyResult() { + void testCheckDbHealthTaskRunWhenEmptyResult() { List testJtList = new ArrayList<>(); testJtList.add(jt); ReflectionTestUtils.setField(service, "testJtList", testJtList); @@ -126,12 +128,12 @@ public void testCheckDbHealthTaskRunWhenEmptyResult() { when(jt.queryForMap(anyString())).thenThrow(new EmptyResultDataAccessException("Expected exception", 1)); service.new CheckDbHealthTask().run(); - Assert.assertEquals(1, isHealthList.size()); - Assert.assertTrue(isHealthList.get(0)); + assertEquals(1, isHealthList.size()); + assertTrue(isHealthList.get(0)); } @Test - public void testCheckDbHealthTaskRunWhenSqlException() { + void testCheckDbHealthTaskRunWhenSqlException() { List testJtList = new ArrayList<>(); testJtList.add(jt); ReflectionTestUtils.setField(service, "testJtList", testJtList); @@ -140,11 +142,10 @@ public void testCheckDbHealthTaskRunWhenSqlException() { isHealthList.add(Boolean.FALSE); ReflectionTestUtils.setField(service, "isHealthList", isHealthList); - when(jt.queryForMap(anyString())).thenThrow( - new UncategorizedSQLException("Expected exception", "", new SQLException())); + when(jt.queryForMap(anyString())).thenThrow(new UncategorizedSQLException("Expected exception", "", new SQLException())); service.new CheckDbHealthTask().run(); - Assert.assertEquals(1, isHealthList.size()); - Assert.assertFalse(isHealthList.get(0)); + assertEquals(1, isHealthList.size()); + assertFalse(isHealthList.get(0)); } } diff --git a/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/LocalDataSourceServiceImplTest.java b/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/LocalDataSourceServiceImplTest.java index 123d7b33aa1..dd8dd298fc4 100644 --- a/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/LocalDataSourceServiceImplTest.java +++ b/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/LocalDataSourceServiceImplTest.java @@ -17,21 +17,22 @@ package com.alibaba.nacos.persistence.datasource; import com.zaxxer.hikari.HikariDataSource; -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.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.transaction.support.TransactionTemplate; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class LocalDataSourceServiceImplTest { +@ExtendWith(MockitoExtension.class) +class LocalDataSourceServiceImplTest { @InjectMocks private LocalDataSourceServiceImpl service; @@ -42,35 +43,35 @@ public class LocalDataSourceServiceImplTest { @Mock private TransactionTemplate tjt; - @Before - public void setUp() { + @BeforeEach + void setUp() { service = new LocalDataSourceServiceImpl(); ReflectionTestUtils.setField(service, "jt", jt); ReflectionTestUtils.setField(service, "tjt", tjt); } @Test - public void testGetDataSource() { + void testGetDataSource() { HikariDataSource dataSource = new HikariDataSource(); dataSource.setJdbcUrl("test.jdbc.url"); when(jt.getDataSource()).thenReturn(dataSource); - Assert.assertEquals(dataSource.getJdbcUrl(), ((HikariDataSource) service.getDatasource()).getJdbcUrl()); + assertEquals(dataSource.getJdbcUrl(), ((HikariDataSource) service.getDatasource()).getJdbcUrl()); } @Test - public void testCheckMasterWritable() { + void testCheckMasterWritable() { - Assert.assertTrue(service.checkMasterWritable()); + assertTrue(service.checkMasterWritable()); } @Test - public void testSetAndGetHealth() { + void testSetAndGetHealth() { service.setHealthStatus("DOWN"); - Assert.assertEquals("DOWN", service.getHealth()); + assertEquals("DOWN", service.getHealth()); service.setHealthStatus("UP"); - Assert.assertEquals("UP", service.getHealth()); + assertEquals("UP", service.getHealth()); } } diff --git a/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/StandaloneExternalStorageTest.java b/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/StandaloneExternalStorageTest.java index e8240c4b821..c3d03144c2f 100644 --- a/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/StandaloneExternalStorageTest.java +++ b/persistence/src/test/java/com/alibaba/nacos/persistence/datasource/StandaloneExternalStorageTest.java @@ -20,27 +20,31 @@ import com.alibaba.nacos.persistence.constants.PersistenceConstant; import com.alibaba.nacos.sys.env.Constants; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.env.MockEnvironment; import org.springframework.test.util.ReflectionTestUtils; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * StandaloneExternalStorage unit test. * * @author Long Yu * @since 2.2.0 */ -@RunWith(MockitoJUnitRunner.class) -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class StandaloneExternalStorageTest { +@ExtendWith(MockitoExtension.class) +@TestMethodOrder(MethodName.class) +class StandaloneExternalStorageTest { + + DatasourceConfiguration datasourceConfig; @InjectMocks private DynamicDataSource dataSource; @@ -53,10 +57,8 @@ public class StandaloneExternalStorageTest { @Mock private ExternalDataSourceServiceImpl basicDataSourceService; - DatasourceConfiguration datasourceConfig; - - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { environment = new MockEnvironment(); EnvUtil.setEnvironment(environment); datasourceConfig = new DatasourceConfiguration(); @@ -66,7 +68,7 @@ public void setUp() throws Exception { } @Test - public void test001WithStandaloneAndNullDatabase() { + void test001WithStandaloneAndNullDatabase() { // 模拟设置环境01:指定单例,未指定数据库,UseExternalDB是false System.setProperty(Constants.STANDALONE_MODE_PROPERTY_NAME, "true"); environment.setProperty(PersistenceConstant.DATASOURCE_PLATFORM_PROPERTY_OLD, ""); @@ -76,13 +78,13 @@ public void test001WithStandaloneAndNullDatabase() { // 模拟初始化 datasourceConfig.initialize(null); - Assert.assertTrue(EnvUtil.getStandaloneMode()); - Assert.assertTrue(dataSource.getDataSource() instanceof LocalDataSourceServiceImpl); - Assert.assertFalse(DatasourceConfiguration.isUseExternalDB()); + assertTrue(EnvUtil.getStandaloneMode()); + assertTrue(dataSource.getDataSource() instanceof LocalDataSourceServiceImpl); + assertFalse(DatasourceConfiguration.isUseExternalDB()); } @Test - public void test002WithStandaloneAndDerbyDatabase() { + void test002WithStandaloneAndDerbyDatabase() { // 模拟设置环境02:指定单例,指定数据库derby,UseExternalDB是false System.setProperty(Constants.STANDALONE_MODE_PROPERTY_NAME, "true"); environment.setProperty(PersistenceConstant.DATASOURCE_PLATFORM_PROPERTY_OLD, "derby"); @@ -92,13 +94,13 @@ public void test002WithStandaloneAndDerbyDatabase() { datasourceConfig.initialize(null); - Assert.assertTrue(EnvUtil.getStandaloneMode()); - Assert.assertTrue(dataSource.getDataSource() instanceof LocalDataSourceServiceImpl); - Assert.assertFalse(DatasourceConfiguration.isUseExternalDB()); + assertTrue(EnvUtil.getStandaloneMode()); + assertTrue(dataSource.getDataSource() instanceof LocalDataSourceServiceImpl); + assertFalse(DatasourceConfiguration.isUseExternalDB()); } @Test - public void test003WithStandaloneAndMysqlDatabase() { + void test003WithStandaloneAndMysqlDatabase() { // 模拟设置环境03:指定单例,指定数据库为mysql, UseExternalDB是true System.setProperty(Constants.STANDALONE_MODE_PROPERTY_NAME, "true"); environment.setProperty(PersistenceConstant.DATASOURCE_PLATFORM_PROPERTY_OLD, "mysql"); @@ -108,13 +110,13 @@ public void test003WithStandaloneAndMysqlDatabase() { datasourceConfig.initialize(null); - Assert.assertTrue(EnvUtil.getStandaloneMode()); - Assert.assertTrue(dataSource.getDataSource() instanceof ExternalDataSourceServiceImpl); - Assert.assertTrue(DatasourceConfiguration.isUseExternalDB()); + assertTrue(EnvUtil.getStandaloneMode()); + assertTrue(dataSource.getDataSource() instanceof ExternalDataSourceServiceImpl); + assertTrue(DatasourceConfiguration.isUseExternalDB()); } @Test - public void test004WithStandaloneAndOtherDatabase() { + void test004WithStandaloneAndOtherDatabase() { // 模拟设置环境04:指定单例,指定数据库为其他, UseExternalDB是true System.setProperty(Constants.STANDALONE_MODE_PROPERTY_NAME, "true"); environment.setProperty(PersistenceConstant.DATASOURCE_PLATFORM_PROPERTY_OLD, "postgresql"); @@ -124,9 +126,9 @@ public void test004WithStandaloneAndOtherDatabase() { datasourceConfig.initialize(null); - Assert.assertTrue(EnvUtil.getStandaloneMode()); - Assert.assertTrue(dataSource.getDataSource() instanceof ExternalDataSourceServiceImpl); - Assert.assertTrue(DatasourceConfiguration.isUseExternalDB()); + assertTrue(EnvUtil.getStandaloneMode()); + assertTrue(dataSource.getDataSource() instanceof ExternalDataSourceServiceImpl); + assertTrue(DatasourceConfiguration.isUseExternalDB()); } } diff --git a/persistence/src/test/java/com/alibaba/nacos/persistence/repository/embedded/operate/MockConfigInfo.java b/persistence/src/test/java/com/alibaba/nacos/persistence/repository/embedded/operate/MockConfigInfo.java index 56c6a70a3a0..0247ae5a9f2 100644 --- a/persistence/src/test/java/com/alibaba/nacos/persistence/repository/embedded/operate/MockConfigInfo.java +++ b/persistence/src/test/java/com/alibaba/nacos/persistence/repository/embedded/operate/MockConfigInfo.java @@ -69,8 +69,8 @@ public boolean equals(Object o) { return false; } MockConfigInfo that = (MockConfigInfo) o; - return id == that.id && Objects.equals(dataId, that.dataId) && Objects.equals(group, that.group) && Objects - .equals(content, that.content); + return id == that.id && Objects.equals(dataId, that.dataId) && Objects.equals(group, that.group) && Objects.equals(content, + that.content); } @Override diff --git a/persistence/src/test/java/com/alibaba/nacos/persistence/repository/embedded/operate/StandaloneDatabaseOperateImplTest.java b/persistence/src/test/java/com/alibaba/nacos/persistence/repository/embedded/operate/StandaloneDatabaseOperateImplTest.java index 5bfefbae1f3..6f10f72518f 100644 --- a/persistence/src/test/java/com/alibaba/nacos/persistence/repository/embedded/operate/StandaloneDatabaseOperateImplTest.java +++ b/persistence/src/test/java/com/alibaba/nacos/persistence/repository/embedded/operate/StandaloneDatabaseOperateImplTest.java @@ -19,16 +19,19 @@ import com.alibaba.nacos.common.model.RestResult; import com.alibaba.nacos.persistence.repository.embedded.EmbeddedStorageContextHolder; import com.alibaba.nacos.persistence.repository.embedded.sql.ModifyRequest; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import com.alibaba.nacos.sys.env.EnvUtil; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; +import org.springframework.mock.env.MockEnvironment; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; @@ -41,14 +44,16 @@ import java.util.concurrent.ExecutionException; import java.util.function.BiConsumer; +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; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class StandaloneDatabaseOperateImplTest { +@ExtendWith(MockitoExtension.class) +class StandaloneDatabaseOperateImplTest { @Spy @InjectMocks @@ -72,24 +77,35 @@ public class StandaloneDatabaseOperateImplTest { @Mock private TransactionTemplate transactionTemplate; - @Before - public void setUp() { + @BeforeAll + static void beforeAll() { + MockEnvironment environment = new MockEnvironment(); + environment.setProperty("nacos.persistence.sql.derby.limit.enabled", "false"); + EnvUtil.setEnvironment(environment); + } + + @BeforeEach + void setUp() { ReflectionTestUtils.setField(operate, "jdbcTemplate", jdbcTemplate); ReflectionTestUtils.setField(operate, "transactionTemplate", transactionTemplate); - + } + + @AfterAll + static void afterAll() { + EnvUtil.setEnvironment(null); } @Test - public void testQueryOne1() { + void testQueryOne1() { String sql = "SELECT 1"; Class clazz = Long.class; Long num = 1L; when(jdbcTemplate.queryForObject(sql, clazz)).thenReturn(num); - Assert.assertEquals(operate.queryOne(sql, clazz), (Long) 1L); + assertEquals(operate.queryOne(sql, clazz), (Long) 1L); } @Test - public void testQueryOne2() { + void testQueryOne2() { final String sql = "SELECT * FROM config_info WHERE id = ? AND data_id = ? AND group_id = ?"; MockConfigInfo configInfo = new MockConfigInfo(); configInfo.setId(1L); @@ -97,11 +113,11 @@ public void testQueryOne2() { configInfo.setGroup("test"); Object[] args = new Object[] {configInfo.getId(), configInfo.getDataId(), configInfo.getGroup()}; when(jdbcTemplate.queryForObject(sql, args, MockConfigInfo.class)).thenReturn(configInfo); - Assert.assertEquals(operate.queryOne(sql, args, MockConfigInfo.class), configInfo); + assertEquals(operate.queryOne(sql, args, MockConfigInfo.class), configInfo); } @Test - public void testQueryOne3() { + void testQueryOne3() { final String sql = "SELECT * FROM config_info WHERE id = ? AND data_id = ? AND group_id = ?"; MockConfigInfo configInfo = new MockConfigInfo(); configInfo.setId(1L); @@ -109,20 +125,20 @@ public void testQueryOne3() { configInfo.setGroup("test"); Object[] args = new Object[] {configInfo.getId(), configInfo.getDataId(), configInfo.getGroup()}; when(jdbcTemplate.queryForObject(eq(sql), eq(args), any(RowMapper.class))).thenReturn(configInfo); - Assert.assertEquals(operate.queryOne(sql, args, rowMapper), configInfo); + assertEquals(operate.queryOne(sql, args, rowMapper), configInfo); } @Test - public void testQueryOne4() { + void testQueryOne4() { String sql = "SELECT 1"; Class clazz = Long.class; Long result = 1L; when(tempJdbcTemplate.queryForObject(sql, clazz)).thenReturn(result); - Assert.assertEquals(operate.queryOne(tempJdbcTemplate, sql, clazz), result); + assertEquals(operate.queryOne(tempJdbcTemplate, sql, clazz), result); } @Test - public void testQueryOne5() { + void testQueryOne5() { final String sql = "SELECT * FROM config_info WHERE id = ? AND data_id = ? AND group_id = ?"; MockConfigInfo configInfo = new MockConfigInfo(); configInfo.setId(1L); @@ -130,11 +146,11 @@ public void testQueryOne5() { configInfo.setGroup("test"); Object[] args = new Object[] {configInfo.getId(), configInfo.getDataId(), configInfo.getGroup()}; when(tempJdbcTemplate.queryForObject(sql, args, MockConfigInfo.class)).thenReturn(configInfo); - Assert.assertEquals(operate.queryOne(tempJdbcTemplate, sql, args, MockConfigInfo.class), configInfo); + assertEquals(operate.queryOne(tempJdbcTemplate, sql, args, MockConfigInfo.class), configInfo); } @Test - public void testQueryOne6() { + void testQueryOne6() { final String sql = "SELECT * FROM config_info WHERE id = ? AND data_id = ? AND group_id = ?"; MockConfigInfo configInfo = new MockConfigInfo(); configInfo.setId(1L); @@ -142,11 +158,11 @@ public void testQueryOne6() { configInfo.setGroup("test"); Object[] args = new Object[] {configInfo.getId(), configInfo.getDataId(), configInfo.getGroup()}; when(tempJdbcTemplate.queryForObject(eq(sql), eq(args), any(RowMapper.class))).thenReturn(configInfo); - Assert.assertEquals(operate.queryOne(tempJdbcTemplate, sql, args, rowMapper), configInfo); + assertEquals(operate.queryOne(tempJdbcTemplate, sql, args, rowMapper), configInfo); } @Test - public void testQueryMany1() { + void testQueryMany1() { final String sql = "SELECT * FROM config_info WHERE id >= ? AND id <= ?"; final Object[] args = new Object[] {1, 2}; MockConfigInfo configInfo1 = new MockConfigInfo(); @@ -157,11 +173,11 @@ public void testQueryMany1() { configInfos.add(configInfo1); configInfos.add(configInfo2); when(jdbcTemplate.query(eq(sql), eq(args), any(RowMapper.class))).thenReturn(configInfos); - Assert.assertEquals(configInfos, operate.queryMany(sql, args, rowMapper)); + assertEquals(configInfos, operate.queryMany(sql, args, rowMapper)); } @Test - public void testQueryMany2() { + void testQueryMany2() { final String sql = "SELECT id, data_id, group_id FROM config_info WHERE id >= ? AND id <= ?"; final Object[] args = new Object[] {1, 2}; @@ -180,11 +196,11 @@ public void testQueryMany2() { resultList.add(map2); when(jdbcTemplate.queryForList(sql, args)).thenReturn(resultList); - Assert.assertEquals(operate.queryMany(sql, args), resultList); + assertEquals(operate.queryMany(sql, args), resultList); } @Test - public void testQueryMany3() { + void testQueryMany3() { String sql = "SELECT data_id FROM config_info WHERE id >= ? AND id <= ?"; Object[] args = new Object[] {1, 2}; String dataId1 = "test1"; @@ -194,11 +210,11 @@ public void testQueryMany3() { resultList.add(dataId2); Class clazz = dataId1.getClass(); when(jdbcTemplate.queryForList(sql, args, clazz)).thenReturn(resultList); - Assert.assertEquals(operate.queryMany(sql, args, clazz), resultList); + assertEquals(operate.queryMany(sql, args, clazz), resultList); } @Test - public void testQueryMany4() { + void testQueryMany4() { final String sql = "SELECT data_id FROM config_info WHERE id >= ? AND id <= ?"; final Object[] args = new Object[] {1, 2}; final List> resultList = new ArrayList<>(); @@ -216,11 +232,11 @@ public void testQueryMany4() { resultList.add(map2); when(tempJdbcTemplate.queryForList(sql, args)).thenReturn(resultList); - Assert.assertEquals(operate.queryMany(tempJdbcTemplate, sql, args), resultList); + assertEquals(operate.queryMany(tempJdbcTemplate, sql, args), resultList); } @Test - public void testQueryMany5() { + void testQueryMany5() { String sql = "SELECT data_id FROM config_info WHERE id >= ? AND id <= ?"; Object[] args = new Object[] {1, 2}; String dataId1 = "test1"; @@ -230,11 +246,11 @@ public void testQueryMany5() { resultList.add(dataId2); Class clazz = dataId1.getClass(); when(operate.queryMany(jdbcTemplate, sql, args, clazz)).thenReturn(resultList); - Assert.assertEquals(operate.queryMany(jdbcTemplate, sql, args, clazz), resultList); + assertEquals(operate.queryMany(jdbcTemplate, sql, args, clazz), resultList); } @Test - public void testQueryMany6() { + void testQueryMany6() { final String sql = "SELECT * FROM config_info WHERE id >= ? AND id <= ?"; final Object[] args = new Object[] {1, 2}; MockConfigInfo configInfo1 = new MockConfigInfo(); @@ -245,21 +261,20 @@ public void testQueryMany6() { configInfos.add(configInfo1); configInfos.add(configInfo2); when(tempJdbcTemplate.query(eq(sql), eq(args), any(RowMapper.class))).thenReturn(configInfos); - Assert.assertEquals(operate.queryMany(tempJdbcTemplate, sql, args, rowMapper), configInfos); + assertEquals(operate.queryMany(tempJdbcTemplate, sql, args, rowMapper), configInfos); } @Test - public void testDataImport() throws ExecutionException, InterruptedException { - RestResult errorResult = RestResult.builder().withCode(500).withMsg("null").withData(null) - .build(); + void testDataImport() throws ExecutionException, InterruptedException { + RestResult errorResult = RestResult.builder().withCode(500).withMsg("null").withData(null).build(); CompletableFuture> errorFuture = new CompletableFuture<>(); errorFuture.complete(errorResult); doReturn(errorFuture).when(operate).dataImport(null); - Assert.assertEquals(operate.dataImport(null).get(), errorResult); + assertEquals(operate.dataImport(null).get(), errorResult); } @Test - public void testUpdate1() { + void testUpdate1() { List modifyRequests = new ArrayList<>(); ModifyRequest modifyRequest1 = new ModifyRequest(); String sql = "UPDATE config_info SET data_id = 'test' WHERE id = ?;"; @@ -268,11 +283,11 @@ public void testUpdate1() { modifyRequest1.setArgs(args); modifyRequests.add(modifyRequest1); when(transactionTemplate.execute(any(TransactionCallback.class))).thenReturn(true); - Assert.assertTrue(operate.update(modifyRequests)); + assertTrue(operate.update(modifyRequests)); } @Test - public void testUpdate2() { + void testUpdate2() { List modifyRequests = new ArrayList<>(); ModifyRequest modifyRequest1 = new ModifyRequest(); String sql = "UPDATE config_info SET data_id = 'test' WHERE id = ?;"; @@ -281,11 +296,11 @@ public void testUpdate2() { modifyRequest1.setArgs(args); modifyRequests.add(modifyRequest1); when(transactionTemplate.execute(any(TransactionCallback.class))).thenReturn(true); - Assert.assertTrue(operate.update(modifyRequests, biConsumer)); + assertTrue(operate.update(modifyRequests, biConsumer)); } @Test - public void testUpdate3() { + void testUpdate3() { List modifyRequests = new ArrayList<>(); ModifyRequest modifyRequest1 = new ModifyRequest(); String sql = "UPDATE config_info SET data_id = 'test' WHERE id = ?;"; @@ -294,11 +309,11 @@ public void testUpdate3() { modifyRequest1.setArgs(args); modifyRequests.add(modifyRequest1); when(transactionTemplate.execute(any(TransactionCallback.class))).thenReturn(true); - Assert.assertTrue(operate.update(transactionTemplate, jdbcTemplate, modifyRequests)); + assertTrue(operate.update(transactionTemplate, jdbcTemplate, modifyRequests)); } @Test - public void testUpdate4() { + void testUpdate4() { List modifyRequests = new ArrayList<>(); ModifyRequest modifyRequest1 = new ModifyRequest(); String sql = "UPDATE config_info SET data_id = 'test' WHERE id = ?;"; @@ -307,27 +322,27 @@ public void testUpdate4() { modifyRequest1.setArgs(args); modifyRequests.add(modifyRequest1); when(transactionTemplate.execute(any(TransactionCallback.class))).thenReturn(true); - Assert.assertTrue(operate.update(transactionTemplate, jdbcTemplate, modifyRequests, biConsumer)); + assertTrue(operate.update(transactionTemplate, jdbcTemplate, modifyRequests, biConsumer)); } @Test - public void testBlockUpdate1() { + void testBlockUpdate1() { String sql = "UPDATE config_info SET data_id = 'test' WHERE id = 1;"; EmbeddedStorageContextHolder.addSqlContext(sql); when(transactionTemplate.execute(any(TransactionCallback.class))).thenReturn(true); - Assert.assertTrue(operate.blockUpdate()); + assertTrue(operate.blockUpdate()); } @Test - public void testBlockUpdate2() { + void testBlockUpdate2() { String sql = "UPDATE config_info SET data_id = 'test' WHERE id = 1;"; EmbeddedStorageContextHolder.addSqlContext(sql); when(transactionTemplate.execute(any(TransactionCallback.class))).thenReturn(true); - Assert.assertTrue(operate.blockUpdate(biConsumer)); + assertTrue(operate.blockUpdate(biConsumer)); } @Test - public void testDoDataImport() { + void testDoDataImport() { List modifyRequests = new ArrayList<>(); ModifyRequest modifyRequest1 = new ModifyRequest(); String sql = "UPDATE config_info SET data_id = 'test' WHERE id = ?;"; @@ -336,17 +351,17 @@ public void testDoDataImport() { modifyRequest1.setArgs(args); modifyRequests.add(modifyRequest1); when(tempJdbcTemplate.batchUpdate(sql)).thenReturn(new int[] {1}); - Assert.assertTrue(operate.doDataImport(tempJdbcTemplate, modifyRequests)); + assertTrue(operate.doDataImport(tempJdbcTemplate, modifyRequests)); } @Test - public void testFutureUpdate() throws ExecutionException, InterruptedException { + void testFutureUpdate() throws ExecutionException, InterruptedException { String sql = "SELECT 1"; EmbeddedStorageContextHolder.addSqlContext(sql); CompletableFuture future = new CompletableFuture<>(); future.complete(true); doAnswer((invocationOnMock) -> null).when(operate).futureUpdate(); when(operate.futureUpdate()).thenReturn(future); - Assert.assertTrue(operate.futureUpdate().get()); + assertTrue(operate.futureUpdate().get()); } } \ No newline at end of file diff --git a/persistence/src/test/java/com/alibaba/nacos/persistence/repository/embedded/sql/limiter/SqlTypeLimiterTest.java b/persistence/src/test/java/com/alibaba/nacos/persistence/repository/embedded/sql/limiter/SqlTypeLimiterTest.java new file mode 100644 index 00000000000..ecb8a9829ac --- /dev/null +++ b/persistence/src/test/java/com/alibaba/nacos/persistence/repository/embedded/sql/limiter/SqlTypeLimiterTest.java @@ -0,0 +1,134 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.persistence.repository.embedded.sql.limiter; + +import com.alibaba.nacos.persistence.repository.embedded.sql.ModifyRequest; +import com.alibaba.nacos.persistence.repository.embedded.sql.SelectRequest; +import com.alibaba.nacos.sys.env.EnvUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.mock.env.MockEnvironment; + +import java.sql.SQLException; +import java.util.LinkedList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +class SqlTypeLimiterTest { + + SqlTypeLimiter sqlLimiter; + + @BeforeEach + void setUp() { + MockEnvironment environment = new MockEnvironment(); + EnvUtil.setEnvironment(environment); + sqlLimiter = new SqlTypeLimiter(); + } + + @AfterEach + void tearDown() { + EnvUtil.setEnvironment(null); + } + + @Test + void testDoLimitForModifyRequestForDdl() throws SQLException { + ModifyRequest createTable = new ModifyRequest("create table test(id int,name varchar(255))"); + ModifyRequest createIndex = new ModifyRequest("create index test_index on test(id)"); + ModifyRequest alterTable = new ModifyRequest("alter table test add column age int"); + List modifyRequests = new LinkedList<>(); + modifyRequests.add(createTable); + modifyRequests.add(createIndex); + modifyRequests.add(alterTable); + sqlLimiter.doLimitForModifyRequest(modifyRequests); + } + + @Test + void testDoLimitForModifyRequestForDdlForEmptyToken() throws SQLException { + ModifyRequest create = new ModifyRequest("create "); + assertThrows(SQLException.class, () -> sqlLimiter.doLimitForModifyRequest(create)); + } + + @Test + void testDoLimitForModifyRequestForDdlForOneToken() throws SQLException { + ModifyRequest create = new ModifyRequest("create"); + assertThrows(SQLException.class, () -> sqlLimiter.doLimitForModifyRequest(create)); + } + + @Test + void testDoLimitForModifyRequestForDdlForInvalidSecondToken() throws SQLException { + ModifyRequest create = new ModifyRequest("create xxx"); + assertThrows(SQLException.class, () -> sqlLimiter.doLimitForModifyRequest(create)); + } + + @Test + void testDoLimitForModifyRequestForDml() throws SQLException { + ModifyRequest insert = new ModifyRequest("insert into test(id,name) values(1,'test')"); + ModifyRequest update = new ModifyRequest("update test set name='test' where id=1"); + ModifyRequest delete = new ModifyRequest("delete from test where id=1"); + List modifyRequests = new LinkedList<>(); + modifyRequests.add(insert); + modifyRequests.add(update); + modifyRequests.add(delete); + sqlLimiter.doLimitForModifyRequest(modifyRequests); + } + + @Test + void testDoLimitForModifyRequestForDmlInvalid() throws SQLException { + ModifyRequest insert = new ModifyRequest("insert into test(id,name) values(1,'test')"); + ModifyRequest invalid = new ModifyRequest("CALL SALES.TOTAL_REVENUES()"); + List modifyRequests = new LinkedList<>(); + modifyRequests.add(insert); + modifyRequests.add(invalid); + assertThrows(SQLException.class, () -> sqlLimiter.doLimitForModifyRequest(modifyRequests)); + } + + @Test + void testDoLimitForSelectRequest() throws SQLException { + SelectRequest selectRequest = SelectRequest.builder().sql("select * from test").build(); + sqlLimiter.doLimitForSelectRequest(selectRequest); + } + + @Test + void testDoLimitForSelectRequestInvalid() throws SQLException { + SelectRequest selectRequest = SelectRequest.builder().sql("select * from test").build(); + SelectRequest invalid = SelectRequest.builder().sql("CALL SALES.TOTAL_REVENUES()").build(); + List selectRequests = new LinkedList<>(); + selectRequests.add(selectRequest); + selectRequests.add(invalid); + assertThrows(SQLException.class, () -> sqlLimiter.doLimitForSelectRequest(selectRequests)); + } + + @Test + void testDoLimit() { + List sql = new LinkedList<>(); + sql.add("create table test(id int,name varchar(255))"); + sql.add("select * from test"); + sql.add("CALL SALES.TOTAL_REVENUES();"); + assertThrows(SQLException.class, () -> sqlLimiter.doLimit(sql)); + } + + @Test + void testDoLimitForDisabledLimit() throws SQLException { + MockEnvironment environment = new MockEnvironment(); + environment.setProperty("nacos.persistence.sql.derby.limit.enabled", "false"); + EnvUtil.setEnvironment(environment); + sqlLimiter = new SqlTypeLimiter(); + sqlLimiter.doLimit("CALL SALES.TOTAL_REVENUES();"); + } +} \ No newline at end of file diff --git a/persistence/src/test/java/com/alibaba/nacos/persistence/utils/ConnectionCheckUtilTest.java b/persistence/src/test/java/com/alibaba/nacos/persistence/utils/ConnectionCheckUtilTest.java index 63a94fb4671..a3c8922aaa9 100644 --- a/persistence/src/test/java/com/alibaba/nacos/persistence/utils/ConnectionCheckUtilTest.java +++ b/persistence/src/test/java/com/alibaba/nacos/persistence/utils/ConnectionCheckUtilTest.java @@ -17,11 +17,12 @@ package com.alibaba.nacos.persistence.utils; import com.zaxxer.hikari.HikariDataSource; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.sql.Connection; import java.sql.SQLException; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -31,18 +32,20 @@ * * @author Long Yu */ -public class ConnectionCheckUtilTest { +class ConnectionCheckUtilTest { - @Test(expected = RuntimeException.class) - public void testCheckConnectionThrowException() throws SQLException { - HikariDataSource ds = mock(HikariDataSource.class); - when(ds.getConnection()).thenThrow(new RuntimeException()); - ConnectionCheckUtil.checkDataSourceConnection(ds); - verify(ds).getConnection(); + @Test + void testCheckConnectionThrowException() throws SQLException { + assertThrows(RuntimeException.class, () -> { + HikariDataSource ds = mock(HikariDataSource.class); + when(ds.getConnection()).thenThrow(new RuntimeException()); + ConnectionCheckUtil.checkDataSourceConnection(ds); + verify(ds).getConnection(); + }); } @Test - public void testCheckConnectionNormal() throws SQLException { + void testCheckConnectionNormal() throws SQLException { HikariDataSource ds = mock(HikariDataSource.class); Connection connection = mock(Connection.class); when(ds.getConnection()).thenReturn(connection); diff --git a/persistence/src/test/java/com/alibaba/nacos/persistence/utils/DerbyUtilsTest.java b/persistence/src/test/java/com/alibaba/nacos/persistence/utils/DerbyUtilsTest.java index 271a78802e8..cc7682b25d5 100644 --- a/persistence/src/test/java/com/alibaba/nacos/persistence/utils/DerbyUtilsTest.java +++ b/persistence/src/test/java/com/alibaba/nacos/persistence/utils/DerbyUtilsTest.java @@ -16,19 +16,20 @@ package com.alibaba.nacos.persistence.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; @SuppressWarnings("checkstyle:linelength") -public class DerbyUtilsTest { +class DerbyUtilsTest { @Test - public void testDerbySqlCorrect() { + void testDerbySqlCorrect() { final String testSql = "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (1,'boot-test','ALIBABA','dept:123123123\\ngroup:123123123','2ca50d002a7dabf81497f666a7967e15','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL);"; final String result = DerbyUtils.insertStatementCorrection(testSql); final String expect = "INSERT INTO CONFIG_INFO (ID, DATA_ID, GROUP_ID, CONTENT, MD5, GMT_CREATE, GMT_MODIFIED, SRC_USER, SRC_IP, APP_NAME, TENANT_ID, C_DESC, C_USE, EFFECT, TYPE, C_SCHEMA) VALUES (1,'boot-test','ALIBABA','dept:123123123\\ngroup:123123123','2ca50d002a7dabf81497f666a7967e15','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL)"; - Assert.assertEquals(expect, result); + assertEquals(expect, result); } } diff --git a/persistence/src/test/java/com/alibaba/nacos/persistence/utils/PersistenceExecutorTest.java b/persistence/src/test/java/com/alibaba/nacos/persistence/utils/PersistenceExecutorTest.java index 300aa221258..0aaa90a6518 100644 --- a/persistence/src/test/java/com/alibaba/nacos/persistence/utils/PersistenceExecutorTest.java +++ b/persistence/src/test/java/com/alibaba/nacos/persistence/utils/PersistenceExecutorTest.java @@ -16,16 +16,17 @@ package com.alibaba.nacos.persistence.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -public class PersistenceExecutorTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class PersistenceExecutorTest { @Test - public void testExecuteEmbeddedDump() throws InterruptedException { + void testExecuteEmbeddedDump() throws InterruptedException { AtomicInteger atomicInteger = new AtomicInteger(); @@ -35,7 +36,7 @@ public void testExecuteEmbeddedDump() throws InterruptedException { TimeUnit.MILLISECONDS.sleep(20); - Assert.assertEquals(1, atomicInteger.get()); + assertEquals(1, atomicInteger.get()); } diff --git a/persistence/src/test/resources/logback-test.xml b/persistence/src/test/resources/logback-test.xml new file mode 100644 index 00000000000..e726ab228a6 --- /dev/null +++ b/persistence/src/test/resources/logback-test.xml @@ -0,0 +1,19 @@ + + + + + \ No newline at end of file diff --git a/plugin-default-impl/nacos-default-auth-plugin/pom.xml b/plugin-default-impl/nacos-default-auth-plugin/pom.xml index 95b618c4686..11e4d389b11 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/pom.xml +++ b/plugin-default-impl/nacos-default-auth-plugin/pom.xml @@ -54,5 +54,11 @@ org.springframework.ldap spring-ldap-core + + + org.springframework + spring-test + test + - \ No newline at end of file + diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/LdapAuthenticationProvider.java b/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/LdapAuthenticationProvider.java index 6db396bac0e..d2fa4b07bc9 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/LdapAuthenticationProvider.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/LdapAuthenticationProvider.java @@ -94,11 +94,10 @@ public Authentication authenticate(Authentication authentication) throws Authent try { userDetails = userDetailsService.loadUserByUsername(AuthConstants.LDAP_PREFIX + username); } catch (UsernameNotFoundException exception) { - String nacosPassword = PasswordEncoderUtil.encode(AuthConstants.LDAP_DEFAULT_PASSWORD); - userDetailsService.createUser(AuthConstants.LDAP_PREFIX + username, nacosPassword); + userDetailsService.createUser(AuthConstants.LDAP_PREFIX + username, AuthConstants.LDAP_DEFAULT_ENCODED_PASSWORD); User user = new User(); user.setUsername(AuthConstants.LDAP_PREFIX + username); - user.setPassword(nacosPassword); + user.setPassword(AuthConstants.LDAP_DEFAULT_ENCODED_PASSWORD); userDetails = new NacosUserDetails(user); } return new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities()); diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/NacosAuthPluginService.java b/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/NacosAuthPluginService.java index 4902e665292..0332ba729b0 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/NacosAuthPluginService.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/NacosAuthPluginService.java @@ -113,6 +113,18 @@ public boolean isLoginEnabled() { return ApplicationUtils.getBean(AuthConfigs.class).isAuthEnabled(); } + /** + * Only auth enabled and not global admin role existed. + * + * @return {@code true} when auth enabled and not global admin role existed, otherwise {@code false} + */ + @Override + public boolean isAdminRequest() { + boolean authEnabled = ApplicationUtils.getBean(AuthConfigs.class).isAuthEnabled(); + boolean hasGlobalAdminRole = ApplicationUtils.getBean(IAuthenticationManager.class).hasGlobalAdminRole(); + return authEnabled && !hasGlobalAdminRole; + } + protected void checkNacosAuthManager() { if (null == authenticationManager) { authenticationManager = ApplicationUtils.getBean(DefaultAuthenticationManager.class); diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/constant/AuthConstants.java b/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/constant/AuthConstants.java index 90664d65e24..56d6dd75a5b 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/constant/AuthConstants.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/constant/AuthConstants.java @@ -73,11 +73,8 @@ public class AuthConstants { * LDAP Ignore partial result exception. */ public static final String NACOS_CORE_AUTH_IGNORE_PARTIAL_RESULT_EXCEPTION = "nacos.core.auth.ldap.ignore.partial.result.exception"; - - @Deprecated - public static final String LDAP_DEFAULT_PASSWORD = "nacos"; - - public static final String LDAP_DEFAULT_ENCODED_PASSWORD = PasswordEncoderUtil.encode(LDAP_DEFAULT_PASSWORD); + + public static final String LDAP_DEFAULT_ENCODED_PASSWORD = PasswordEncoderUtil.encode(System.getProperty("ldap.default.password", "nacos")); public static final String LDAP_PREFIX = "LDAP_"; } diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/controller/UserController.java b/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/controller/UserController.java index a4e60f7c5e3..ed904b83a6e 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/controller/UserController.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/controller/UserController.java @@ -23,6 +23,7 @@ import com.alibaba.nacos.common.model.RestResultUtils; import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.common.utils.StringUtils; +import com.alibaba.nacos.core.context.RequestContextHolder; import com.alibaba.nacos.persistence.model.Page; import com.alibaba.nacos.plugin.auth.api.IdentityContext; import com.alibaba.nacos.plugin.auth.constant.ActionTypes; @@ -102,7 +103,11 @@ public class UserController { @Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "users", action = ActionTypes.WRITE) @PostMapping public Object createUser(@RequestParam String username, @RequestParam String password) { - + if (AuthConstants.DEFAULT_USER.equals(username)) { + return RestResultUtils.failed(HttpStatus.CONFLICT.value(), + "User `nacos` is default admin user. Please use `/nacos/v1/auth/users/admin` API to init `nacos` users. " + + "Detail see `https://nacos.io/docs/latest/manual/admin/auth/#31-%E8%AE%BE%E7%BD%AE%E7%AE%A1%E7%90%86%E5%91%98%E5%AF%86%E7%A0%81`"); + } User user = userDetailsService.getUserFromDatabase(username); if (user != null) { throw new IllegalArgumentException("user '" + username + "' already exist!"); @@ -115,18 +120,16 @@ public Object createUser(@RequestParam String username, @RequestParam String pas * Create a admin user only not exist admin user can use. */ @PostMapping("/admin") - public Object createAdminUser(@RequestParam(required = false) String username, - @RequestParam(required = false) String password) { + public Object createAdminUser(@RequestParam(required = false) String password) { if (AuthSystemTypes.NACOS.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType())) { - if (roleService.hasGlobalAdminRole()) { - return RestResultUtils.failed("have admin user cannot use it"); + if (iAuthenticationManager.hasGlobalAdminRole()) { + return RestResultUtils.failed(HttpStatus.CONFLICT.value(), "have admin user cannot use it"); } if (StringUtils.isBlank(password)) { password = PasswordGeneratorUtil.generateRandomPassword(); } - if (StringUtils.isBlank(username)) { - username = AuthConstants.DEFAULT_USER; - } + + String username = AuthConstants.DEFAULT_USER; userDetailsService.createUser(username, PasswordEncoderUtil.encode(password)); roleService.addAdminRole(username); ObjectNode result = JacksonUtils.createEmptyJsonNode(); @@ -134,7 +137,7 @@ public Object createAdminUser(@RequestParam(required = false) String username, result.put(AuthConstants.PARAM_PASSWORD, password); return result; } else { - return RestResultUtils.failed("not support"); + return RestResultUtils.failed(HttpStatus.NOT_IMPLEMENTED.value(), "not support"); } } @@ -204,8 +207,7 @@ private boolean hasPermission(String username, HttpServletRequest request) if (!authConfigs.isAuthEnabled()) { return true; } - IdentityContext identityContext = (IdentityContext) request.getSession() - .getAttribute(com.alibaba.nacos.plugin.auth.constant.Constants.Identity.IDENTITY_CONTEXT); + IdentityContext identityContext = RequestContextHolder.getContext().getAuthContext().getIdentityContext(); if (identityContext == null) { throw new HttpSessionRequiredException("session expired!"); } @@ -266,10 +268,7 @@ public Object login(@RequestParam String username, @RequestParam String password if (AuthSystemTypes.NACOS.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType()) || AuthSystemTypes.LDAP.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType())) { - if (!iAuthenticationManager.hasGlobalAdminRole()) { - response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, "admin role user not exist"); - return null; - } + NacosUser user = iAuthenticationManager.authenticate(request); response.addHeader(AuthConstants.AUTHORIZATION_HEADER, AuthConstants.TOKEN_PREFIX + user.getToken()); @@ -329,7 +328,6 @@ public RestResult updatePassword(@RequestParam(value = "oldPassword") St } } - /** * Fuzzy matching username. * diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/jwt/NacosJwtParser.java b/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/jwt/NacosJwtParser.java index 4adfa6f3ec0..0a18bfbbaae 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/jwt/NacosJwtParser.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/jwt/NacosJwtParser.java @@ -19,6 +19,8 @@ import com.alibaba.nacos.plugin.auth.exception.AccessException; import com.alibaba.nacos.plugin.auth.impl.users.NacosUser; import com.alibaba.nacos.plugin.auth.impl.utils.Base64Decode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.crypto.spec.SecretKeySpec; import java.security.Key; @@ -32,12 +34,15 @@ */ @SuppressWarnings("PMD.UndefineMagicConstantRule") public class NacosJwtParser { + + private static final Logger LOG = LoggerFactory.getLogger(NacosJwtParser.class); private final NacosSignatureAlgorithm signatureAlgorithm; private final Key key; public NacosJwtParser(String base64edKey) { + this.validKey(base64edKey); byte[] decode = Base64Decode.decode(base64edKey); int bitLength = decode.length << 3; if (bitLength < 256) { @@ -58,6 +63,14 @@ public NacosJwtParser(String base64edKey) { } this.key = new SecretKeySpec(decode, signatureAlgorithm.getJcaName()); } + + private void validKey(String base64edKey) { + int length = base64edKey.toCharArray().length; + if (length % 4 != 0) { + LOG.warn("The secret Key currently in use is not a standard Base64 encoding" + + " and will no longer be supported in future versions;"); + } + } private String sign(NacosJwtPayload payload) { return signatureAlgorithm.sign(payload, key); diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/jwt/NacosSignatureAlgorithm.java b/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/jwt/NacosSignatureAlgorithm.java index 335375b4567..38b1e1e206b 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/jwt/NacosSignatureAlgorithm.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/jwt/NacosSignatureAlgorithm.java @@ -203,7 +203,9 @@ private Mac getMacInstance(Key key) { Mac instance = Mac.getInstance(jcaName); instance.init(key); return instance; - } catch (NoSuchAlgorithmException | InvalidKeyException e) { + } catch (NoSuchAlgorithmException e) { + throw new IllegalArgumentException("No Such Algorithm: " + jcaName); + } catch (InvalidKeyException e) { throw new IllegalArgumentException("Invalid key: " + key); } } diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/token/impl/JwtTokenManager.java b/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/token/impl/JwtTokenManager.java index 33e727cc722..7dc2cc57469 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/token/impl/JwtTokenManager.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/token/impl/JwtTokenManager.java @@ -103,10 +103,13 @@ public String createToken(Authentication authentication) { * @return token */ public String createToken(String userName) { - if (!authConfigs.isAuthEnabled()) { + // create a token when auth enabled or nacos.core.auth.plugin.nacos.token.secret.key is configured + if (!authConfigs.isAuthEnabled() && null == jwtParser) { return AUTH_DISABLED_TOKEN; + } else if (authConfigs.isAuthEnabled()) { + // check nacos.core.auth.plugin.nacos.token.secret.key only if auth enabled + checkJwtParser(); } - checkJwtParser(); return jwtParser.jwtBuilder().setUserName(userName).setExpiredTime(this.tokenValidityInSeconds).compact(); } @@ -147,7 +150,7 @@ public long getTokenValidityInSeconds() { @Override public long getTokenTtlInSeconds(String token) throws AccessException { if (!authConfigs.isAuthEnabled()) { - return TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()) + tokenValidityInSeconds; + return tokenValidityInSeconds; } return jwtParser.getExpireTimeInSeconds(token) - TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()); } diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/LdapAuthenticationProviderTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/LdapAuthenticationProviderTest.java index cd22d25f51c..0b272384954 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/LdapAuthenticationProviderTest.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/LdapAuthenticationProviderTest.java @@ -23,13 +23,14 @@ import com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetails; import com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetailsServiceImpl; import org.apache.commons.lang.StringUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.mockito.stubbing.Answer; import org.springframework.ldap.core.LdapTemplate; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -40,10 +41,30 @@ import java.util.ArrayList; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class LdapAuthenticationProviderTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class LdapAuthenticationProviderTest { + + private static final String LDAP_PREFIX = "LDAP_"; + + private final String adminUserName = "nacos"; + + private final String normalUserName = "normal"; + + private final String filterPrefix = "uid"; + + private final boolean caseSensitive = true; + + Method isAdmin; + + Method ldapLogin; @Mock private NacosUserDetailsServiceImpl userDetailsService; @@ -60,32 +81,18 @@ public class LdapAuthenticationProviderTest { private List roleInfos = new ArrayList<>(); - private final String adminUserName = "nacos"; - - private final String normalUserName = "normal"; + private String defaultPassWord = System.getProperty("ldap.default.password", "nacos"); - private final String filterPrefix = "uid"; - - private final boolean caseSensitive = true; - - private static final String LDAP_PREFIX = "LDAP_"; - - Method isAdmin; - - Method ldapLogin; - - private String defaultPassWord = "nacos"; - - @Before - public void setUp() throws NoSuchMethodException { + @BeforeEach + void setUp() throws NoSuchMethodException { RoleInfo adminRole = new RoleInfo(); adminRole.setRole(AuthConstants.GLOBAL_ADMIN_ROLE); adminRole.setUsername(adminUserName); roleInfos.add(adminRole); when(nacosRoleService.getRoles(adminUserName)).thenReturn(roleInfos); when(nacosRoleService.getRoles(normalUserName)).thenReturn(new ArrayList<>()); - when(ldapTemplate.authenticate("", "(" + filterPrefix + "=" + adminUserName + ")", defaultPassWord)) - .thenAnswer(new Answer() { + when(ldapTemplate.authenticate("", "(" + filterPrefix + "=" + adminUserName + ")", defaultPassWord)).thenAnswer( + new Answer() { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); @@ -97,10 +104,10 @@ public Boolean answer(InvocationOnMock invocation) throws Throwable { return false; } }); - this.ldapAuthenticationProvider = new LdapAuthenticationProvider(ldapTemplate, userDetailsService, - nacosRoleService, filterPrefix, caseSensitive); - this.ldapAuthenticationProviderForCloseCaseSensitive = new LdapAuthenticationProvider(ldapTemplate, - userDetailsService, nacosRoleService, filterPrefix, !caseSensitive); + this.ldapAuthenticationProvider = new LdapAuthenticationProvider(ldapTemplate, userDetailsService, nacosRoleService, filterPrefix, + caseSensitive); + this.ldapAuthenticationProviderForCloseCaseSensitive = new LdapAuthenticationProvider(ldapTemplate, userDetailsService, + nacosRoleService, filterPrefix, !caseSensitive); isAdmin = LdapAuthenticationProvider.class.getDeclaredMethod("isAdmin", String.class); isAdmin.setAccessible(true); ldapLogin = LdapAuthenticationProvider.class.getDeclaredMethod("ldapLogin", String.class, String.class); @@ -108,77 +115,75 @@ public Boolean answer(InvocationOnMock invocation) throws Throwable { } @Test - public void testIsAdmin() { + void testIsAdmin() { try { Boolean result = (Boolean) isAdmin.invoke(ldapAuthenticationProvider, adminUserName); - Assert.assertTrue(result); + assertTrue(result); } catch (IllegalAccessException e) { - Assert.fail(); + fail(); } catch (InvocationTargetException e) { - Assert.fail(); + fail(); } try { Boolean result = (Boolean) isAdmin.invoke(ldapAuthenticationProvider, normalUserName); - Assert.assertTrue(!result); + assertFalse(result); } catch (IllegalAccessException e) { - Assert.fail(); + fail(); } catch (InvocationTargetException e) { - Assert.fail(); + fail(); } } @Test - public void testldapLogin() { + void testldapLogin() { try { Boolean result = (Boolean) ldapLogin.invoke(ldapAuthenticationProvider, adminUserName, defaultPassWord); - Assert.assertTrue(result); + assertTrue(result); } catch (IllegalAccessException e) { - Assert.fail(); + fail(); } catch (InvocationTargetException e) { - Assert.fail(); + fail(); } try { Boolean result = (Boolean) ldapLogin.invoke(ldapAuthenticationProvider, adminUserName, "123"); - Assert.assertTrue(!result); + assertFalse(result); } catch (IllegalAccessException e) { - Assert.fail(); + fail(); } catch (InvocationTargetException e) { - Assert.fail(); + fail(); } } @Test - public void testDefaultCaseSensitive() { + void testDefaultCaseSensitive() { String userName = StringUtils.upperCase(normalUserName); - when(ldapTemplate.authenticate("", "(" + filterPrefix + "=" + userName + ")", defaultPassWord)) - .thenAnswer(new Answer() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - String b = (String) args[1]; - String c = (String) args[2]; - if (defaultPassWord.equals(c)) { - return true; - } - return false; - } - }); + when(ldapTemplate.authenticate("", "(" + filterPrefix + "=" + userName + ")", defaultPassWord)).thenAnswer(new Answer() { + @Override + public Boolean answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + String b = (String) args[1]; + String c = (String) args[2]; + if (defaultPassWord.equals(c)) { + return true; + } + return false; + } + }); User userUpperCase = new User(); userUpperCase.setUsername(LDAP_PREFIX + userName); userUpperCase.setPassword(defaultPassWord); - when(userDetailsService.loadUserByUsername(LDAP_PREFIX + userName)) - .thenReturn(new NacosUserDetails(userUpperCase)); + when(userDetailsService.loadUserByUsername(LDAP_PREFIX + userName)).thenReturn(new NacosUserDetails(userUpperCase)); Authentication authentication = new UsernamePasswordAuthenticationToken(userName, defaultPassWord); Authentication result = ldapAuthenticationProvider.authenticate(authentication); NacosUserDetails nacosUserDetails = (NacosUserDetails) result.getPrincipal(); - Assert.assertTrue(nacosUserDetails.getUsername().equals(LDAP_PREFIX + userName)); + assertEquals(nacosUserDetails.getUsername(), LDAP_PREFIX + userName); } @Test - public void testCloseCaseSensitive() { - when(ldapTemplate.authenticate("", "(" + filterPrefix + "=" + normalUserName + ")", defaultPassWord)) - .thenAnswer(new Answer() { + void testCloseCaseSensitive() { + when(ldapTemplate.authenticate("", "(" + filterPrefix + "=" + normalUserName + ")", defaultPassWord)).thenAnswer( + new Answer() { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); @@ -193,12 +198,10 @@ public Boolean answer(InvocationOnMock invocation) throws Throwable { User user = new User(); user.setUsername(LDAP_PREFIX + normalUserName); user.setPassword(defaultPassWord); - when(userDetailsService.loadUserByUsername(LDAP_PREFIX + normalUserName)) - .thenReturn(new NacosUserDetails(user)); - Authentication authentication = new UsernamePasswordAuthenticationToken(StringUtils.upperCase(normalUserName), - defaultPassWord); + when(userDetailsService.loadUserByUsername(LDAP_PREFIX + normalUserName)).thenReturn(new NacosUserDetails(user)); + Authentication authentication = new UsernamePasswordAuthenticationToken(StringUtils.upperCase(normalUserName), defaultPassWord); Authentication result = ldapAuthenticationProviderForCloseCaseSensitive.authenticate(authentication); NacosUserDetails nacosUserDetails = (NacosUserDetails) result.getPrincipal(); - Assert.assertTrue(nacosUserDetails.getUsername().equals(LDAP_PREFIX + normalUserName)); + assertEquals(nacosUserDetails.getUsername(), LDAP_PREFIX + normalUserName); } } diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/authenticate/AbstractAuthenticationManagerTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/authenticate/AbstractAuthenticationManagerTest.java new file mode 100644 index 00000000000..69df77d91af --- /dev/null +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/authenticate/AbstractAuthenticationManagerTest.java @@ -0,0 +1,211 @@ +/* + * Copyright 1999-2024 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.plugin.auth.impl.authenticate; + +import com.alibaba.nacos.api.common.Constants; +import com.alibaba.nacos.plugin.auth.api.Permission; +import com.alibaba.nacos.plugin.auth.exception.AccessException; +import com.alibaba.nacos.plugin.auth.impl.constant.AuthConstants; +import com.alibaba.nacos.plugin.auth.impl.persistence.User; +import com.alibaba.nacos.plugin.auth.impl.roles.NacosRoleServiceImpl; +import com.alibaba.nacos.plugin.auth.impl.token.TokenManagerDelegate; +import com.alibaba.nacos.plugin.auth.impl.users.NacosUser; +import com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetails; +import com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetailsServiceImpl; +import com.alibaba.nacos.plugin.auth.impl.utils.PasswordEncoderUtil; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.mock.web.MockHttpServletRequest; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +public class AbstractAuthenticationManagerTest { + + @InjectMocks + private AbstractAuthenticationManager abstractAuthenticationManager; + + @Mock + private NacosUserDetailsServiceImpl userDetailsService; + + @Mock + private TokenManagerDelegate jwtTokenManager; + + @Mock + private NacosRoleServiceImpl roleService; + + private User user; + + @BeforeEach + void setUp() throws Exception { + user = new User(); + user.setUsername("nacos"); + user.setPassword(PasswordEncoderUtil.encode("test")); + } + + @Test + void testAuthenticate1() { + assertThrows(AccessException.class, () -> { + abstractAuthenticationManager.authenticate(null, "pwd"); + }); + } + + @Test + void testAuthenticate2() { + assertThrows(AccessException.class, () -> { + abstractAuthenticationManager.authenticate("nacos", null); + }); + } + + @Test + void testAuthenticate3() throws AccessException { + NacosUserDetails nacosUserDetails = new NacosUserDetails(user); + + when(userDetailsService.loadUserByUsername(anyString())).thenReturn(nacosUserDetails); + + when(jwtTokenManager.createToken(anyString())).thenReturn("token"); + + NacosUser nacosUser = abstractAuthenticationManager.authenticate("nacos", "test"); + + assertEquals("token", nacosUser.getToken()); + assertEquals(user.getUsername(), nacosUser.getUserName()); + } + + @Test + void testAuthenticate4() { + when(userDetailsService.loadUserByUsername(anyString())).thenReturn(null); + + assertThrows(AccessException.class, () -> { + abstractAuthenticationManager.authenticate("nacos", "test"); + }); + } + + @Test + void testAuthenticate5() { + assertThrows(AccessException.class, () -> { + abstractAuthenticationManager.authenticate(""); + }); + } + + @Test + void testAuthenticate6() throws AccessException { + NacosUser nacosUser = new NacosUser(); + + when(jwtTokenManager.parseToken(anyString())).thenReturn(nacosUser); + NacosUser authenticate = abstractAuthenticationManager.authenticate("token"); + + assertEquals(nacosUser, authenticate); + } + + @Test + void testAuthenticate7() throws AccessException { + NacosUser nacosUser = new NacosUser(); + when(jwtTokenManager.parseToken(anyString())).thenReturn(nacosUser); + + MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); + mockHttpServletRequest.addHeader(AuthConstants.AUTHORIZATION_HEADER, AuthConstants.TOKEN_PREFIX + "-token"); + NacosUser authenticate = abstractAuthenticationManager.authenticate(mockHttpServletRequest); + + assertEquals(nacosUser, authenticate); + } + + @Test + void testAuthenticate8() throws AccessException { + NacosUser nacosUser = new NacosUser(); + when(jwtTokenManager.parseToken(anyString())).thenReturn(nacosUser); + + MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); + mockHttpServletRequest.addHeader(AuthConstants.AUTHORIZATION_HEADER, "token"); + mockHttpServletRequest.addParameter(Constants.ACCESS_TOKEN, "token"); + NacosUser authenticate = abstractAuthenticationManager.authenticate(mockHttpServletRequest); + + assertEquals(nacosUser, authenticate); + } + + @Test + void testAuthenticate9() throws AccessException { + NacosUserDetails nacosUserDetails = new NacosUserDetails(user); + when(userDetailsService.loadUserByUsername(anyString())).thenReturn(nacosUserDetails); + + when(jwtTokenManager.createToken(anyString())).thenReturn("token"); + MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); + mockHttpServletRequest.addHeader(AuthConstants.AUTHORIZATION_HEADER, "token"); + mockHttpServletRequest.addParameter(AuthConstants.PARAM_USERNAME, "nacos"); + mockHttpServletRequest.addParameter(AuthConstants.PARAM_PASSWORD, "test"); + NacosUser authenticate = abstractAuthenticationManager.authenticate(mockHttpServletRequest); + + assertEquals("token", authenticate.getToken()); + assertEquals(user.getUsername(), authenticate.getUserName()); + } + + @Test + void testAuthorize() { + Permission permission = new Permission(); + NacosUser nacosUser = new NacosUser(); + when(roleService.hasPermission(nacosUser, permission)).thenReturn(false); + + assertThrows(AccessException.class, () -> { + abstractAuthenticationManager.authorize(permission, nacosUser); + }); + } + + @Test + void testHasGlobalAdminRole() { + when(roleService.hasGlobalAdminRole(anyString())).thenReturn(true); + + boolean hasGlobalAdminRole = abstractAuthenticationManager.hasGlobalAdminRole("nacos"); + + assertTrue(hasGlobalAdminRole); + } + + @Test + void testHasGlobalAdminRole2() { + when(roleService.hasGlobalAdminRole()).thenReturn(true); + + boolean hasGlobalAdminRole = abstractAuthenticationManager.hasGlobalAdminRole(); + + assertTrue(hasGlobalAdminRole); + } + + @Test + void testHasGlobalAdminRole3() { + NacosUser nacosUser = new NacosUser("nacos"); + nacosUser.setGlobalAdmin(true); + + boolean hasGlobalAdminRole = abstractAuthenticationManager.hasGlobalAdminRole(nacosUser); + + assertTrue(hasGlobalAdminRole); + } + + @Test + void testHasGlobalAdminRole4() { + NacosUser nacosUser = new NacosUser("nacos"); + nacosUser.setGlobalAdmin(false); + when(roleService.hasGlobalAdminRole(anyString())).thenReturn(true); + boolean hasGlobalAdminRole = abstractAuthenticationManager.hasGlobalAdminRole(nacosUser); + + assertTrue(hasGlobalAdminRole); + } +} diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/authenticate/LdapAuthenticationManagerTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/authenticate/LdapAuthenticationManagerTest.java new file mode 100644 index 00000000000..242283db164 --- /dev/null +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/authenticate/LdapAuthenticationManagerTest.java @@ -0,0 +1,73 @@ +/* + * Copyright 1999-2024 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.plugin.auth.impl.authenticate; + +import com.alibaba.nacos.plugin.auth.exception.AccessException; +import com.alibaba.nacos.plugin.auth.impl.persistence.User; +import com.alibaba.nacos.plugin.auth.impl.roles.NacosRoleServiceImpl; +import com.alibaba.nacos.plugin.auth.impl.token.TokenManagerDelegate; +import com.alibaba.nacos.plugin.auth.impl.users.NacosUser; +import com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetails; +import com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetailsServiceImpl; +import com.alibaba.nacos.plugin.auth.impl.utils.PasswordEncoderUtil; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.ldap.core.LdapTemplate; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +public class LdapAuthenticationManagerTest { + + @Mock + private NacosUserDetailsServiceImpl userDetailsService; + + @Mock + private TokenManagerDelegate jwtTokenManager; + + @Mock + private NacosRoleServiceImpl roleService; + + @Mock + private LdapTemplate ldapTemplate; + + private LdapAuthenticationManager ldapAuthenticationManager; + + private User user; + + @BeforeEach + void setUp() throws Exception { + user = new User(); + user.setUsername("nacos"); + user.setPassword(PasswordEncoderUtil.encode("test")); + ldapAuthenticationManager = new LdapAuthenticationManager(ldapTemplate, userDetailsService, jwtTokenManager, + roleService, "", true); + } + + @Test + void testLdapAuthenticate() throws AccessException { + NacosUserDetails nacosUserDetails = new NacosUserDetails(user); + when(userDetailsService.loadUserByUsername(anyString())).thenReturn(nacosUserDetails); + NacosUser authenticate = ldapAuthenticationManager.authenticate("nacos", "test"); + assertEquals(user.getUsername(), authenticate.getUserName()); + } +} diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/configuration/ConditionOnLdapAuthTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/configuration/ConditionOnLdapAuthTest.java index 30760036bbe..242284f039f 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/configuration/ConditionOnLdapAuthTest.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/configuration/ConditionOnLdapAuthTest.java @@ -17,24 +17,29 @@ package com.alibaba.nacos.plugin.auth.impl.configuration; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.type.AnnotatedTypeMetadata; +import static org.junit.jupiter.api.Assertions.assertFalse; + /** * ConditionOnLdapAuth test. + * * @ClassName: ConditionOnLdapAuthTest * @Author: ChenHao26 * @Date: 2022/8/16 17:03 */ -@RunWith(MockitoJUnitRunner.class) -public class ConditionOnLdapAuthTest { +@ExtendWith(MockitoExtension.class) +class ConditionOnLdapAuthTest { + + @Mock + private static ConfigurableEnvironment environment; private ConditionOnLdapAuth conditionOnLdapAuth; @@ -44,18 +49,15 @@ public class ConditionOnLdapAuthTest { @Mock private AnnotatedTypeMetadata annotatedTypeMetadata; - @Mock - private static ConfigurableEnvironment environment; - - @Before - public void setup() { + @BeforeEach + void setup() { conditionOnLdapAuth = new ConditionOnLdapAuth(); EnvUtil.setEnvironment(environment); } @Test - public void matches() { + void matches() { boolean matches = conditionOnLdapAuth.matches(conditionContext, annotatedTypeMetadata); - Assert.assertFalse(matches); + assertFalse(matches); } } diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/controller/PermissionControllerTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/controller/PermissionControllerTest.java new file mode 100644 index 00000000000..6f73ec63859 --- /dev/null +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/controller/PermissionControllerTest.java @@ -0,0 +1,89 @@ +/* + * Copyright 1999-2024 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.plugin.auth.impl.controller; + +import com.alibaba.nacos.common.model.RestResult; +import com.alibaba.nacos.persistence.model.Page; +import com.alibaba.nacos.plugin.auth.impl.persistence.PermissionInfo; +import com.alibaba.nacos.plugin.auth.impl.roles.NacosRoleServiceImpl; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +public class PermissionControllerTest { + + @InjectMocks + private PermissionController permissionController; + + @Mock + private NacosRoleServiceImpl nacosRoleService; + + @BeforeEach + void setUp() throws Exception { + + } + + @Test + void testGetPermissions() { + Page permissionInfoPage = new Page(); + + when(nacosRoleService.getPermissionsFromDatabase(anyString(), anyInt(), anyInt())).thenReturn( + permissionInfoPage); + + Object permissions = permissionController.getPermissions(1, 10, "admin"); + assertEquals(permissionInfoPage, permissions); + } + + @Test + void testFuzzySearchPermission() { + Page permissionInfoPage = new Page(); + + when(nacosRoleService.findPermissionsLike4Page(anyString(), anyInt(), anyInt())).thenReturn(permissionInfoPage); + + Page permissions = permissionController.fuzzySearchPermission(1, 10, "admin"); + assertEquals(permissionInfoPage, permissions); + } + + @Test + void testAddPermission() { + + RestResult result = (RestResult) permissionController.addPermission("admin", "test", "test"); + + verify(nacosRoleService, times(1)).addPermission(anyString(), anyString(), anyString()); + assertEquals(200, result.getCode()); + } + + @Test + void testDeletePermission() { + RestResult result = (RestResult) permissionController.deletePermission("admin", "test", "test"); + + verify(nacosRoleService, times(1)).deletePermission(anyString(), anyString(), anyString()); + assertEquals(200, result.getCode()); + } + +} diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/controller/RoleControllerTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/controller/RoleControllerTest.java new file mode 100644 index 00000000000..880a687dc5a --- /dev/null +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/controller/RoleControllerTest.java @@ -0,0 +1,114 @@ +/* + * Copyright 1999-2024 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.plugin.auth.impl.controller; + +import com.alibaba.nacos.common.model.RestResult; +import com.alibaba.nacos.persistence.model.Page; +import com.alibaba.nacos.plugin.auth.impl.persistence.RoleInfo; +import com.alibaba.nacos.plugin.auth.impl.roles.NacosRoleServiceImpl; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +public class RoleControllerTest { + + @Mock + private NacosRoleServiceImpl roleService; + + @InjectMocks + private RoleController roleController; + + @BeforeEach + void setUp() throws Exception { + + } + + @Test + void testGetRoles() { + Page rolesTest = new Page(); + + when(roleService.getRolesFromDatabase(anyString(), anyString(), anyInt(), anyInt())).thenReturn(rolesTest); + Object roles = roleController.getRoles(1, 10, "nacos", "test"); + + assertEquals(rolesTest, roles); + } + + @Test + void testFuzzySearchRole() { + + Page rolesTest = new Page(); + + when(roleService.findRolesLike4Page(anyString(), anyString(), anyInt(), anyInt())).thenReturn(rolesTest); + + Page roleInfoPage = roleController.fuzzySearchRole(1, 10, "nacos", "test"); + + assertEquals(rolesTest, roleInfoPage); + } + + @Test + void testSearchRoles() { + List test = new ArrayList<>(); + + when(roleService.findRolesLikeRoleName(anyString())).thenReturn(test); + + List list = roleController.searchRoles("test"); + assertEquals(test, list); + } + + @Test + void testAddRole() { + RestResult result = (RestResult) roleController.addRole("test", "nacos"); + + verify(roleService, times(1)).addRole(anyString(), anyString()); + + assertEquals(200, result.getCode()); + } + + @Test + void testDeleteRole1() { + RestResult result = (RestResult) roleController.deleteRole("test", null); + + verify(roleService, times(1)).deleteRole(anyString()); + + assertEquals(200, result.getCode()); + + } + + @Test + void testDeleteRole2() { + RestResult result = (RestResult) roleController.deleteRole("test", "nacos"); + + verify(roleService, times(1)).deleteRole(anyString(), anyString()); + + assertEquals(200, result.getCode()); + + } +} diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/controller/UserControllerTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/controller/UserControllerTest.java index 74417f67dc8..391d55a0b6d 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/controller/UserControllerTest.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/controller/UserControllerTest.java @@ -17,34 +17,54 @@ package com.alibaba.nacos.plugin.auth.impl.controller; import com.alibaba.nacos.auth.config.AuthConfigs; +import com.alibaba.nacos.common.model.RestResult; +import com.alibaba.nacos.core.context.RequestContextHolder; +import com.alibaba.nacos.persistence.model.Page; +import com.alibaba.nacos.plugin.auth.api.IdentityContext; import com.alibaba.nacos.plugin.auth.exception.AccessException; import com.alibaba.nacos.plugin.auth.impl.authenticate.IAuthenticationManager; import com.alibaba.nacos.plugin.auth.impl.constant.AuthConstants; import com.alibaba.nacos.plugin.auth.impl.constant.AuthSystemTypes; +import com.alibaba.nacos.plugin.auth.impl.persistence.RoleInfo; +import com.alibaba.nacos.plugin.auth.impl.persistence.User; +import com.alibaba.nacos.plugin.auth.impl.roles.NacosRoleServiceImpl; import com.alibaba.nacos.plugin.auth.impl.token.TokenManagerDelegate; import com.alibaba.nacos.plugin.auth.impl.users.NacosUser; +import com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetailsServiceImpl; import com.alibaba.nacos.sys.env.EnvUtil; import com.fasterxml.jackson.databind.JsonNode; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import com.fasterxml.jackson.databind.node.ObjectNode; +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.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.HttpStatus; import org.springframework.mock.env.MockEnvironment; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; -import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.Base64; +import java.util.List; -import static org.junit.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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class UserControllerTest { +@ExtendWith(MockitoExtension.class) +class UserControllerTest { @Mock private HttpServletRequest request; @@ -61,19 +81,23 @@ public class UserControllerTest { @Mock private TokenManagerDelegate tokenManagerDelegate; + @Mock + private NacosUserDetailsServiceImpl userDetailsService; + + @Mock + private NacosRoleServiceImpl roleService; + + @InjectMocks private UserController userController; private NacosUser user; - @Before - public void setUp() throws Exception { - userController = new UserController(); + @BeforeEach + void setUp() throws Exception { user = new NacosUser(); user.setUserName("nacos"); user.setGlobalAdmin(true); user.setToken("1234567890"); - injectObject("authConfigs", authConfigs); - injectObject("iAuthenticationManager", authenticationManager); MockEnvironment mockEnvironment = new MockEnvironment(); mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, Base64.getEncoder().encodeToString( @@ -83,14 +107,18 @@ public void setUp() throws Exception { AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString()); EnvUtil.setEnvironment(mockEnvironment); - injectObject("jwtTokenManager", tokenManagerDelegate); + RequestContextHolder.getContext().getAuthContext().setIdentityContext(new IdentityContext()); + } + + @AfterEach + public void tearDown() { + RequestContextHolder.removeContext(); } @Test - public void testLoginWithAuthedUser() throws AccessException, IOException { + void testLoginWithAuthedUser() throws AccessException, IOException { when(authenticationManager.authenticate(request)).thenReturn(user); when(authenticationManager.hasGlobalAdminRole(user)).thenReturn(true); - when(authenticationManager.hasGlobalAdminRole()).thenReturn(true); when(authConfigs.getNacosAuthSystemType()).thenReturn(AuthSystemTypes.NACOS.name()); when(tokenManagerDelegate.getTokenTtlInSeconds(anyString())).thenReturn(18000L); Object actual = userController.login("nacos", "nacos", response, request); @@ -101,9 +129,214 @@ public void testLoginWithAuthedUser() throws AccessException, IOException { assertTrue(actualString.contains("\"globalAdmin\":true")); } - private void injectObject(String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException { - Field field = UserController.class.getDeclaredField(fieldName); - field.setAccessible(true); - field.set(userController, value); + @Test + void testCreateUser1() { + when(userDetailsService.getUserFromDatabase("test")).thenReturn(null); + RestResult result = (RestResult) userController.createUser("test", "test"); + assertEquals(200, result.getCode()); + + } + + @Test + void testCreateUser2() { + when(userDetailsService.getUserFromDatabase("test")).thenReturn(new User()); + assertThrows(IllegalArgumentException.class, () -> { + userController.createUser("test", "test"); + }); + } + + @Test + void testCreateUserNamedNacos() { + RestResult result = (RestResult) userController.createUser("nacos", "test"); + assertEquals(409, result.getCode()); + } + + @Test + void testCreateAdminUser1() { + when(authConfigs.getNacosAuthSystemType()).thenReturn(AuthSystemTypes.NACOS.name()); + when(authenticationManager.hasGlobalAdminRole()).thenReturn(true); + + RestResult result = (RestResult) userController.createAdminUser("test"); + + assertEquals(HttpStatus.CONFLICT.value(), result.getCode()); + } + + @Test + void testCreateAdminUser2() { + RestResult result = (RestResult) userController.createAdminUser("test"); + + assertEquals(HttpStatus.NOT_IMPLEMENTED.value(), result.getCode()); + } + + @Test + void testCreateAdminUser3() { + when(authConfigs.getNacosAuthSystemType()).thenReturn(AuthSystemTypes.NACOS.name()); + when(authenticationManager.hasGlobalAdminRole()).thenReturn(false); + ObjectNode result = (ObjectNode) userController.createAdminUser("test"); + + assertEquals("test", result.get(AuthConstants.PARAM_PASSWORD).asText()); + } + + @Test + void testDeleteUser1() { + List roleInfoList = new ArrayList<>(1); + RoleInfo testRole = new RoleInfo(); + testRole.setUsername("nacos"); + testRole.setRole(AuthConstants.GLOBAL_ADMIN_ROLE); + roleInfoList.add(testRole); + + when(roleService.getRoles(anyString())).thenReturn(roleInfoList); + + assertThrows(IllegalArgumentException.class, () -> { + userController.deleteUser("nacos"); + }); + + } + + @Test + void testDeleteUser2() { + List roleInfoList = new ArrayList<>(1); + RoleInfo testRole = new RoleInfo(); + testRole.setUsername("nacos"); + testRole.setRole("testRole"); + roleInfoList.add(testRole); + + when(roleService.getRoles(anyString())).thenReturn(roleInfoList); + + RestResult result = (RestResult) userController.deleteUser("nacos"); + assertEquals(200, result.getCode()); + } + + @Test + void testUpdateUser1() throws IOException { + + when(authConfigs.isAuthEnabled()).thenReturn(false); + when(userDetailsService.getUserFromDatabase(anyString())).thenReturn(new User()); + MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); + MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); + RestResult result = (RestResult) userController.updateUser("nacos", "test", + mockHttpServletResponse, mockHttpServletRequest); + assertEquals(200, result.getCode()); + + } + + @Test + void testUpdateUser2() { + + when(authConfigs.isAuthEnabled()).thenReturn(false); + when(userDetailsService.getUserFromDatabase(anyString())).thenReturn(null); + MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); + MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); + + assertThrows(IllegalArgumentException.class, () -> { + userController.updateUser("nacos", "test", mockHttpServletResponse, mockHttpServletRequest); + }); + } + + @Test + void testUpdateUser3() throws IOException { + RequestContextHolder.getContext().getAuthContext().setIdentityContext(null); + when(authConfigs.isAuthEnabled()).thenReturn(true); + MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); + MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); + Object result = userController.updateUser("nacos", "test", mockHttpServletResponse, mockHttpServletRequest); + + assertNull(result); + assertEquals(HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus()); + + } + + @Test + void testUpdateUser4() throws IOException { + RequestContextHolder.getContext().getAuthContext().getIdentityContext() + .setParameter(AuthConstants.NACOS_USER_KEY, user); + when(authConfigs.isAuthEnabled()).thenReturn(true); + when(userDetailsService.getUserFromDatabase(anyString())).thenReturn(new User()); + MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); + MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); + RestResult result = (RestResult) userController.updateUser("nacos", "test", + mockHttpServletResponse, mockHttpServletRequest); + assertEquals(200, result.getCode()); + + } + + @Test + void testUpdateUser5() throws IOException, AccessException { + RequestContextHolder.getContext().getAuthContext().getIdentityContext() + .setParameter(AuthConstants.NACOS_USER_KEY, null); + when(authConfigs.isAuthEnabled()).thenReturn(true); + when(userDetailsService.getUserFromDatabase(anyString())).thenReturn(new User()); + when(authenticationManager.authenticate(any(MockHttpServletRequest.class))).thenReturn(user); + + MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); + MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); + RestResult result = (RestResult) userController.updateUser("nacos", "test", + mockHttpServletResponse, mockHttpServletRequest); + assertEquals(200, result.getCode()); + } + + @Test + void testUpdateUser6() throws IOException, AccessException { + RequestContextHolder.getContext().getAuthContext().getIdentityContext() + .setParameter(AuthConstants.NACOS_USER_KEY, null); + when(authConfigs.isAuthEnabled()).thenReturn(true); + when(authenticationManager.authenticate(any(MockHttpServletRequest.class))).thenReturn(null); + + MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); + MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); + Object result = userController.updateUser("nacos", "test", mockHttpServletResponse, mockHttpServletRequest); + + assertNull(result); + assertEquals(HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus()); + + } + + @Test + void testUpdateUser7() throws IOException, AccessException { + RequestContextHolder.getContext().getAuthContext().getIdentityContext() + .setParameter(AuthConstants.NACOS_USER_KEY, null); + when(authConfigs.isAuthEnabled()).thenReturn(true); + when(authenticationManager.authenticate(any(MockHttpServletRequest.class))).thenThrow( + new AccessException("test")); + + MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); + MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); + Object result = userController.updateUser("nacos", "test", mockHttpServletResponse, mockHttpServletRequest); + + assertNull(result); + assertEquals(HttpServletResponse.SC_FORBIDDEN, mockHttpServletResponse.getStatus()); + + } + + @Test + void testGetUsers() { + Page userPage = new Page<>(); + + when(userDetailsService.getUsersFromDatabase(anyInt(), anyInt(), anyString())).thenReturn(userPage); + + Page nacos = userController.getUsers(1, 10, "nacos"); + assertEquals(userPage, nacos); + } + + @Test + void testFuzzySearchUser() { + Page userPage = new Page<>(); + + when(userDetailsService.findUsersLike4Page(anyString(), anyInt(), anyInt())).thenReturn(userPage); + + Page nacos = userController.fuzzySearchUser(1, 10, "nacos"); + assertEquals(userPage, nacos); + } + + @Test + void testSearchUsersLikeUsername() { + List test = new ArrayList<>(1); + + when(userDetailsService.findUserLikeUsername(anyString())).thenReturn(test); + List list = userController.searchUsersLikeUsername("nacos"); + + assertEquals(test, list); + } + } diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/jwt/NacosJwtParserTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/jwt/NacosJwtParserTest.java index bf772cf429e..56f5fbb8238 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/jwt/NacosJwtParserTest.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/jwt/NacosJwtParserTest.java @@ -17,16 +17,16 @@ package com.alibaba.nacos.plugin.auth.impl.jwt; import com.alibaba.nacos.plugin.auth.exception.AccessException; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; import java.nio.charset.StandardCharsets; import java.util.Base64; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * NacosJwtParserTest. @@ -34,16 +34,16 @@ * @author Weizhan▪Yun * @date 2023/2/1 16:32 */ -@RunWith(MockitoJUnitRunner.class) -public class NacosJwtParserTest { +@ExtendWith(MockitoExtension.class) +class NacosJwtParserTest { @Test - public void testParseWithOriginKey() { + void testParseWithOriginKey() { new NacosJwtParser("SecretKey012345678901234567890123456789012345678901234567890123456789"); } @Test - public void testParseWith16Key() { + void testParseWith16Key() { Exception e = null; try { new NacosJwtParser("SecretKey0123456"); @@ -57,7 +57,7 @@ public void testParseWith16Key() { } @Test - public void testParseWith32Key() { + void testParseWith32Key() { NacosJwtParser parser = new NacosJwtParser(encode("SecretKey01234567890123456789012")); String token = parser.jwtBuilder().setUserName("nacos").setExpiredTime(100L).compact(); @@ -65,7 +65,7 @@ public void testParseWith32Key() { } @Test - public void testParseWith48Key() { + void testParseWith48Key() { NacosJwtParser parser = new NacosJwtParser(encode("SecretKey012345678901234567890120124568aa9012345")); String token = parser.jwtBuilder().setUserName("nacos").setExpiredTime(100L).compact(); @@ -73,18 +73,16 @@ public void testParseWith48Key() { } @Test - public void testParseWith64Key() { - NacosJwtParser parser = new NacosJwtParser( - encode("SecretKey012345678901234567SecretKey0123456789012345678901289012")); + void testParseWith64Key() { + NacosJwtParser parser = new NacosJwtParser(encode("SecretKey012345678901234567SecretKey0123456789012345678901289012")); String token = parser.jwtBuilder().setUserName("nacos").setExpiredTime(100L).compact(); assertTrue(token.startsWith(NacosSignatureAlgorithm.HS512.getHeader())); } @Test - public void testGetExpireTimeInSeconds() throws AccessException { - NacosJwtParser parser = new NacosJwtParser( - encode("SecretKey012345678901234567SecretKey0123456789012345678901289012")); + void testGetExpireTimeInSeconds() throws AccessException { + NacosJwtParser parser = new NacosJwtParser(encode("SecretKey012345678901234567SecretKey0123456789012345678901289012")); String token = parser.jwtBuilder().setUserName("nacos").setExpiredTime(100L).compact(); long expiredTimeSeconds = parser.getExpireTimeInSeconds(token); assertTrue(expiredTimeSeconds * 1000 - System.currentTimeMillis() > 0); diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/persistence/EmbeddedPermissionPersistServiceImplTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/persistence/EmbeddedPermissionPersistServiceImplTest.java index ab81f8256a8..7bde09eb054 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/persistence/EmbeddedPermissionPersistServiceImplTest.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/persistence/EmbeddedPermissionPersistServiceImplTest.java @@ -20,31 +20,35 @@ import com.alibaba.nacos.persistence.repository.embedded.EmbeddedStorageContextHolder; import com.alibaba.nacos.persistence.repository.embedded.operate.DatabaseOperate; import com.alibaba.nacos.persistence.repository.embedded.sql.ModifyRequest; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import java.lang.reflect.Field; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class EmbeddedPermissionPersistServiceImplTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class EmbeddedPermissionPersistServiceImplTest { @Mock private DatabaseOperate databaseOperate; private EmbeddedPermissionPersistServiceImpl embeddedPermissionPersistService; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { when(databaseOperate.queryOne(any(String.class), any(Object[].class), eq(Integer.class))).thenReturn(0); embeddedPermissionPersistService = new EmbeddedPermissionPersistServiceImpl(); Class embeddedPermissionPersistServiceClass = EmbeddedPermissionPersistServiceImpl.class; @@ -54,15 +58,15 @@ public void setUp() throws Exception { } @Test - public void testGetPermissions() { + void testGetPermissions() { String role = "role"; Page permissions = embeddedPermissionPersistService.getPermissions(role, 1, 10); - Assert.assertNotNull(permissions); + assertNotNull(permissions); } @Test - public void testAddPermission() { + void testAddPermission() { embeddedPermissionPersistService.addPermission("role", "resource", "action"); List currentSqlContext = EmbeddedStorageContextHolder.getCurrentSqlContext(); @@ -70,7 +74,7 @@ public void testAddPermission() { } @Test - public void testDeletePermission() { + void testDeletePermission() { embeddedPermissionPersistService.deletePermission("role", "resource", "action"); List currentSqlContext = EmbeddedStorageContextHolder.getCurrentSqlContext(); diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/persistence/EmbeddedRolePersistServiceImplTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/persistence/EmbeddedRolePersistServiceImplTest.java index 8d509433df4..f84e2d7ffa3 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/persistence/EmbeddedRolePersistServiceImplTest.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/persistence/EmbeddedRolePersistServiceImplTest.java @@ -20,30 +20,35 @@ import com.alibaba.nacos.persistence.repository.embedded.EmbeddedStorageContextHolder; import com.alibaba.nacos.persistence.repository.embedded.operate.DatabaseOperate; import com.alibaba.nacos.persistence.repository.embedded.sql.ModifyRequest; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import java.lang.reflect.Field; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class EmbeddedRolePersistServiceImplTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class EmbeddedRolePersistServiceImplTest { @Mock private DatabaseOperate databaseOperate; private EmbeddedRolePersistServiceImpl embeddedRolePersistService; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { when(databaseOperate.queryOne(any(String.class), any(Object[].class), eq(Integer.class))).thenReturn(0); embeddedRolePersistService = new EmbeddedRolePersistServiceImpl(); Class embeddedRolePersistServiceClass = EmbeddedRolePersistServiceImpl.class; @@ -53,41 +58,41 @@ public void setUp() throws Exception { } @Test - public void testGetRoles() { + void testGetRoles() { Page roles = embeddedRolePersistService.getRoles(1, 10); - Assert.assertNotNull(roles); + assertNotNull(roles); } @Test - public void testGetRolesByUserName() { + void testGetRolesByUserName() { Page page = embeddedRolePersistService.getRolesByUserNameAndRoleName("userName", "roleName", 1, 10); - Assert.assertNotNull(page); + assertNotNull(page); } @Test - public void testAddRole() { + void testAddRole() { embeddedRolePersistService.addRole("role", "userName"); List currentSqlContext = EmbeddedStorageContextHolder.getCurrentSqlContext(); - Assert.assertEquals(currentSqlContext.size(), 0); + assertEquals(0, currentSqlContext.size()); } @Test - public void testDeleteRole() { + void testDeleteRole() { embeddedRolePersistService.deleteRole("role"); embeddedRolePersistService.deleteRole("role", "userName"); List currentSqlContext = EmbeddedStorageContextHolder.getCurrentSqlContext(); - Assert.assertEquals(currentSqlContext.size(), 0); + assertEquals(0, currentSqlContext.size()); } @Test - public void testFindRolesLikeRoleName() { + void testFindRolesLikeRoleName() { List role = embeddedRolePersistService.findRolesLikeRoleName("role"); - Assert.assertEquals(role.size(), 0); + assertEquals(0, role.size()); } } diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/persistence/EmbeddedUserPersistServiceImplTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/persistence/EmbeddedUserPersistServiceImplTest.java index 8ec8cdfc2bb..17b76a07270 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/persistence/EmbeddedUserPersistServiceImplTest.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/persistence/EmbeddedUserPersistServiceImplTest.java @@ -18,31 +18,37 @@ import com.alibaba.nacos.persistence.model.Page; import com.alibaba.nacos.persistence.repository.embedded.operate.DatabaseOperate; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import java.lang.reflect.Field; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class EmbeddedUserPersistServiceImplTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class EmbeddedUserPersistServiceImplTest { @Mock private DatabaseOperate databaseOperate; private EmbeddedUserPersistServiceImpl embeddedUserPersistService; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { when(databaseOperate.queryOne(any(String.class), any(Object[].class), eq(Integer.class))).thenReturn(0); embeddedUserPersistService = new EmbeddedUserPersistServiceImpl(); Class embeddedUserPersistServiceClass = EmbeddedUserPersistServiceImpl.class; @@ -53,43 +59,43 @@ public void setUp() throws Exception { } @Test - public void testCreateUser() { + void testCreateUser() { embeddedUserPersistService.createUser("username", "password"); Mockito.verify(databaseOperate).blockUpdate(); } @Test - public void testDeleteUser() { + void testDeleteUser() { embeddedUserPersistService.deleteUser("username"); Mockito.verify(databaseOperate).blockUpdate(); } @Test - public void testUpdateUserPassword() { + void testUpdateUserPassword() { embeddedUserPersistService.updateUserPassword("username", "password"); Mockito.verify(databaseOperate).blockUpdate(); } @Test - public void testFindUserByUsername() { + void testFindUserByUsername() { User user = embeddedUserPersistService.findUserByUsername("username"); - Assert.assertNull(user); + assertNull(user); } @Test - public void testGetUsers() { + void testGetUsers() { Page users = embeddedUserPersistService.getUsers(1, 10, "nacos"); - Assert.assertNotNull(users); + assertNotNull(users); } @Test - public void testFindUserLikeUsername() { + void testFindUserLikeUsername() { List username = embeddedUserPersistService.findUserLikeUsername("username"); - Assert.assertEquals(username.size(), 0); + assertEquals(0, username.size()); } } diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/persistence/ExternalPermissionPersistServiceImplTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/persistence/ExternalPermissionPersistServiceImplTest.java index 15aea1df7c8..e7a1f230933 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/persistence/ExternalPermissionPersistServiceImplTest.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/persistence/ExternalPermissionPersistServiceImplTest.java @@ -20,24 +20,28 @@ import com.alibaba.nacos.persistence.datasource.DataSourceService; import com.alibaba.nacos.persistence.datasource.DynamicDataSource; import com.alibaba.nacos.persistence.model.Page; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.jdbc.core.JdbcTemplate; import java.lang.reflect.Field; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class ExternalPermissionPersistServiceImplTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class ExternalPermissionPersistServiceImplTest { @Mock private JdbcTemplate jdbcTemplate; @@ -51,8 +55,8 @@ public class ExternalPermissionPersistServiceImplTest { private ExternalPermissionPersistServiceImpl externalPermissionPersistService; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { externalPermissionPersistService = new ExternalPermissionPersistServiceImpl(); when(jdbcTemplate.queryForObject(any(), any(), eq(Integer.class))).thenReturn(0); when(dataSourceService.getJdbcTemplate()).thenReturn(jdbcTemplate); @@ -65,8 +69,8 @@ public void setUp() throws Exception { externalPermissionPersistService.init(); } - @After - public void tearDown() throws NoSuchFieldException, IllegalAccessException { + @AfterEach + void tearDown() throws NoSuchFieldException, IllegalAccessException { DatasourceConfiguration.setEmbeddedStorage(embeddedStorageCache); Field datasourceField = DynamicDataSource.class.getDeclaredField("basicDataSourceService"); datasourceField.setAccessible(true); @@ -74,13 +78,13 @@ public void tearDown() throws NoSuchFieldException, IllegalAccessException { } @Test - public void testGetPermissions() { + void testGetPermissions() { Page role = externalPermissionPersistService.getPermissions("role", 1, 10); - Assert.assertNotNull(role); + assertNotNull(role); } @Test - public void testAddPermission() { + void testAddPermission() { String sql = "INSERT INTO permissions (role, resource, action) VALUES (?, ?, ?)"; externalPermissionPersistService.addPermission("role", "resource", "action"); @@ -88,7 +92,7 @@ public void testAddPermission() { } @Test - public void testDeletePermission() { + void testDeletePermission() { String sql = "DELETE FROM permissions WHERE role=? AND resource=? AND action=?"; externalPermissionPersistService.deletePermission("role", "resource", "action"); diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/persistence/ExternalRolePersistServiceImplTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/persistence/ExternalRolePersistServiceImplTest.java index ec475923529..5f3baddd597 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/persistence/ExternalRolePersistServiceImplTest.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/persistence/ExternalRolePersistServiceImplTest.java @@ -20,25 +20,30 @@ import com.alibaba.nacos.persistence.datasource.DataSourceService; import com.alibaba.nacos.persistence.datasource.DynamicDataSource; import com.alibaba.nacos.persistence.model.Page; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.jdbc.core.JdbcTemplate; import java.lang.reflect.Field; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class ExternalRolePersistServiceImplTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class ExternalRolePersistServiceImplTest { @Mock private JdbcTemplate jdbcTemplate; @@ -52,8 +57,8 @@ public class ExternalRolePersistServiceImplTest { private ExternalRolePersistServiceImpl externalRolePersistService; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { externalRolePersistService = new ExternalRolePersistServiceImpl(); when(jdbcTemplate.queryForObject(any(), any(), eq(Integer.class))).thenReturn(0); when(dataSourceService.getJdbcTemplate()).thenReturn(jdbcTemplate); @@ -66,8 +71,8 @@ public void setUp() throws Exception { externalRolePersistService.init(); } - @After - public void tearDown() throws NoSuchFieldException, IllegalAccessException { + @AfterEach + void tearDown() throws NoSuchFieldException, IllegalAccessException { DatasourceConfiguration.setEmbeddedStorage(embeddedStorageCache); Field datasourceField = DynamicDataSource.class.getDeclaredField("basicDataSourceService"); datasourceField.setAccessible(true); @@ -75,21 +80,20 @@ public void tearDown() throws NoSuchFieldException, IllegalAccessException { } @Test - public void testGetRoles() { + void testGetRoles() { Page roles = externalRolePersistService.getRoles(1, 10); - Assert.assertNotNull(roles); + assertNotNull(roles); } @Test - public void testGetRolesByUserName() { - Page userName = externalRolePersistService - .getRolesByUserNameAndRoleName("userName", "roleName", 1, 10); - Assert.assertNotNull(userName); + void testGetRolesByUserName() { + Page userName = externalRolePersistService.getRolesByUserNameAndRoleName("userName", "roleName", 1, 10); + assertNotNull(userName); } @Test - public void testAddRole() { + void testAddRole() { externalRolePersistService.addRole("role", "userName"); String sql = "INSERT INTO roles (role, username) VALUES (?, ?)"; @@ -97,7 +101,7 @@ public void testAddRole() { } @Test - public void testDeleteRole() { + void testDeleteRole() { externalRolePersistService.deleteRole("role"); String sql = "DELETE FROM roles WHERE role=?"; @@ -110,9 +114,9 @@ public void testDeleteRole() { } @Test - public void testFindRolesLikeRoleName() { + void testFindRolesLikeRoleName() { List role = externalRolePersistService.findRolesLikeRoleName("role"); - Assert.assertEquals(role.size(), 0); + assertEquals(0, role.size()); } } diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/persistence/ExternalUserPersistServiceImplTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/persistence/ExternalUserPersistServiceImplTest.java index 968da1ae69f..ee2cc8fd81a 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/persistence/ExternalUserPersistServiceImplTest.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/persistence/ExternalUserPersistServiceImplTest.java @@ -20,25 +20,31 @@ import com.alibaba.nacos.persistence.datasource.DataSourceService; import com.alibaba.nacos.persistence.datasource.DynamicDataSource; import com.alibaba.nacos.persistence.model.Page; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.jdbc.core.JdbcTemplate; import java.lang.reflect.Field; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class ExternalUserPersistServiceImplTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class ExternalUserPersistServiceImplTest { @Mock private JdbcTemplate jdbcTemplate; @@ -52,8 +58,8 @@ public class ExternalUserPersistServiceImplTest { private ExternalUserPersistServiceImpl externalUserPersistService; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { externalUserPersistService = new ExternalUserPersistServiceImpl(); when(jdbcTemplate.queryForObject(any(), any(), eq(Integer.class))).thenReturn(0); when(dataSourceService.getJdbcTemplate()).thenReturn(jdbcTemplate); @@ -66,8 +72,8 @@ public void setUp() throws Exception { externalUserPersistService.init(); } - @After - public void tearDown() throws NoSuchFieldException, IllegalAccessException { + @AfterEach + void tearDown() throws NoSuchFieldException, IllegalAccessException { DatasourceConfiguration.setEmbeddedStorage(embeddedStorageCache); Field datasourceField = DynamicDataSource.class.getDeclaredField("basicDataSourceService"); datasourceField.setAccessible(true); @@ -75,7 +81,7 @@ public void tearDown() throws NoSuchFieldException, IllegalAccessException { } @Test - public void testCreateUser() { + void testCreateUser() { externalUserPersistService.createUser("username", "password"); String sql = "INSERT INTO users (username, password, enabled) VALUES (?, ?, ?)"; @@ -83,7 +89,7 @@ public void testCreateUser() { } @Test - public void testDeleteUser() { + void testDeleteUser() { externalUserPersistService.deleteUser("username"); String sql = "DELETE FROM users WHERE username=?"; @@ -91,7 +97,7 @@ public void testDeleteUser() { } @Test - public void testUpdateUserPassword() { + void testUpdateUserPassword() { externalUserPersistService.updateUserPassword("username", "password"); String sql = "UPDATE users SET password = ? WHERE username=?"; @@ -99,23 +105,23 @@ public void testUpdateUserPassword() { } @Test - public void testFindUserByUsername() { + void testFindUserByUsername() { User username = externalUserPersistService.findUserByUsername("username"); - Assert.assertNull(username); + assertNull(username); } @Test - public void testGetUsers() { + void testGetUsers() { Page users = externalUserPersistService.getUsers(1, 10, "nacos"); - Assert.assertNotNull(users); + assertNotNull(users); } @Test - public void testFindUserLikeUsername() { + void testFindUserLikeUsername() { List username = externalUserPersistService.findUserLikeUsername("username"); - Assert.assertEquals(username.size(), 0); + assertEquals(0, username.size()); } } diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/roles/NacosRoleServiceImplTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/roles/NacosRoleServiceImplTest.java index 7ce80170817..aea87556a72 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/roles/NacosRoleServiceImplTest.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/roles/NacosRoleServiceImplTest.java @@ -28,18 +28,23 @@ import com.alibaba.nacos.plugin.auth.impl.persistence.User; import com.alibaba.nacos.plugin.auth.impl.users.NacosUser; import com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetailsServiceImpl; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collections; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * NacosRoleServiceImpl Test. * @@ -48,8 +53,10 @@ * @Date: 2022/8/16 17:31 * @Description: TODO */ -@RunWith(MockitoJUnitRunner.class) -public class NacosRoleServiceImplTest { +@ExtendWith(MockitoExtension.class) +class NacosRoleServiceImplTest { + + Class nacosRoleServiceClass; @Mock private AuthConfigs authConfigs; @@ -66,10 +73,8 @@ public class NacosRoleServiceImplTest { @Mock private NacosRoleServiceImpl nacosRoleService; - Class nacosRoleServiceClass; - - @Before - public void setup() throws Exception { + @BeforeEach + void setup() throws Exception { nacosRoleService = new NacosRoleServiceImpl(); nacosRoleServiceClass = NacosRoleServiceImpl.class; Field authConfigsFile = nacosRoleServiceClass.getDeclaredField("authConfigs"); @@ -90,107 +95,105 @@ public void setup() throws Exception { } @Test - public void reload() throws Exception { + void reload() throws Exception { Method reload = nacosRoleServiceClass.getDeclaredMethod("reload"); reload.setAccessible(true); reload.invoke(nacosRoleService); } @Test - public void hasPermission() { + void hasPermission() { Permission permission = new Permission(); permission.setAction("rw"); permission.setResource(Resource.EMPTY_RESOURCE); NacosUser nacosUser = new NacosUser(); nacosUser.setUserName("nacos"); boolean res = nacosRoleService.hasPermission(nacosUser, permission); - Assert.assertFalse(res); + assertFalse(res); Permission permission2 = new Permission(); permission2.setAction("rw"); Resource resource = new Resource("public", "group", AuthConstants.UPDATE_PASSWORD_ENTRY_POINT, "rw", null); permission2.setResource(resource); boolean res2 = nacosRoleService.hasPermission(nacosUser, permission2); - Assert.assertTrue(res2); + assertTrue(res2); } @Test - public void getRoles() { + void getRoles() { List nacos = nacosRoleService.getRoles("role-admin"); - Assert.assertEquals(nacos, Collections.emptyList()); + assertEquals(nacos, Collections.emptyList()); } @Test - public void getRolesFromDatabase() { - Page roleInfoPage = nacosRoleService.getRolesFromDatabase("nacos", "ROLE_ADMIN", 1, - Integer.MAX_VALUE); - Assert.assertEquals(roleInfoPage.getTotalCount(), 0); + void getRolesFromDatabase() { + Page roleInfoPage = nacosRoleService.getRolesFromDatabase("nacos", "ROLE_ADMIN", 1, Integer.MAX_VALUE); + assertEquals(0, roleInfoPage.getTotalCount()); } @Test - public void getPermissions() { + void getPermissions() { boolean cachingEnabled = authConfigs.isCachingEnabled(); - Assert.assertFalse(cachingEnabled); + assertFalse(cachingEnabled); List permissions = nacosRoleService.getPermissions("role-admin"); - Assert.assertEquals(permissions, Collections.emptyList()); + assertEquals(permissions, Collections.emptyList()); } @Test - public void getPermissionsByRoleFromDatabase() { - Page permissionsByRoleFromDatabase = nacosRoleService.getPermissionsByRoleFromDatabase( - "role-admin", 1, Integer.MAX_VALUE); - Assert.assertNull(permissionsByRoleFromDatabase); + void getPermissionsByRoleFromDatabase() { + Page permissionsByRoleFromDatabase = nacosRoleService.getPermissionsByRoleFromDatabase("role-admin", 1, + Integer.MAX_VALUE); + assertNull(permissionsByRoleFromDatabase); } @Test - public void addRole() { + void addRole() { String username = "nacos"; User userFromDatabase = userDetailsService.getUserFromDatabase(username); - Assert.assertNull(userFromDatabase); + assertNull(userFromDatabase); try { nacosRoleService.addRole("role-admin", "nacos"); } catch (Exception e) { - Assert.assertTrue(e.getMessage().contains("user 'nacos' not found!")); + assertTrue(e.getMessage().contains("user 'nacos' not found!")); } } @Test - public void deleteRole() { + void deleteRole() { try { nacosRoleService.deleteRole("role-admin"); } catch (Exception e) { - Assert.assertNull(e); + assertNull(e); } } @Test - public void getPermissionsFromDatabase() { - Page permissionsFromDatabase = nacosRoleService.getPermissionsFromDatabase("role-admin", 1, - Integer.MAX_VALUE); - Assert.assertEquals(permissionsFromDatabase.getTotalCount(), 0); + void getPermissionsFromDatabase() { + Page permissionsFromDatabase = nacosRoleService.getPermissionsFromDatabase("role-admin", 1, Integer.MAX_VALUE); + assertEquals(0, permissionsFromDatabase.getTotalCount()); } @Test - public void addPermission() { + void addPermission() { try { nacosRoleService.addPermission("role-admin", "", "rw"); } catch (Exception e) { - Assert.assertTrue(e.getMessage().contains("role role-admin not found!")); + assertTrue(e.getMessage().contains("role role-admin not found!")); } } @Test - public void findRolesLikeRoleName() { + void findRolesLikeRoleName() { List rolesLikeRoleName = rolePersistService.findRolesLikeRoleName("role-admin"); - Assert.assertEquals(rolesLikeRoleName, Collections.emptyList()); + assertEquals(rolesLikeRoleName, Collections.emptyList()); } @Test - public void joinResource() throws Exception { + void joinResource() throws Exception { Method method = nacosRoleServiceClass.getDeclaredMethod("joinResource", Resource.class); method.setAccessible(true); Resource resource = new Resource("public", "group", AuthConstants.UPDATE_PASSWORD_ENTRY_POINT, "rw", null); Object invoke = method.invoke(nacosRoleService, new Resource[] {resource}); - Assert.assertNotNull(invoke); + assertNotNull(invoke); } } diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/token/TokenManagerDelegateTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/token/TokenManagerDelegateTest.java index 0074f9dfae8..815eb17d54f 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/token/TokenManagerDelegateTest.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/token/TokenManagerDelegateTest.java @@ -20,16 +20,20 @@ import com.alibaba.nacos.plugin.auth.impl.token.impl.CachedJwtTokenManager; import com.alibaba.nacos.plugin.auth.impl.token.impl.JwtTokenManager; import com.alibaba.nacos.plugin.auth.impl.users.NacosUser; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.security.core.Authentication; import java.lang.reflect.Field; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; @@ -38,8 +42,10 @@ * * @author majorhe */ -@RunWith(MockitoJUnitRunner.class) -public class TokenManagerDelegateTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class TokenManagerDelegateTest { private TokenManagerDelegate tokenManagerDelegate; @@ -55,8 +61,8 @@ public class TokenManagerDelegateTest { @Mock private NacosUser user; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { tokenManagerDelegate = new TokenManagerDelegate(); injectObject("jwtTokenManager", jwtTokenManager); injectObject("cachedJwtTokenManager", cachedJwtTokenManager); @@ -70,38 +76,38 @@ public void setUp() throws Exception { } @Test - public void testCreateToken1() throws AccessException { - Assert.assertEquals("token", tokenManagerDelegate.createToken(authentication)); + void testCreateToken1() throws AccessException { + assertEquals("token", tokenManagerDelegate.createToken(authentication)); } @Test - public void testCreateToken2() throws AccessException { - Assert.assertEquals("token", tokenManagerDelegate.createToken("nacos")); + void testCreateToken2() throws AccessException { + assertEquals("token", tokenManagerDelegate.createToken("nacos")); } @Test - public void testGetAuthentication() throws AccessException { - Assert.assertNotNull(tokenManagerDelegate.getAuthentication("token")); + void testGetAuthentication() throws AccessException { + assertNotNull(tokenManagerDelegate.getAuthentication("token")); } @Test - public void testValidateToken() throws AccessException { + void testValidateToken() throws AccessException { tokenManagerDelegate.validateToken("token"); } @Test - public void testParseToken() throws AccessException { - Assert.assertNotNull(tokenManagerDelegate.parseToken("token")); + void testParseToken() throws AccessException { + assertNotNull(tokenManagerDelegate.parseToken("token")); } @Test - public void testGetTokenTtlInSeconds() throws AccessException { - Assert.assertTrue(tokenManagerDelegate.getTokenTtlInSeconds("token") > 0); + void testGetTokenTtlInSeconds() throws AccessException { + assertTrue(tokenManagerDelegate.getTokenTtlInSeconds("token") > 0); } @Test - public void testGetTokenValidityInSeconds() throws AccessException { - Assert.assertTrue(tokenManagerDelegate.getTokenValidityInSeconds() > 0); + void testGetTokenValidityInSeconds() throws AccessException { + assertTrue(tokenManagerDelegate.getTokenValidityInSeconds() > 0); } private void injectObject(String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException { diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/token/impl/CachedJwtTokenManagerTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/token/impl/CachedJwtTokenManagerTest.java index 6cf2bd30bef..9875a5b316a 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/token/impl/CachedJwtTokenManagerTest.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/token/impl/CachedJwtTokenManagerTest.java @@ -18,16 +18,20 @@ import com.alibaba.nacos.plugin.auth.exception.AccessException; import com.alibaba.nacos.plugin.auth.impl.users.NacosUser; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.security.core.Authentication; import java.lang.reflect.Field; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; @@ -36,8 +40,10 @@ * * @author Majorhe */ -@RunWith(MockitoJUnitRunner.class) -public class CachedJwtTokenManagerTest { +@ExtendWith(MockitoExtension.class) +// todo remove this +@MockitoSettings(strictness = Strictness.LENIENT) +class CachedJwtTokenManagerTest { private CachedJwtTokenManager cachedJwtTokenManager; @@ -50,8 +56,8 @@ public class CachedJwtTokenManagerTest { @Mock private NacosUser user; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { cachedJwtTokenManager = new CachedJwtTokenManager(); injectObject("jwtTokenManager", jwtTokenManager); when(jwtTokenManager.getTokenValidityInSeconds()).thenReturn(100L); @@ -64,38 +70,38 @@ public void setUp() throws Exception { } @Test - public void testCreateToken1() throws AccessException { - Assert.assertEquals("token", cachedJwtTokenManager.createToken(authentication)); + void testCreateToken1() throws AccessException { + assertEquals("token", cachedJwtTokenManager.createToken(authentication)); } @Test - public void testCreateToken2() throws AccessException { - Assert.assertEquals("token", cachedJwtTokenManager.createToken("nacos")); + void testCreateToken2() throws AccessException { + assertEquals("token", cachedJwtTokenManager.createToken("nacos")); } @Test - public void testGetAuthentication() throws AccessException { - Assert.assertNotNull(cachedJwtTokenManager.getAuthentication("token")); + void testGetAuthentication() throws AccessException { + assertNotNull(cachedJwtTokenManager.getAuthentication("token")); } @Test - public void testValidateToken() throws AccessException { + void testValidateToken() throws AccessException { cachedJwtTokenManager.validateToken("token"); } @Test - public void testParseToken() throws AccessException { - Assert.assertNotNull(cachedJwtTokenManager.parseToken("token")); + void testParseToken() throws AccessException { + assertNotNull(cachedJwtTokenManager.parseToken("token")); } @Test - public void testGetTokenTtlInSeconds() throws AccessException { - Assert.assertTrue(cachedJwtTokenManager.getTokenTtlInSeconds("token") > 0); + void testGetTokenTtlInSeconds() throws AccessException { + assertTrue(cachedJwtTokenManager.getTokenTtlInSeconds("token") > 0); } @Test - public void testGetTokenValidityInSeconds() { - Assert.assertTrue(cachedJwtTokenManager.getTokenValidityInSeconds() > 0); + void testGetTokenValidityInSeconds() { + assertTrue(cachedJwtTokenManager.getTokenValidityInSeconds() > 0); } private void injectObject(String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException { diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/token/impl/JwtTokenManagerTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/token/impl/JwtTokenManagerTest.java index 6942f028e42..8715e9dd413 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/token/impl/JwtTokenManagerTest.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/token/impl/JwtTokenManagerTest.java @@ -21,12 +21,11 @@ import com.alibaba.nacos.plugin.auth.impl.constant.AuthConstants; import com.alibaba.nacos.plugin.auth.impl.jwt.NacosJwtParser; import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.env.MockEnvironment; import org.springframework.security.core.Authentication; @@ -34,38 +33,40 @@ import java.util.Base64; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class JwtTokenManagerTest { +@ExtendWith(MockitoExtension.class) +class JwtTokenManagerTest { private JwtTokenManager jwtTokenManager; @Mock private AuthConfigs authConfigs; - @Before - public void setUp() { + @BeforeEach + void setUp() { when(authConfigs.isAuthEnabled()).thenReturn(true); MockEnvironment mockEnvironment = new MockEnvironment(); - mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, Base64.getEncoder().encodeToString( - "SecretKey0123$567890$234567890123456789012345678901234567890123456789" - .getBytes(StandardCharsets.UTF_8))); - mockEnvironment - .setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS, AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString()); + mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, Base64.getEncoder() + .encodeToString("SecretKey0123$567890$234567890123456789012345678901234567890123456789".getBytes(StandardCharsets.UTF_8))); + mockEnvironment.setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS, AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString()); EnvUtil.setEnvironment(mockEnvironment); jwtTokenManager = new JwtTokenManager(authConfigs); } @Test - public void testCreateTokenAndSecretKeyWithoutSpecialSymbol() throws AccessException { + void testCreateTokenAndSecretKeyWithoutSpecialSymbol() throws AccessException { createToken("SecretKey0123567890234567890123456789012345678901234567890123456789"); } @Test - public void testCreateTokenAndSecretKeyWithSpecialSymbol() throws AccessException { + void testCreateTokenAndSecretKeyWithSpecialSymbol() throws AccessException { createToken("SecretKey01234@#!5678901234567890123456789012345678901234567890123456789"); } @@ -73,72 +74,102 @@ private void createToken(String secretKey) throws AccessException { MockEnvironment mockEnvironment = new MockEnvironment(); mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, Base64.getEncoder().encodeToString(secretKey.getBytes(StandardCharsets.UTF_8))); - mockEnvironment - .setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS, AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString()); + mockEnvironment.setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS, AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString()); EnvUtil.setEnvironment(mockEnvironment); JwtTokenManager jwtTokenManager = new JwtTokenManager(authConfigs); String nacosToken = jwtTokenManager.createToken("nacos"); - Assert.assertNotNull(nacosToken); + assertNotNull(nacosToken); jwtTokenManager.validateToken(nacosToken); } @Test - public void getAuthentication() throws AccessException { + void getAuthentication() throws AccessException { String nacosToken = jwtTokenManager.createToken("nacos"); Authentication authentication = jwtTokenManager.getAuthentication(nacosToken); - Assert.assertNotNull(authentication); + assertNotNull(authentication); } @Test - public void testInvalidSecretKey() { - Assert.assertThrows(IllegalArgumentException.class, () -> createToken("0123456789ABCDEF0123456789ABCDE")); + void testInvalidSecretKey() { + assertThrows(IllegalArgumentException.class, () -> createToken("0123456789ABCDEF0123456789ABCDE")); } @Test - public void testGetTokenTtlInSeconds() throws AccessException { - Assert.assertTrue(jwtTokenManager.getTokenTtlInSeconds(jwtTokenManager.createToken("nacos")) > 0); + void testGetTokenTtlInSeconds() throws AccessException { + assertTrue(jwtTokenManager.getTokenTtlInSeconds(jwtTokenManager.createToken("nacos")) > 0); } @Test - public void testGetExpiredTimeInSeconds() throws AccessException { - Assert.assertTrue(jwtTokenManager.getExpiredTimeInSeconds(jwtTokenManager.createToken("nacos")) > 0); + void testGetExpiredTimeInSeconds() throws AccessException { + assertTrue(jwtTokenManager.getExpiredTimeInSeconds(jwtTokenManager.createToken("nacos")) > 0); } @Test - public void testCreateTokenWhenDisableAuth() { + void testGetTokenTtlInSecondsWhenAuthDisabled() throws AccessException { when(authConfigs.isAuthEnabled()).thenReturn(false); + // valid secret key + String ttl = EnvUtil.getProperty(AuthConstants.TOKEN_EXPIRE_SECONDS); + assertEquals(Integer.parseInt(ttl), jwtTokenManager.getTokenTtlInSeconds(jwtTokenManager.createToken("nacos"))); + // invalid secret key + MockEnvironment mockEnvironment = new MockEnvironment(); + mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, ""); + EnvUtil.setEnvironment(mockEnvironment); + jwtTokenManager = new JwtTokenManager(authConfigs); + assertEquals(Integer.parseInt(ttl), jwtTokenManager.getTokenTtlInSeconds(jwtTokenManager.createToken("nacos"))); + } + + @Test + void testCreateTokenWhenDisableAuthAndSecretKeyIsBlank() { + when(authConfigs.isAuthEnabled()).thenReturn(false); + MockEnvironment mockEnvironment = new MockEnvironment(); + mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, ""); + mockEnvironment.setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS, AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString()); + + EnvUtil.setEnvironment(mockEnvironment); jwtTokenManager = new JwtTokenManager(authConfigs); assertEquals("AUTH_DISABLED", jwtTokenManager.createToken("nacos")); } @Test - public void testNacosJwtParser() throws AccessException { + void testCreateTokenWhenDisableAuthAndSecretKeyIsNotBlank() throws AccessException { + when(authConfigs.isAuthEnabled()).thenReturn(false); + MockEnvironment mockEnvironment = new MockEnvironment(); + String tmpKey = "SecretKey0123567890234567890123456789012345678901234567890123456789"; + mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, + Base64.getEncoder().encodeToString(tmpKey.getBytes(StandardCharsets.UTF_8))); + mockEnvironment.setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS, AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString()); + EnvUtil.setEnvironment(mockEnvironment); + jwtTokenManager = new JwtTokenManager(authConfigs); + String token = jwtTokenManager.createToken("nacos"); + assertNotEquals("AUTH_DISABLED", token); + jwtTokenManager.validateToken(token); + } + + @Test + void testNacosJwtParser() throws AccessException { String secretKey = "SecretKey0123$567890$234567890123456789012345678901234567890123456789"; MockEnvironment mockEnvironment = new MockEnvironment(); mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, Base64.getEncoder().encodeToString(secretKey.getBytes(StandardCharsets.UTF_8))); - mockEnvironment - .setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS, AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString()); + mockEnvironment.setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS, AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString()); EnvUtil.setEnvironment(mockEnvironment); JwtTokenManager jwtTokenManager = new JwtTokenManager(authConfigs); String nacosToken = jwtTokenManager.createToken("nacos"); - Assert.assertNotNull(nacosToken); + assertNotNull(nacosToken); System.out.println("oldToken: " + nacosToken); jwtTokenManager.validateToken(nacosToken); - NacosJwtParser nacosJwtParser = new NacosJwtParser( - Base64.getEncoder().encodeToString(secretKey.getBytes(StandardCharsets.UTF_8))); + NacosJwtParser nacosJwtParser = new NacosJwtParser(Base64.getEncoder().encodeToString(secretKey.getBytes(StandardCharsets.UTF_8))); //check old token nacosJwtParser.parse(nacosToken); //create new token - String newToken = nacosJwtParser.jwtBuilder().setUserName("nacos").setExpiredTime(TimeUnit.DAYS.toSeconds(10L)) - .compact(); + String newToken = nacosJwtParser.jwtBuilder().setUserName("nacos").setExpiredTime(TimeUnit.DAYS.toSeconds(10L)).compact(); System.out.println("newToken: " + newToken); jwtTokenManager.validateToken(newToken); } diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/utils/Base64DecodeTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/utils/Base64DecodeTest.java index ea3e7fc9e54..f77f1c62dce 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/utils/Base64DecodeTest.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/utils/Base64DecodeTest.java @@ -16,8 +16,9 @@ package com.alibaba.nacos.plugin.auth.impl.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; /** * Base64Decoder test. @@ -25,22 +26,22 @@ * @author xYohn * @date 2023/8/8 */ -public class Base64DecodeTest { +class Base64DecodeTest { @Test - public void testStandardDecode() { + void testStandardDecode() { String origin = "aGVsbG8sbmFjb3MhdGVzdEJhc2U2NGVuY29kZQ=="; String expectDecodeOrigin = "hello,nacos!testBase64encode"; byte[] decodeOrigin = Base64Decode.decode(origin); - Assert.assertArrayEquals(decodeOrigin, expectDecodeOrigin.getBytes()); + assertArrayEquals(decodeOrigin, expectDecodeOrigin.getBytes()); } @Test - public void testNotStandardDecode() { + void testNotStandardDecode() { String notStandardOrigin = "SecretKey012345678901234567890123456789012345678901234567890123456789"; byte[] decodeNotStandardOrigin = Base64Decode.decode(notStandardOrigin); String truncationOrigin = "SecretKey01234567890123456789012345678901234567890123456789012345678"; byte[] decodeTruncationOrigin = Base64Decode.decode(truncationOrigin); - Assert.assertArrayEquals(decodeNotStandardOrigin, decodeTruncationOrigin); + assertArrayEquals(decodeNotStandardOrigin, decodeTruncationOrigin); } } diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/utils/PasswordEncoderUtilTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/utils/PasswordEncoderUtilTest.java index 8c101329fbb..4f316ea0ba8 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/utils/PasswordEncoderUtilTest.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/utils/PasswordEncoderUtilTest.java @@ -16,36 +16,38 @@ package com.alibaba.nacos.plugin.auth.impl.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * PasswordEncoderUtil test. + * * @ClassName: PasswordEncoderUtilTest * @Author: ChenHao26 * @Date: 2022/8/17 01:25 */ -public class PasswordEncoderUtilTest { +class PasswordEncoderUtilTest { /** * encode test. */ @Test - public void encode() { + void encode() { String str = PasswordEncoderUtil.encode("nacos"); String str2 = PasswordEncoderUtil.encode("nacos"); - Assert.assertNotEquals(str2, str); + assertNotEquals(str2, str); } @Test - public void matches() { - Boolean result1 = PasswordEncoderUtil.matches("nacos", - "$2a$10$MK2dspqy7MKcCU63x8PoI.vTGXYxhzTmjWGJ21T.WX8thVsw0K2mO"); - Assert.assertTrue(result1); - Boolean result2 = PasswordEncoderUtil.matches("nacos", - "$2a$10$MK2dspqy7MKcCU63x8PoI.vTGXcxhzTmjWGJ21T.WX8thVsw0K2mO"); - Assert.assertFalse(result2); + void matches() { + Boolean result1 = PasswordEncoderUtil.matches("nacos", "$2a$10$MK2dspqy7MKcCU63x8PoI.vTGXYxhzTmjWGJ21T.WX8thVsw0K2mO"); + assertTrue(result1); + Boolean result2 = PasswordEncoderUtil.matches("nacos", "$2a$10$MK2dspqy7MKcCU63x8PoI.vTGXcxhzTmjWGJ21T.WX8thVsw0K2mO"); + assertFalse(result2); Boolean matches = PasswordEncoderUtil.matches("nacos", PasswordEncoderUtil.encode("nacos")); - Assert.assertTrue(matches); + assertTrue(matches); } } diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/utils/PasswordGeneratorUtilTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/utils/PasswordGeneratorUtilTest.java index dee12f94c9f..10558e1f66d 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/utils/PasswordGeneratorUtilTest.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/utils/PasswordGeneratorUtilTest.java @@ -16,18 +16,19 @@ package com.alibaba.nacos.plugin.auth.impl.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class PasswordGeneratorUtilTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class PasswordGeneratorUtilTest { /** * generatePwd test. */ @Test - public void generatePwd() { + void generatePwd() { String pwd = PasswordGeneratorUtil.generateRandomPassword(); - Assert.assertEquals(8, pwd.length()); + assertEquals(8, pwd.length()); } } diff --git a/plugin-default-impl/nacos-default-control-plugin/src/main/java/com/alibaba/nacos/plugin/control/impl/NacosConnectionControlManager.java b/plugin-default-impl/nacos-default-control-plugin/src/main/java/com/alibaba/nacos/plugin/control/impl/NacosConnectionControlManager.java index d6d975c3f0e..f52c3e283bc 100644 --- a/plugin-default-impl/nacos-default-control-plugin/src/main/java/com/alibaba/nacos/plugin/control/impl/NacosConnectionControlManager.java +++ b/plugin-default-impl/nacos-default-control-plugin/src/main/java/com/alibaba/nacos/plugin/control/impl/NacosConnectionControlManager.java @@ -58,6 +58,11 @@ public ConnectionCheckResponse check(ConnectionCheckRequest connectionCheckReque connectionCheckResponse.setSuccess(true); connectionCheckResponse.setCode(ConnectionCheckCode.PASS_BY_TOTAL); int totalCountLimit = connectionControlRule.getCountLimit(); + // If totalCountLimit less than 0, no limit is applied. + if (totalCountLimit < 0) { + return connectionCheckResponse; + } + // Get total connection from metrics Map metricsTotalCount = metricsCollectorList.stream().collect( Collectors.toMap(ConnectionMetricsCollector::getName, ConnectionMetricsCollector::getTotalCount)); diff --git a/plugin-default-impl/nacos-default-control-plugin/src/test/java/com/alibaba/nacos/plugin/control/impl/NacosConnectionControlManagerTest.java b/plugin-default-impl/nacos-default-control-plugin/src/test/java/com/alibaba/nacos/plugin/control/impl/NacosConnectionControlManagerTest.java index c3cb4f5c24b..f78822fe53b 100644 --- a/plugin-default-impl/nacos-default-control-plugin/src/test/java/com/alibaba/nacos/plugin/control/impl/NacosConnectionControlManagerTest.java +++ b/plugin-default-impl/nacos-default-control-plugin/src/test/java/com/alibaba/nacos/plugin/control/impl/NacosConnectionControlManagerTest.java @@ -19,40 +19,54 @@ import com.alibaba.nacos.plugin.control.connection.request.ConnectionCheckRequest; import com.alibaba.nacos.plugin.control.connection.response.ConnectionCheckResponse; import com.alibaba.nacos.plugin.control.connection.rule.ConnectionControlRule; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class NacosConnectionControlManagerTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class NacosConnectionControlManagerTest { @Test - public void testApplyConnectionLimitRule() { + void testApplyConnectionLimitRule() { NacosConnectionControlManager nacosConnectionControlManager = new NacosConnectionControlManager(); ConnectionControlRule connectionControlRule = new ConnectionControlRule(); connectionControlRule.setCountLimit(10); nacosConnectionControlManager.applyConnectionLimitRule(connectionControlRule); ConnectionControlRule connectionLimitRule = nacosConnectionControlManager.getConnectionLimitRule(); - Assert.assertEquals(connectionControlRule, connectionLimitRule); + assertEquals(connectionControlRule, connectionLimitRule); } @Test - public void testCheckLimit() { + void testCheckLimit() { NacosConnectionControlManager nacosConnectionControlManager = new NacosConnectionControlManager(); ConnectionControlRule connectionControlRule = new ConnectionControlRule(); connectionControlRule.setCountLimit(10); nacosConnectionControlManager.applyConnectionLimitRule(connectionControlRule); ConnectionCheckRequest connectionCheckRequest = new ConnectionCheckRequest("127.0.0.1", "test", "test"); ConnectionCheckResponse connectionCheckResponse = nacosConnectionControlManager.check(connectionCheckRequest); - Assert.assertFalse(connectionCheckResponse.isSuccess()); + assertFalse(connectionCheckResponse.isSuccess()); } @Test - public void testCheckUnLimit() { + void testCheckUnLimit() { NacosConnectionControlManager nacosConnectionControlManager = new NacosConnectionControlManager(); ConnectionControlRule connectionControlRule = new ConnectionControlRule(); connectionControlRule.setCountLimit(30); nacosConnectionControlManager.applyConnectionLimitRule(connectionControlRule); ConnectionCheckRequest connectionCheckRequest = new ConnectionCheckRequest("127.0.0.1", "test", "test"); ConnectionCheckResponse connectionCheckResponse = nacosConnectionControlManager.check(connectionCheckRequest); - Assert.assertTrue(connectionCheckResponse.isSuccess()); + assertTrue(connectionCheckResponse.isSuccess()); + } + + @Test + void testCheckLimitCountLessThanZero() { + NacosConnectionControlManager nacosConnectionControlManager = new NacosConnectionControlManager(); + ConnectionControlRule connectionControlRule = new ConnectionControlRule(); + connectionControlRule.setCountLimit(-1); + nacosConnectionControlManager.applyConnectionLimitRule(connectionControlRule); + ConnectionCheckRequest connectionCheckRequest = new ConnectionCheckRequest("127.0.0.1", "test", "test"); + ConnectionCheckResponse connectionCheckResponse = nacosConnectionControlManager.check(connectionCheckRequest); + assertTrue(connectionCheckResponse.isSuccess()); } } diff --git a/plugin-default-impl/nacos-default-control-plugin/src/test/java/com/alibaba/nacos/plugin/control/impl/NacosControlManagerBuilderTest.java b/plugin-default-impl/nacos-default-control-plugin/src/test/java/com/alibaba/nacos/plugin/control/impl/NacosControlManagerBuilderTest.java index 449b4dad9d8..83534c4800d 100644 --- a/plugin-default-impl/nacos-default-control-plugin/src/test/java/com/alibaba/nacos/plugin/control/impl/NacosControlManagerBuilderTest.java +++ b/plugin-default-impl/nacos-default-control-plugin/src/test/java/com/alibaba/nacos/plugin/control/impl/NacosControlManagerBuilderTest.java @@ -18,20 +18,21 @@ import com.alibaba.nacos.plugin.control.connection.ConnectionControlManager; import com.alibaba.nacos.plugin.control.tps.TpsControlManager; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class NacosControlManagerBuilderTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class NacosControlManagerBuilderTest { @Test - public void test() { + void test() { NacosControlManagerBuilder nacosControlManagerBuilder = new NacosControlManagerBuilder(); ConnectionControlManager connectionControlManager = nacosControlManagerBuilder.buildConnectionControlManager(); TpsControlManager tpsControlManager = nacosControlManagerBuilder.buildTpsControlManager(); - Assert.assertEquals("nacos", tpsControlManager.getName()); - Assert.assertEquals("nacos", connectionControlManager.getName()); - Assert.assertEquals("nacos", nacosControlManagerBuilder.getName()); + assertEquals("nacos", tpsControlManager.getName()); + assertEquals("nacos", connectionControlManager.getName()); + assertEquals("nacos", nacosControlManagerBuilder.getName()); } } diff --git a/plugin-default-impl/nacos-default-control-plugin/src/test/java/com/alibaba/nacos/plugin/control/impl/NacosTpsControlManagerTest.java b/plugin-default-impl/nacos-default-control-plugin/src/test/java/com/alibaba/nacos/plugin/control/impl/NacosTpsControlManagerTest.java index 5600089c8dc..0eb352f15ee 100644 --- a/plugin-default-impl/nacos-default-control-plugin/src/test/java/com/alibaba/nacos/plugin/control/impl/NacosTpsControlManagerTest.java +++ b/plugin-default-impl/nacos-default-control-plugin/src/test/java/com/alibaba/nacos/plugin/control/impl/NacosTpsControlManagerTest.java @@ -21,51 +21,53 @@ import com.alibaba.nacos.plugin.control.tps.response.TpsCheckResponse; import com.alibaba.nacos.plugin.control.tps.rule.RuleDetail; import com.alibaba.nacos.plugin.control.tps.rule.TpsControlRule; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; -public class NacosTpsControlManagerTest { +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class NacosTpsControlManagerTest { @Test - public void testRegisterTpsPoint1() { + void testRegisterTpsPoint1() { NacosTpsControlManager nacosTpsControlManager = new NacosTpsControlManager(); nacosTpsControlManager.registerTpsPoint("test"); - Assert.assertTrue(nacosTpsControlManager.getPoints().containsKey("test")); + assertTrue(nacosTpsControlManager.getPoints().containsKey("test")); } @Test - public void testRegisterTpsPoint2() { + void testRegisterTpsPoint2() { NacosTpsControlManager nacosTpsControlManager = new NacosTpsControlManager(); TpsControlRule tpsLimitRule = new TpsControlRule(); nacosTpsControlManager.applyTpsRule("test", tpsLimitRule); nacosTpsControlManager.registerTpsPoint("test"); - Assert.assertTrue(nacosTpsControlManager.getPoints().containsKey("test")); + assertTrue(nacosTpsControlManager.getPoints().containsKey("test")); } @Test - public void testApplyTpsRule1() { + void testApplyTpsRule1() { NacosTpsControlManager nacosTpsControlManager = new NacosTpsControlManager(); TpsControlRule tpsLimitRule = new TpsControlRule(); nacosTpsControlManager.applyTpsRule("test", tpsLimitRule); - Assert.assertTrue(nacosTpsControlManager.getRules().containsKey("test")); + assertTrue(nacosTpsControlManager.getRules().containsKey("test")); } @Test - public void testApplyTpsRule2() { + void testApplyTpsRule2() { NacosTpsControlManager nacosTpsControlManager = new NacosTpsControlManager(); nacosTpsControlManager.applyTpsRule("test", null); - Assert.assertFalse(nacosTpsControlManager.getRules().containsKey("test")); + assertFalse(nacosTpsControlManager.getRules().containsKey("test")); } @Test - public void testCheck() { + void testCheck() { NacosTpsControlManager nacosTpsControlManager = new NacosTpsControlManager(); nacosTpsControlManager.registerTpsPoint("test"); final TpsControlRule tpsLimitRule = new TpsControlRule(); @@ -82,6 +84,6 @@ public void testCheck() { tpsCheckRequest.setPointName("test"); tpsCheckRequest.setTimestamp(timeMillis); TpsCheckResponse check = nacosTpsControlManager.check(tpsCheckRequest); - Assert.assertTrue(check.isSuccess()); + assertTrue(check.isSuccess()); } } diff --git a/plugin-default-impl/nacos-default-plugin-all/pom.xml b/plugin-default-impl/nacos-default-plugin-all/pom.xml index a20bce8c85c..ef6d6d02943 100644 --- a/plugin-default-impl/nacos-default-plugin-all/pom.xml +++ b/plugin-default-impl/nacos-default-plugin-all/pom.xml @@ -30,12 +30,12 @@ com.alibaba.nacos default-auth-plugin - ${revision} + ${project.version} com.alibaba.nacos default-control-plugin - ${revision} + ${project.version} diff --git a/plugin/auth/src/main/java/com/alibaba/nacos/plugin/auth/spi/server/AuthPluginService.java b/plugin/auth/src/main/java/com/alibaba/nacos/plugin/auth/spi/server/AuthPluginService.java index f08dd3b1b46..93b4ef24cd3 100644 --- a/plugin/auth/src/main/java/com/alibaba/nacos/plugin/auth/spi/server/AuthPluginService.java +++ b/plugin/auth/src/main/java/com/alibaba/nacos/plugin/auth/spi/server/AuthPluginService.java @@ -84,4 +84,13 @@ public interface AuthPluginService { default boolean isLoginEnabled() { return false; } + + /** + * Whether need administrator . + * + * @return if need the administrator role. + */ + default boolean isAdminRequest() { + return true; + } } diff --git a/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/api/IdentityContextTest.java b/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/api/IdentityContextTest.java index cfd6bfcfb2d..7682899bf12 100644 --- a/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/api/IdentityContextTest.java +++ b/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/api/IdentityContextTest.java @@ -16,32 +16,33 @@ package com.alibaba.nacos.plugin.auth.api; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -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.assertThrows; -public class IdentityContextTest { +class IdentityContextTest { private static final String TEST = "test"; private IdentityContext identityContext; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { identityContext = new IdentityContext(); } @Test - public void testGetParameter() { + void testGetParameter() { assertNull(identityContext.getParameter(TEST)); identityContext.setParameter(TEST, TEST); assertEquals(TEST, identityContext.getParameter(TEST)); } @Test - public void testGetParameterWithDefaultValue() { + void testGetParameterWithDefaultValue() { assertEquals(TEST, identityContext.getParameter(TEST, TEST)); identityContext.setParameter(TEST, TEST + "new"); assertEquals(TEST + "new", identityContext.getParameter(TEST, TEST)); @@ -49,8 +50,10 @@ public void testGetParameterWithDefaultValue() { assertEquals(1L, actual); } - @Test(expected = IllegalArgumentException.class) - public void testGetParameterWithNullDefaultValue() { - identityContext.getParameter(TEST, null); + @Test + void testGetParameterWithNullDefaultValue() { + assertThrows(IllegalArgumentException.class, () -> { + identityContext.getParameter(TEST, null); + }); } } diff --git a/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/api/LoginIdentityContextTest.java b/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/api/LoginIdentityContextTest.java index a175f0c1bc0..6d42ac1c7e6 100644 --- a/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/api/LoginIdentityContextTest.java +++ b/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/api/LoginIdentityContextTest.java @@ -16,29 +16,29 @@ package com.alibaba.nacos.plugin.auth.api; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; -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; -public class LoginIdentityContextTest { +class LoginIdentityContextTest { private static final String TEST = "test"; private LoginIdentityContext loginIdentityContext; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { loginIdentityContext = new LoginIdentityContext(); } @Test - public void testSetParameter() { + void testSetParameter() { assertNull(loginIdentityContext.getParameter(TEST)); assertTrue(loginIdentityContext.getAllKey().isEmpty()); loginIdentityContext.setParameter(TEST, TEST); @@ -47,7 +47,7 @@ public void testSetParameter() { } @Test - public void testSetParameters() { + void testSetParameters() { assertNull(loginIdentityContext.getParameter(TEST)); assertTrue(loginIdentityContext.getAllKey().isEmpty()); Map map = new HashMap<>(2); diff --git a/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/api/PermissionTest.java b/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/api/PermissionTest.java index c365d36a788..fe6da73da77 100644 --- a/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/api/PermissionTest.java +++ b/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/api/PermissionTest.java @@ -17,31 +17,30 @@ package com.alibaba.nacos.plugin.auth.api; import com.alibaba.nacos.plugin.auth.constant.ActionTypes; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Properties; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class PermissionTest { +class PermissionTest { private Permission permission; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { permission = new Permission(Resource.EMPTY_RESOURCE, ActionTypes.WRITE.toString()); } @Test - public void testToString() { - assertEquals( - "Permission{resource='Resource{namespaceId='', group='', name='', type='', properties=null}', action='w'}", + void testToString() { + assertEquals("Permission{resource='Resource{namespaceId='', group='', name='', type='', properties=null}', action='w'}", permission.toString()); } @Test - public void testSetResource() { + void testSetResource() { Permission permission = new Permission(); Properties properties = new Properties(); Resource resource = new Resource("NS", "G", "N", "TEST", properties); @@ -54,7 +53,7 @@ public void testSetResource() { } @Test - public void testSetAction() { + void testSetAction() { Permission permission = new Permission(); permission.setAction(ActionTypes.READ.toString()); assertEquals(ActionTypes.READ.toString(), permission.getAction()); diff --git a/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/api/RequestResourceTest.java b/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/api/RequestResourceTest.java index c707135e227..5e99edc854e 100644 --- a/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/api/RequestResourceTest.java +++ b/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/api/RequestResourceTest.java @@ -17,21 +17,20 @@ package com.alibaba.nacos.plugin.auth.api; import com.alibaba.nacos.plugin.auth.constant.SignType; -import org.junit.Before; -import org.junit.Test; +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 RequestResourceTest { +class RequestResourceTest { - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { } @Test - public void testBuildNamingRequestResource() { - RequestResource actual = RequestResource.namingBuilder().setNamespace("NS").setGroup("G").setResource("Service") - .build(); + void testBuildNamingRequestResource() { + RequestResource actual = RequestResource.namingBuilder().setNamespace("NS").setGroup("G").setResource("Service").build(); assertEquals(SignType.NAMING, actual.getType()); assertEquals("NS", actual.getNamespace()); assertEquals("G", actual.getGroup()); @@ -39,9 +38,8 @@ public void testBuildNamingRequestResource() { } @Test - public void testBuildConfigRequestResource() { - RequestResource actual = RequestResource.configBuilder().setNamespace("NS").setGroup("G").setResource("dataId") - .build(); + void testBuildConfigRequestResource() { + RequestResource actual = RequestResource.configBuilder().setNamespace("NS").setGroup("G").setResource("dataId").build(); assertEquals(SignType.CONFIG, actual.getType()); assertEquals("NS", actual.getNamespace()); assertEquals("G", actual.getGroup()); diff --git a/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/constant/ActionTypesTest.java b/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/constant/ActionTypesTest.java index cda6b993634..d72a067045b 100644 --- a/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/constant/ActionTypesTest.java +++ b/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/constant/ActionTypesTest.java @@ -16,20 +16,20 @@ package com.alibaba.nacos.plugin.auth.constant; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class ActionTypesTest { +class ActionTypesTest { @Test - public void testToStringForRead() { + void testToStringForRead() { ActionTypes actual = ActionTypes.valueOf("READ"); assertEquals("r", actual.toString()); } @Test - public void testToStringForWrite() { + void testToStringForWrite() { ActionTypes actual = ActionTypes.valueOf("WRITE"); assertEquals("w", actual.toString()); } diff --git a/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/constant/ConstantsTest.java b/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/constant/ConstantsTest.java index 2e03cb2b888..582d182f773 100644 --- a/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/constant/ConstantsTest.java +++ b/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/constant/ConstantsTest.java @@ -16,25 +16,24 @@ package com.alibaba.nacos.plugin.auth.constant; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class ConstantsTest { +class ConstantsTest { @Test - public void testConstantsForAuth() { + void testConstantsForAuth() { assertEquals("nacos.core.auth.enabled", Constants.Auth.NACOS_CORE_AUTH_ENABLED); assertEquals("nacos.core.auth.system.type", Constants.Auth.NACOS_CORE_AUTH_SYSTEM_TYPE); assertEquals("nacos.core.auth.caching.enabled", Constants.Auth.NACOS_CORE_AUTH_CACHING_ENABLED); assertEquals("nacos.core.auth.server.identity.key", Constants.Auth.NACOS_CORE_AUTH_SERVER_IDENTITY_KEY); assertEquals("nacos.core.auth.server.identity.value", Constants.Auth.NACOS_CORE_AUTH_SERVER_IDENTITY_VALUE); - assertEquals("nacos.core.auth.enable.userAgentAuthWhite", - Constants.Auth.NACOS_CORE_AUTH_ENABLE_USER_AGENT_AUTH_WHITE); + assertEquals("nacos.core.auth.enable.userAgentAuthWhite", Constants.Auth.NACOS_CORE_AUTH_ENABLE_USER_AGENT_AUTH_WHITE); } @Test - public void testConstantsForResource() { + void testConstantsForResource() { assertEquals(":", Constants.Resource.SPLITTER); assertEquals("*", Constants.Resource.ANY); assertEquals("action", Constants.Resource.ACTION); @@ -42,14 +41,14 @@ public void testConstantsForResource() { } @Test - public void testConstantsForIdentity() { + void testConstantsForIdentity() { assertEquals("identity_id", Constants.Identity.IDENTITY_ID); assertEquals("X-Real-IP", Constants.Identity.X_REAL_IP); assertEquals("remote_ip", Constants.Identity.REMOTE_IP); } @Test - public void testConstantsForSignType() { + void testConstantsForSignType() { assertEquals("naming", SignType.NAMING); assertEquals("config", SignType.CONFIG); assertEquals("console", SignType.CONSOLE); diff --git a/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/exception/AccessExceptionTest.java b/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/exception/AccessExceptionTest.java index 611bacf88fc..df020281be8 100644 --- a/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/exception/AccessExceptionTest.java +++ b/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/exception/AccessExceptionTest.java @@ -17,28 +17,28 @@ package com.alibaba.nacos.plugin.auth.exception; import com.alibaba.nacos.api.common.Constants; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class AccessExceptionTest { +class AccessExceptionTest { @Test - public void testNewAccessExceptionWithCode() { + void testNewAccessExceptionWithCode() { AccessException actual = new AccessException(403); assertEquals(403, actual.getErrCode()); assertEquals(Constants.NULL, actual.getErrMsg()); } @Test - public void testNewAccessExceptionWithMsg() { + void testNewAccessExceptionWithMsg() { AccessException actual = new AccessException("Test"); assertEquals("Test", actual.getErrMsg()); assertEquals(0, actual.getErrCode()); } @Test - public void testNewAccessExceptionWithNoArgs() { + void testNewAccessExceptionWithNoArgs() { AccessException actual = new AccessException(); assertEquals(Constants.NULL, actual.getErrMsg()); assertEquals(0, actual.getErrCode()); diff --git a/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/spi/client/ClientAuthPluginManagerTest.java b/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/spi/client/ClientAuthPluginManagerTest.java index ae86d83985d..45e6a835b43 100644 --- a/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/spi/client/ClientAuthPluginManagerTest.java +++ b/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/spi/client/ClientAuthPluginManagerTest.java @@ -19,13 +19,12 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.common.http.client.NacosRestTemplate; import com.alibaba.nacos.common.spi.NacosServiceLoader; -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.util.Collection; @@ -34,6 +33,9 @@ import java.util.Map; import java.util.Set; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * {@link ClientAuthPluginManager} unit test. * @@ -41,8 +43,8 @@ * @date 2021-08-12 12:56 */ -@RunWith(MockitoJUnitRunner.class) -public class ClientAuthPluginManagerTest { +@ExtendWith(MockitoExtension.class) +class ClientAuthPluginManagerTest { private ClientAuthPluginManager clientAuthPluginManager; @@ -52,37 +54,36 @@ public class ClientAuthPluginManagerTest { @Mock private NacosRestTemplate nacosRestTemplate; - @Before - public void setUp() throws NoSuchFieldException, IllegalAccessException { + @BeforeEach + void setUp() throws NoSuchFieldException, IllegalAccessException { clientAuthPluginManager = new ClientAuthPluginManager(); } - @After - public void tearDown() throws NacosException, NoSuchFieldException, IllegalAccessException { + @AfterEach + void tearDown() throws NacosException, NoSuchFieldException, IllegalAccessException { getServiceLoaderMap().remove(AbstractClientAuthService.class); clientAuthPluginManager.shutdown(); } - private Map, Collection>> getServiceLoaderMap() - throws NoSuchFieldException, IllegalAccessException { + private Map, Collection>> getServiceLoaderMap() throws NoSuchFieldException, IllegalAccessException { Field servicesField = NacosServiceLoader.class.getDeclaredField("SERVICES"); servicesField.setAccessible(true); return (Map, Collection>>) servicesField.get(null); } @Test - public void testGetAuthServiceSpiImplSet() { + void testGetAuthServiceSpiImplSet() { clientAuthPluginManager.init(serverlist, nacosRestTemplate); Set clientAuthServiceSet = clientAuthPluginManager.getAuthServiceSpiImplSet(); - Assert.assertFalse(clientAuthServiceSet.isEmpty()); + assertFalse(clientAuthServiceSet.isEmpty()); } @Test - public void testGetAuthServiceSpiImplSetForEmpty() throws NoSuchFieldException, IllegalAccessException { + void testGetAuthServiceSpiImplSetForEmpty() throws NoSuchFieldException, IllegalAccessException { getServiceLoaderMap().put(AbstractClientAuthService.class, Collections.emptyList()); clientAuthPluginManager.init(serverlist, nacosRestTemplate); Set clientAuthServiceSet = clientAuthPluginManager.getAuthServiceSpiImplSet(); - Assert.assertTrue(clientAuthServiceSet.isEmpty()); + assertTrue(clientAuthServiceSet.isEmpty()); } } diff --git a/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/spi/server/AuthPluginManagerTest.java b/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/spi/server/AuthPluginManagerTest.java index a4802cc60b4..87800977d31 100644 --- a/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/spi/server/AuthPluginManagerTest.java +++ b/plugin/auth/src/test/java/com/alibaba/nacos/plugin/auth/spi/server/AuthPluginManagerTest.java @@ -16,17 +16,19 @@ package com.alibaba.nacos.plugin.auth.spi.server; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.lang.reflect.Field; import java.util.Map; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * {@link AuthPluginManager} unit test. * @@ -34,38 +36,37 @@ * @date 2021-08-12 12:56 */ -@RunWith(MockitoJUnitRunner.class) -public class AuthPluginManagerTest { +@ExtendWith(MockitoExtension.class) +class AuthPluginManagerTest { + + private static final String TYPE = "test"; private AuthPluginManager authPluginManager; @Mock private AuthPluginService authPluginService; - private static final String TYPE = "test"; - - @Before - public void setUp() throws NoSuchFieldException, IllegalAccessException { + @BeforeEach + void setUp() throws NoSuchFieldException, IllegalAccessException { authPluginManager = AuthPluginManager.getInstance(); Class authPluginManagerClass = AuthPluginManager.class; Field authPlugins = authPluginManagerClass.getDeclaredField("authServiceMap"); authPlugins.setAccessible(true); - Map authServiceMap = (Map) authPlugins - .get(authPluginManager); + Map authServiceMap = (Map) authPlugins.get(authPluginManager); authServiceMap.put(TYPE, authPluginService); } @Test - public void testGetInstance() { + void testGetInstance() { AuthPluginManager instance = AuthPluginManager.getInstance(); - Assert.assertNotNull(instance); + assertNotNull(instance); } @Test - public void testFindAuthServiceSpiImpl() { + void testFindAuthServiceSpiImpl() { Optional authServiceImpl = authPluginManager.findAuthServiceSpiImpl(TYPE); - Assert.assertTrue(authServiceImpl.isPresent()); + assertTrue(authServiceImpl.isPresent()); } } diff --git a/plugin/config/src/test/java/com/alibaba/nacos/plugin/config/ConfigChangePluginManagerTests.java b/plugin/config/src/test/java/com/alibaba/nacos/plugin/config/ConfigChangePluginManagerTests.java index 27822506a1f..c9fb5930813 100644 --- a/plugin/config/src/test/java/com/alibaba/nacos/plugin/config/ConfigChangePluginManagerTests.java +++ b/plugin/config/src/test/java/com/alibaba/nacos/plugin/config/ConfigChangePluginManagerTests.java @@ -21,52 +21,58 @@ import com.alibaba.nacos.plugin.config.model.ConfigChangeRequest; import com.alibaba.nacos.plugin.config.model.ConfigChangeResponse; import com.alibaba.nacos.plugin.config.spi.ConfigChangePluginService; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.Optional; import java.util.stream.IntStream; +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.assertTrue; + /** * ConfigChangePluginManagerTests. * * @author liyunfei **/ -public class ConfigChangePluginManagerTests { +class ConfigChangePluginManagerTests { + @Test - public void testInstance() { + void testInstance() { ConfigChangePluginManager instance = ConfigChangePluginManager.getInstance(); - Assert.assertNotNull(instance); + assertNotNull(instance); } - - @Before - public void initPluginServices() { + + @BeforeEach + void initPluginServices() { ConfigChangePluginManager.join(new ConfigChangePluginService() { @Override public void execute(ConfigChangeRequest configChangeRequest, ConfigChangeResponse configChangeResponse) { // ignore } - + @Override public ConfigChangeExecuteTypes executeType() { return ConfigChangeExecuteTypes.EXECUTE_BEFORE_TYPE; } - + @Override public String getServiceType() { return "test1"; } - + @Override public int getOrder() { return 0; } - + @Override public ConfigChangePointCutTypes[] pointcutMethodNames() { - return new ConfigChangePointCutTypes[]{ConfigChangePointCutTypes.PUBLISH_BY_HTTP, ConfigChangePointCutTypes.PUBLISH_BY_RPC}; + return new ConfigChangePointCutTypes[] {ConfigChangePointCutTypes.PUBLISH_BY_HTTP, + ConfigChangePointCutTypes.PUBLISH_BY_RPC}; } }); ConfigChangePluginManager.join(new ConfigChangePluginService() { @@ -74,25 +80,25 @@ public ConfigChangePointCutTypes[] pointcutMethodNames() { public void execute(ConfigChangeRequest configChangeRequest, ConfigChangeResponse configChangeResponse) { // ignore } - + @Override public ConfigChangeExecuteTypes executeType() { return ConfigChangeExecuteTypes.EXECUTE_BEFORE_TYPE; } - + @Override public String getServiceType() { return "test2"; } - + @Override public int getOrder() { return 200; } - + @Override public ConfigChangePointCutTypes[] pointcutMethodNames() { - return new ConfigChangePointCutTypes[]{ConfigChangePointCutTypes.IMPORT_BY_HTTP, ConfigChangePointCutTypes.PUBLISH_BY_RPC}; + return new ConfigChangePointCutTypes[] {ConfigChangePointCutTypes.IMPORT_BY_HTTP, ConfigChangePointCutTypes.PUBLISH_BY_RPC}; } }); ConfigChangePluginManager.join(new ConfigChangePluginService() { @@ -100,105 +106,100 @@ public ConfigChangePointCutTypes[] pointcutMethodNames() { public void execute(ConfigChangeRequest configChangeRequest, ConfigChangeResponse configChangeResponse) { // ignore } - + @Override public ConfigChangeExecuteTypes executeType() { return ConfigChangeExecuteTypes.EXECUTE_AFTER_TYPE; } - + @Override public String getServiceType() { return "test3"; } - + @Override public int getOrder() { return 400; } - + @Override public ConfigChangePointCutTypes[] pointcutMethodNames() { - return new ConfigChangePointCutTypes[]{ConfigChangePointCutTypes.IMPORT_BY_HTTP, ConfigChangePointCutTypes.PUBLISH_BY_RPC, + return new ConfigChangePointCutTypes[] {ConfigChangePointCutTypes.IMPORT_BY_HTTP, ConfigChangePointCutTypes.PUBLISH_BY_RPC, ConfigChangePointCutTypes.REMOVE_BATCH_HTTP, ConfigChangePointCutTypes.REMOVE_BY_RPC, ConfigChangePointCutTypes.REMOVE_BY_HTTP}; } }); - + ConfigChangePluginManager.join(new ConfigChangePluginService() { @Override public void execute(ConfigChangeRequest configChangeRequest, ConfigChangeResponse configChangeResponse) { // ignore } - + @Override public ConfigChangeExecuteTypes executeType() { return ConfigChangeExecuteTypes.EXECUTE_AFTER_TYPE; } - + @Override public String getServiceType() { return "test4"; } - + @Override public int getOrder() { return 600; } - + @Override public ConfigChangePointCutTypes[] pointcutMethodNames() { - return new ConfigChangePointCutTypes[]{ConfigChangePointCutTypes.PUBLISH_BY_HTTP, ConfigChangePointCutTypes.REMOVE_BATCH_HTTP, - ConfigChangePointCutTypes.REMOVE_BY_RPC, ConfigChangePointCutTypes.REMOVE_BY_HTTP}; + return new ConfigChangePointCutTypes[] {ConfigChangePointCutTypes.PUBLISH_BY_HTTP, + ConfigChangePointCutTypes.REMOVE_BATCH_HTTP, ConfigChangePointCutTypes.REMOVE_BY_RPC, + ConfigChangePointCutTypes.REMOVE_BY_HTTP}; } }); } - + @Test - public void testFindPluginServiceQueueByPointcut() { - List configChangePluginServices = ConfigChangePluginManager - .findPluginServicesByPointcut(ConfigChangePointCutTypes.PUBLISH_BY_HTTP); - Assert.assertEquals(2, configChangePluginServices.size()); - Assert.assertTrue(isSorted(configChangePluginServices)); - configChangePluginServices = ConfigChangePluginManager - .findPluginServicesByPointcut(ConfigChangePointCutTypes.PUBLISH_BY_RPC); - Assert.assertEquals(3, configChangePluginServices.size()); - Assert.assertTrue(isSorted(configChangePluginServices)); - configChangePluginServices = ConfigChangePluginManager - .findPluginServicesByPointcut(ConfigChangePointCutTypes.IMPORT_BY_HTTP); - Assert.assertEquals(2, configChangePluginServices.size()); - Assert.assertTrue(isSorted(configChangePluginServices)); - configChangePluginServices = ConfigChangePluginManager - .findPluginServicesByPointcut(ConfigChangePointCutTypes.REMOVE_BATCH_HTTP); - Assert.assertEquals(2, configChangePluginServices.size()); - Assert.assertTrue(isSorted(configChangePluginServices)); - configChangePluginServices = ConfigChangePluginManager - .findPluginServicesByPointcut(ConfigChangePointCutTypes.REMOVE_BY_RPC); - Assert.assertEquals(2, configChangePluginServices.size()); - Assert.assertTrue(isSorted(configChangePluginServices)); - configChangePluginServices = ConfigChangePluginManager - .findPluginServicesByPointcut(ConfigChangePointCutTypes.REMOVE_BY_HTTP); - Assert.assertEquals(2, configChangePluginServices.size()); - Assert.assertTrue(isSorted(configChangePluginServices)); + void testFindPluginServiceQueueByPointcut() { + List configChangePluginServices = ConfigChangePluginManager.findPluginServicesByPointcut( + ConfigChangePointCutTypes.PUBLISH_BY_HTTP); + assertEquals(2, configChangePluginServices.size()); + assertTrue(isSorted(configChangePluginServices)); + configChangePluginServices = ConfigChangePluginManager.findPluginServicesByPointcut(ConfigChangePointCutTypes.PUBLISH_BY_RPC); + assertEquals(3, configChangePluginServices.size()); + assertTrue(isSorted(configChangePluginServices)); + configChangePluginServices = ConfigChangePluginManager.findPluginServicesByPointcut(ConfigChangePointCutTypes.IMPORT_BY_HTTP); + assertEquals(2, configChangePluginServices.size()); + assertTrue(isSorted(configChangePluginServices)); + configChangePluginServices = ConfigChangePluginManager.findPluginServicesByPointcut(ConfigChangePointCutTypes.REMOVE_BATCH_HTTP); + assertEquals(2, configChangePluginServices.size()); + assertTrue(isSorted(configChangePluginServices)); + configChangePluginServices = ConfigChangePluginManager.findPluginServicesByPointcut(ConfigChangePointCutTypes.REMOVE_BY_RPC); + assertEquals(2, configChangePluginServices.size()); + assertTrue(isSorted(configChangePluginServices)); + configChangePluginServices = ConfigChangePluginManager.findPluginServicesByPointcut(ConfigChangePointCutTypes.REMOVE_BY_HTTP); + assertEquals(2, configChangePluginServices.size()); + assertTrue(isSorted(configChangePluginServices)); } - + @Test - public void testFindPluginServiceByServiceType() { - Optional configChangePluginServiceOptional = ConfigChangePluginManager - .getInstance().findPluginServiceImpl("test1"); - Assert.assertTrue(configChangePluginServiceOptional.isPresent()); + void testFindPluginServiceByServiceType() { + Optional configChangePluginServiceOptional = ConfigChangePluginManager.getInstance() + .findPluginServiceImpl("test1"); + assertTrue(configChangePluginServiceOptional.isPresent()); configChangePluginServiceOptional = ConfigChangePluginManager.getInstance().findPluginServiceImpl("test2"); - Assert.assertTrue(configChangePluginServiceOptional.isPresent()); + assertTrue(configChangePluginServiceOptional.isPresent()); configChangePluginServiceOptional = ConfigChangePluginManager.getInstance().findPluginServiceImpl("test3"); - Assert.assertTrue(configChangePluginServiceOptional.isPresent()); + assertTrue(configChangePluginServiceOptional.isPresent()); configChangePluginServiceOptional = ConfigChangePluginManager.getInstance().findPluginServiceImpl("test4"); - Assert.assertTrue(configChangePluginServiceOptional.isPresent()); + assertTrue(configChangePluginServiceOptional.isPresent()); configChangePluginServiceOptional = ConfigChangePluginManager.getInstance().findPluginServiceImpl("test5"); - Assert.assertFalse(configChangePluginServiceOptional.isPresent()); + assertFalse(configChangePluginServiceOptional.isPresent()); } - + private boolean isSorted(List list) { - return IntStream.range(0, list.size() - 1) - .allMatch(i -> list.get(i).getOrder() <= list.get(i + 1).getOrder()); + return IntStream.range(0, list.size() - 1).allMatch(i -> list.get(i).getOrder() <= list.get(i + 1).getOrder()); } } diff --git a/plugin/control/src/main/java/com/alibaba/nacos/plugin/control/connection/ConnectionControlManager.java b/plugin/control/src/main/java/com/alibaba/nacos/plugin/control/connection/ConnectionControlManager.java index 7224d12271d..57d424a4200 100644 --- a/plugin/control/src/main/java/com/alibaba/nacos/plugin/control/connection/ConnectionControlManager.java +++ b/plugin/control/src/main/java/com/alibaba/nacos/plugin/control/connection/ConnectionControlManager.java @@ -36,7 +36,7 @@ /** * connection control manager. * - * @author shiyiyue + * @author shiyiyu */ @SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule") public abstract class ConnectionControlManager { @@ -64,7 +64,7 @@ public ConnectionControlManager() { /** * get manager name. * - * @return + * @return name */ public abstract String getName(); @@ -104,7 +104,7 @@ private void initConnectionRule() { } else { Loggers.CONTROL.info("No connection rule content found ,use default empty rule "); - connectionControlRule = new ConnectionControlRule(); + connectionControlRule = connectionControlRuleParser.parseRule(""); } } @@ -127,7 +127,7 @@ public ConnectionControlRule getConnectionLimitRule() { * check connection allowed. * * @param connectionCheckRequest connectionCheckRequest. - * @return + * @return connection check response */ public abstract ConnectionCheckResponse check(ConnectionCheckRequest connectionCheckRequest); diff --git a/plugin/control/src/test/java/com/alibaba/nacos/plugin/control/ControlManagerCenterTest.java b/plugin/control/src/test/java/com/alibaba/nacos/plugin/control/ControlManagerCenterTest.java index 3362093ccc6..c09cef1cb3b 100644 --- a/plugin/control/src/test/java/com/alibaba/nacos/plugin/control/ControlManagerCenterTest.java +++ b/plugin/control/src/test/java/com/alibaba/nacos/plugin/control/ControlManagerCenterTest.java @@ -26,9 +26,8 @@ import com.alibaba.nacos.plugin.control.tps.rule.RuleDetail; import com.alibaba.nacos.plugin.control.tps.rule.TpsControlRule; import com.alibaba.nacos.plugin.control.utils.EnvUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.File; import java.lang.reflect.Constructor; @@ -36,10 +35,13 @@ import java.lang.reflect.Modifier; import java.util.concurrent.TimeUnit; -public class ControlManagerCenterTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class ControlManagerCenterTest { - @Before - public void initInstance() throws NoSuchFieldException, IllegalAccessException { + @BeforeEach + void initInstance() throws NoSuchFieldException, IllegalAccessException { //reset instance for reload spi Field instanceControlConfigs = ControlConfigs.class.getDeclaredField("instance"); instanceControlConfigs.setAccessible(true); @@ -69,29 +71,28 @@ private void resetRuleStorageProxy() { } @Test - public void testGetInstance() { + void testGetInstance() { ControlConfigs.getInstance().setControlManagerType("test"); ControlManagerCenter controlManagerCenter = ControlManagerCenter.getInstance(); ConnectionControlManager connectionControlManager = controlManagerCenter.getConnectionControlManager(); - Assert.assertEquals("testConnection", connectionControlManager.getName()); + assertEquals("testConnection", connectionControlManager.getName()); TpsControlManager tpsControlManager = controlManagerCenter.getTpsControlManager(); - Assert.assertEquals("testTps", tpsControlManager.getName()); - Assert.assertNotNull(controlManagerCenter.getRuleStorageProxy()); + assertEquals("testTps", tpsControlManager.getName()); + assertNotNull(controlManagerCenter.getRuleStorageProxy()); } @Test - public void testGetInstanceWithDefault() { + void testGetInstanceWithDefault() { ControlManagerCenter controlManagerCenter = ControlManagerCenter.getInstance(); ConnectionControlManager connectionControlManager = controlManagerCenter.getConnectionControlManager(); - Assert.assertEquals("noLimit", connectionControlManager.getName()); + assertEquals("noLimit", connectionControlManager.getName()); TpsControlManager tpsControlManager = controlManagerCenter.getTpsControlManager(); - Assert.assertEquals("noLimit", tpsControlManager.getName()); + assertEquals("noLimit", tpsControlManager.getName()); } @Test - public void testReloadTpsControlRule() throws Exception { - String localRuleStorageBaseDir = - EnvUtils.getNacosHome() + File.separator + "tmpTps" + File.separator + "tps" + File.separator; + void testReloadTpsControlRule() throws Exception { + String localRuleStorageBaseDir = EnvUtils.getNacosHome() + File.separator + "tmpTps" + File.separator + "tps" + File.separator; ControlConfigs.getInstance().setLocalRuleStorageBaseDir(localRuleStorageBaseDir); resetRuleStorageProxy(); final ControlManagerCenter controlManagerCenter = ControlManagerCenter.getInstance(); @@ -108,8 +109,8 @@ public void testReloadTpsControlRule() throws Exception { controlManagerCenter.getTpsControlManager().applyTpsRule("test", tpsControlRule); TpsControlRule testTpsControlRule = controlManagerCenter.getTpsControlManager().getRules().get("test"); - Assert.assertEquals(100, testTpsControlRule.getPointRule().getMaxCount()); - Assert.assertEquals("test", testTpsControlRule.getPointRule().getRuleName()); + assertEquals(100, testTpsControlRule.getPointRule().getMaxCount()); + assertEquals("test", testTpsControlRule.getPointRule().getRuleName()); TpsControlRule tpsControlRule2 = new TpsControlRule(); tpsControlRule2.setPointName("test"); @@ -126,12 +127,12 @@ public void testReloadTpsControlRule() throws Exception { //wait event TimeUnit.SECONDS.sleep(1); TpsControlRule testTpsControlRule2 = controlManagerCenter.getTpsControlManager().getRules().get("test"); - Assert.assertEquals(200, testTpsControlRule2.getPointRule().getMaxCount()); - Assert.assertEquals("test2", testTpsControlRule2.getPointRule().getRuleName()); + assertEquals(200, testTpsControlRule2.getPointRule().getMaxCount()); + assertEquals("test2", testTpsControlRule2.getPointRule().getRuleName()); } @Test - public void testReloadTpsControlRuleExternal() throws Exception { + void testReloadTpsControlRuleExternal() throws Exception { String localRuleStorageBaseDir = EnvUtils.getNacosHome() + File.separator + "tmpTps" + File.separator + "tpsExternal" + File.separator; ControlConfigs.getInstance().setLocalRuleStorageBaseDir(localRuleStorageBaseDir); @@ -152,8 +153,8 @@ public void testReloadTpsControlRuleExternal() throws Exception { controlManagerCenter.getTpsControlManager().applyTpsRule("test", tpsControlRule); TpsControlRule testTpsControlRule = controlManagerCenter.getTpsControlManager().getRules().get("test"); - Assert.assertEquals(100, testTpsControlRule.getPointRule().getMaxCount()); - Assert.assertEquals("test", testTpsControlRule.getPointRule().getRuleName()); + assertEquals(100, testTpsControlRule.getPointRule().getMaxCount()); + assertEquals("test", testTpsControlRule.getPointRule().getRuleName()); TpsControlRule tpsControlRule2 = new TpsControlRule(); tpsControlRule2.setPointName("test"); @@ -170,15 +171,14 @@ public void testReloadTpsControlRuleExternal() throws Exception { //wait event TimeUnit.SECONDS.sleep(1); TpsControlRule testTpsControlRule2 = controlManagerCenter.getTpsControlManager().getRules().get("test"); - Assert.assertEquals(200, testTpsControlRule2.getPointRule().getMaxCount()); - Assert.assertEquals("test2", testTpsControlRule2.getPointRule().getRuleName()); + assertEquals(200, testTpsControlRule2.getPointRule().getMaxCount()); + assertEquals("test2", testTpsControlRule2.getPointRule().getRuleName()); } @Test - public void testReloadConnectionControlRule() throws Exception { + void testReloadConnectionControlRule() throws Exception { String localRuleStorageBaseDir = - EnvUtils.getNacosHome() + File.separator + "tmpConnection" + File.separator + "connection" - + File.separator; + EnvUtils.getNacosHome() + File.separator + "tmpConnection" + File.separator + "connection" + File.separator; ControlConfigs.getInstance().setLocalRuleStorageBaseDir(localRuleStorageBaseDir); resetRuleStorageProxy(); ConnectionControlRule connectionLimitRule = new ConnectionControlRule(); @@ -191,7 +191,7 @@ public void testReloadConnectionControlRule() throws Exception { //apply rule connectionControlManager.applyConnectionLimitRule(connectionLimitRule); ConnectionControlRule connectionLimitRule1 = connectionControlManager.getConnectionLimitRule(); - Assert.assertEquals(100, connectionLimitRule1.getCountLimit()); + assertEquals(100, connectionLimitRule1.getCountLimit()); ConnectionControlRule connectionLimitRule2 = new ConnectionControlRule(); connectionLimitRule2.setCountLimit(200); @@ -203,14 +203,13 @@ public void testReloadConnectionControlRule() throws Exception { //wait event TimeUnit.SECONDS.sleep(1); ConnectionControlRule connectionLimitRule3 = connectionControlManager.getConnectionLimitRule(); - Assert.assertEquals(200, connectionLimitRule3.getCountLimit()); + assertEquals(200, connectionLimitRule3.getCountLimit()); } @Test - public void testReloadConnectionControlRuleExternal() throws Exception { + void testReloadConnectionControlRuleExternal() throws Exception { String localRuleStorageBaseDir = - EnvUtils.getNacosHome() + File.separator + "tmpConnection" + File.separator + "connectionExternal" - + File.separator; + EnvUtils.getNacosHome() + File.separator + "tmpConnection" + File.separator + "connectionExternal" + File.separator; ControlConfigs.getInstance().setLocalRuleStorageBaseDir(localRuleStorageBaseDir); ControlConfigs.getInstance().setRuleExternalStorage("test"); resetRuleStorageProxy(); @@ -224,7 +223,7 @@ public void testReloadConnectionControlRuleExternal() throws Exception { //apply rule connectionControlManager.applyConnectionLimitRule(connectionLimitRule); ConnectionControlRule connectionLimitRule1 = connectionControlManager.getConnectionLimitRule(); - Assert.assertEquals(100, connectionLimitRule1.getCountLimit()); + assertEquals(100, connectionLimitRule1.getCountLimit()); ConnectionControlRule connectionLimitRule2 = new ConnectionControlRule(); connectionLimitRule2.setCountLimit(200); @@ -236,6 +235,6 @@ public void testReloadConnectionControlRuleExternal() throws Exception { //wait event TimeUnit.SECONDS.sleep(1); ConnectionControlRule connectionLimitRule3 = connectionControlManager.getConnectionLimitRule(); - Assert.assertEquals(200, connectionLimitRule3.getCountLimit()); + assertEquals(200, connectionLimitRule3.getCountLimit()); } } diff --git a/plugin/control/src/test/java/com/alibaba/nacos/plugin/control/connection/DefaultConnectionControlManagerTest.java b/plugin/control/src/test/java/com/alibaba/nacos/plugin/control/connection/DefaultConnectionControlManagerTest.java index 9ee82ca6ddf..a41f69bf710 100644 --- a/plugin/control/src/test/java/com/alibaba/nacos/plugin/control/connection/DefaultConnectionControlManagerTest.java +++ b/plugin/control/src/test/java/com/alibaba/nacos/plugin/control/connection/DefaultConnectionControlManagerTest.java @@ -20,18 +20,20 @@ import com.alibaba.nacos.plugin.control.connection.response.ConnectionCheckCode; import com.alibaba.nacos.plugin.control.connection.response.ConnectionCheckResponse; import com.alibaba.nacos.plugin.control.connection.rule.ConnectionControlRule; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * two fixed metrics, total 30, iptotal 15, detail is testa(total-20,iptotal-10),testb(total-10,iptotal-5). */ -public class DefaultConnectionControlManagerTest { +class DefaultConnectionControlManagerTest { DefaultConnectionControlManager connectionControlManager = new DefaultConnectionControlManager(); @Test - public void test() { + void test() { ConnectionControlRule connectionControlRule = new ConnectionControlRule(); @@ -40,8 +42,8 @@ public void test() { connectionControlRule.setCountLimit(40); connectionControlManager.applyConnectionLimitRule(connectionControlRule); check = connectionControlManager.check(connectionCheckRequest); - Assert.assertTrue(check.isSuccess()); - Assert.assertEquals(ConnectionCheckCode.CHECK_SKIP, check.getCode()); + assertTrue(check.isSuccess()); + assertEquals(ConnectionCheckCode.CHECK_SKIP, check.getCode()); } diff --git a/plugin/control/src/test/java/com/alibaba/nacos/plugin/control/tps/DefaultNacosTpsBarrierTest.java b/plugin/control/src/test/java/com/alibaba/nacos/plugin/control/tps/DefaultNacosTpsBarrierTest.java index 6658f4f2574..ffff75dfd2b 100644 --- a/plugin/control/src/test/java/com/alibaba/nacos/plugin/control/tps/DefaultNacosTpsBarrierTest.java +++ b/plugin/control/src/test/java/com/alibaba/nacos/plugin/control/tps/DefaultNacosTpsBarrierTest.java @@ -16,31 +16,32 @@ package com.alibaba.nacos.plugin.control.tps; -import com.alibaba.nacos.plugin.control.tps.barrier.TpsBarrier; import com.alibaba.nacos.plugin.control.tps.barrier.DefaultNacosTpsBarrier; +import com.alibaba.nacos.plugin.control.tps.barrier.TpsBarrier; import com.alibaba.nacos.plugin.control.tps.request.TpsCheckRequest; import com.alibaba.nacos.plugin.control.tps.response.TpsCheckResponse; import com.alibaba.nacos.plugin.control.tps.rule.RuleDetail; import com.alibaba.nacos.plugin.control.tps.rule.TpsControlRule; -import org.junit.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.util.concurrent.TimeUnit; -public class DefaultNacosTpsBarrierTest { +import static org.junit.jupiter.api.Assertions.assertTrue; + +class DefaultNacosTpsBarrierTest { - @Before - public void setUp() { + @BeforeEach + void setUp() { } - @After - public void after() { + @AfterEach + void after() { } @Test - public void testNormalPointPassAndDeny() { + void testNormalPointPassAndDeny() { String testTpsBarrier = "test_barrier"; // max 5tps @@ -63,7 +64,7 @@ public void testNormalPointPassAndDeny() { // 5tps check pass for (int i = 0; i < 5; i++) { TpsCheckResponse tpsCheckResponse = tpsBarrier.applyTps(tpsCheckRequest); - Assert.assertTrue(tpsCheckResponse.isSuccess()); + assertTrue(tpsCheckResponse.isSuccess()); } } diff --git a/plugin/control/src/test/java/com/alibaba/nacos/plugin/control/utils/DiskUtilsTest.java b/plugin/control/src/test/java/com/alibaba/nacos/plugin/control/utils/DiskUtilsTest.java index 837ce41b2fc..bb61475bcc7 100644 --- a/plugin/control/src/test/java/com/alibaba/nacos/plugin/control/utils/DiskUtilsTest.java +++ b/plugin/control/src/test/java/com/alibaba/nacos/plugin/control/utils/DiskUtilsTest.java @@ -16,10 +16,9 @@ package com.alibaba.nacos.plugin.control.utils; -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.io.File; import java.io.FileInputStream; @@ -30,46 +29,52 @@ import java.nio.file.Paths; import java.util.UUID; -public class DiskUtilsTest { - private static File testFile; +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.assertTrue; + +class DiskUtilsTest { private static final String TMP_PATH = EnvUtils.getNacosHome() + File.separator + "data" + File.separator + "tmp" + File.separator; - @BeforeClass - public static void setup() throws IOException { + private static File testFile; + + @BeforeAll + static void setup() throws IOException { testFile = DiskUtils.createTmpFile("nacostmp", ".ut"); } - @AfterClass - public static void tearDown() throws IOException { + @AfterAll + static void tearDown() throws IOException { testFile.deleteOnExit(); } @Test - public void testTouch() throws IOException { + void testTouch() throws IOException { File file = Paths.get(TMP_PATH, "touch.ut").toFile(); - Assert.assertFalse(file.exists()); + assertFalse(file.exists()); DiskUtils.touch(file); - Assert.assertTrue(file.exists()); + assertTrue(file.exists()); file.deleteOnExit(); } @Test - public void testTouchWithFileName() throws IOException { + void testTouchWithFileName() throws IOException { File file = Paths.get(TMP_PATH, UUID.randomUUID().toString()).toFile(); - Assert.assertFalse(file.exists()); + assertFalse(file.exists()); DiskUtils.touch(file.getParent(), file.getName()); - Assert.assertTrue(file.exists()); + assertTrue(file.exists()); file.deleteOnExit(); } @Test - public void testCreateTmpFile() throws IOException { + void testCreateTmpFile() throws IOException { File tmpFile = null; try { tmpFile = DiskUtils.createTmpFile("nacos1", ".ut"); - Assert.assertTrue(tmpFile.getName().startsWith("nacos1")); - Assert.assertTrue(tmpFile.getName().endsWith(".ut")); + assertTrue(tmpFile.getName().startsWith("nacos1")); + assertTrue(tmpFile.getName().endsWith(".ut")); } finally { if (tmpFile != null) { tmpFile.deleteOnExit(); @@ -78,13 +83,13 @@ public void testCreateTmpFile() throws IOException { } @Test - public void testCreateTmpFileWithPath() throws IOException { + void testCreateTmpFileWithPath() throws IOException { File tmpFile = null; try { tmpFile = DiskUtils.createTmpFile(TMP_PATH, "nacos1", ".ut"); - Assert.assertEquals(TMP_PATH, tmpFile.getParent() + File.separator); - Assert.assertTrue(tmpFile.getName().startsWith("nacos1")); - Assert.assertTrue(tmpFile.getName().endsWith(".ut")); + assertEquals(TMP_PATH, tmpFile.getParent() + File.separator); + assertTrue(tmpFile.getName().startsWith("nacos1")); + assertTrue(tmpFile.getName().endsWith(".ut")); } finally { if (tmpFile != null) { tmpFile.deleteOnExit(); @@ -93,94 +98,93 @@ public void testCreateTmpFileWithPath() throws IOException { } @Test - public void testReadFile() { - Assert.assertNotNull(DiskUtils.readFile(testFile)); + void testReadFile() { + assertNotNull(DiskUtils.readFile(testFile)); } @Test - public void testReadFileWithInputStream() throws FileNotFoundException { - Assert.assertNotNull(DiskUtils.readFile(new FileInputStream(testFile))); + void testReadFileWithInputStream() throws FileNotFoundException { + assertNotNull(DiskUtils.readFile(new FileInputStream(testFile))); } @Test - public void testReadFileWithPath() { - Assert.assertNotNull(DiskUtils.readFile(testFile.getParent(), testFile.getName())); + void testReadFileWithPath() { + assertNotNull(DiskUtils.readFile(testFile.getParent(), testFile.getName())); } @Test - public void testReadFileBytes() { - Assert.assertNotNull(DiskUtils.readFileBytes(testFile)); + void testReadFileBytes() { + assertNotNull(DiskUtils.readFileBytes(testFile)); } @Test - public void testReadFileBytesWithPath() { - Assert.assertNotNull(DiskUtils.readFileBytes(testFile.getParent(), testFile.getName())); + void testReadFileBytesWithPath() { + assertNotNull(DiskUtils.readFileBytes(testFile.getParent(), testFile.getName())); } @Test - public void writeFile() { - Assert.assertTrue(DiskUtils.writeFile(testFile, "unit test".getBytes(StandardCharsets.UTF_8), false)); - Assert.assertEquals("unit test", DiskUtils.readFile(testFile)); + void writeFile() { + assertTrue(DiskUtils.writeFile(testFile, "unit test".getBytes(StandardCharsets.UTF_8), false)); + assertEquals("unit test", DiskUtils.readFile(testFile)); } @Test - public void deleteQuietly() throws IOException { + void deleteQuietly() throws IOException { File tmpFile = DiskUtils.createTmpFile(UUID.randomUUID().toString(), ".ut"); DiskUtils.deleteQuietly(tmpFile); - Assert.assertFalse(tmpFile.exists()); + assertFalse(tmpFile.exists()); } @Test - public void testDeleteQuietlyWithPath() throws IOException { + void testDeleteQuietlyWithPath() throws IOException { String dir = TMP_PATH + "/" + "diskutils"; DiskUtils.forceMkdir(dir); DiskUtils.createTmpFile(dir, "nacos", ".ut"); Path path = Paths.get(dir); DiskUtils.deleteQuietly(path); - Assert.assertFalse(path.toFile().exists()); + assertFalse(path.toFile().exists()); } @Test - public void testDeleteFile() throws IOException { + void testDeleteFile() throws IOException { File tmpFile = DiskUtils.createTmpFile(UUID.randomUUID().toString(), ".ut"); - Assert.assertTrue(DiskUtils.deleteFile(tmpFile.getParent(), tmpFile.getName())); - Assert.assertFalse(DiskUtils.deleteFile(tmpFile.getParent(), tmpFile.getName())); + assertTrue(DiskUtils.deleteFile(tmpFile.getParent(), tmpFile.getName())); + assertFalse(DiskUtils.deleteFile(tmpFile.getParent(), tmpFile.getName())); } @Test - public void deleteDirectory() throws IOException { + void deleteDirectory() throws IOException { Path diskutils = Paths.get(TMP_PATH, "diskutils"); File file = diskutils.toFile(); if (!file.exists()) { file.mkdir(); } - Assert.assertTrue(file.exists()); + assertTrue(file.exists()); DiskUtils.deleteDirectory(diskutils.toString()); - Assert.assertFalse(file.exists()); + assertFalse(file.exists()); } @Test - public void testForceMkdir() throws IOException { - File dir = Paths.get(TMP_PATH, UUID.randomUUID().toString(), UUID.randomUUID().toString()) - .toFile(); + void testForceMkdir() throws IOException { + File dir = Paths.get(TMP_PATH, UUID.randomUUID().toString(), UUID.randomUUID().toString()).toFile(); DiskUtils.forceMkdir(dir); - Assert.assertTrue(dir.exists()); + assertTrue(dir.exists()); dir.deleteOnExit(); } @Test - public void testForceMkdirWithPath() throws IOException { + void testForceMkdirWithPath() throws IOException { Path path = Paths.get(TMP_PATH, UUID.randomUUID().toString(), UUID.randomUUID().toString()); DiskUtils.forceMkdir(path.toString()); File file = path.toFile(); - Assert.assertTrue(file.exists()); + assertTrue(file.exists()); file.deleteOnExit(); } @Test - public void deleteDirThenMkdir() throws IOException { + void deleteDirThenMkdir() throws IOException { Path path = Paths.get(TMP_PATH, UUID.randomUUID().toString()); DiskUtils.forceMkdir(path.toString()); @@ -190,15 +194,15 @@ public void deleteDirThenMkdir() throws IOException { DiskUtils.deleteDirThenMkdir(path.toString()); File file = path.toFile(); - Assert.assertTrue(file.exists()); - Assert.assertTrue(file.isDirectory()); - Assert.assertTrue(file.list() == null || file.list().length == 0); + assertTrue(file.exists()); + assertTrue(file.isDirectory()); + assertTrue(file.list() == null || file.list().length == 0); file.deleteOnExit(); } @Test - public void testCopyDirectory() throws IOException { + void testCopyDirectory() throws IOException { Path srcPath = Paths.get(TMP_PATH, UUID.randomUUID().toString()); DiskUtils.forceMkdir(srcPath.toString()); File nacos = DiskUtils.createTmpFile(srcPath.toString(), "nacos", ".ut"); @@ -207,36 +211,36 @@ public void testCopyDirectory() throws IOException { DiskUtils.copyDirectory(srcPath.toFile(), destPath.toFile()); File file = Paths.get(destPath.toString(), nacos.getName()).toFile(); - Assert.assertTrue(file.exists()); + assertTrue(file.exists()); DiskUtils.deleteDirectory(srcPath.toString()); DiskUtils.deleteDirectory(destPath.toString()); } @Test - public void testCopyFile() throws IOException { + void testCopyFile() throws IOException { File nacos = DiskUtils.createTmpFile("nacos", ".ut"); DiskUtils.copyFile(testFile, nacos); - Assert.assertEquals(DiskUtils.readFile(testFile), DiskUtils.readFile(nacos)); + assertEquals(DiskUtils.readFile(testFile), DiskUtils.readFile(nacos)); nacos.deleteOnExit(); } @Test - public void openFile() { + void openFile() { File file = DiskUtils.openFile(testFile.getParent(), testFile.getName()); - Assert.assertNotNull(file); - Assert.assertEquals(testFile.getPath(), file.getPath()); - Assert.assertEquals(testFile.getName(), file.getName()); + assertNotNull(file); + assertEquals(testFile.getPath(), file.getPath()); + assertEquals(testFile.getName(), file.getName()); } @Test - public void testOpenFileWithPath() { + void testOpenFileWithPath() { File file = DiskUtils.openFile(testFile.getParent(), testFile.getName(), false); - Assert.assertNotNull(file); - Assert.assertEquals(testFile.getPath(), file.getPath()); - Assert.assertEquals(testFile.getName(), file.getName()); + assertNotNull(file); + assertEquals(testFile.getPath(), file.getPath()); + assertEquals(testFile.getName(), file.getName()); } } diff --git a/plugin/control/src/test/java/com/alibaba/nacos/plugin/control/utils/EnvUtilsTest.java b/plugin/control/src/test/java/com/alibaba/nacos/plugin/control/utils/EnvUtilsTest.java index 260a8d81d41..7299fb0f24c 100644 --- a/plugin/control/src/test/java/com/alibaba/nacos/plugin/control/utils/EnvUtilsTest.java +++ b/plugin/control/src/test/java/com/alibaba/nacos/plugin/control/utils/EnvUtilsTest.java @@ -16,26 +16,27 @@ package com.alibaba.nacos.plugin.control.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; import java.io.File; -public class EnvUtilsTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class EnvUtilsTest { - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { System.clearProperty("nacos.home"); } @Test - public void test() { + void test() { String nacosHome = EnvUtils.getNacosHome(); - Assert.assertEquals(System.getProperty("user.home") + File.separator + "nacos", nacosHome); + assertEquals(System.getProperty("user.home") + File.separator + "nacos", nacosHome); System.setProperty("nacos.home", "test"); String testHome = EnvUtils.getNacosHome(); - Assert.assertEquals("test", testHome); + assertEquals("test", testHome); } } diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/enums/derby/TrustedDerbylFunctionEnum.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/enums/derby/TrustedDerbylFunctionEnum.java new file mode 100644 index 00000000000..ba13fff17f7 --- /dev/null +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/enums/derby/TrustedDerbylFunctionEnum.java @@ -0,0 +1,66 @@ +/* + * Copyright 1999-2018 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.plugin.datasource.enums.derby; + +import java.util.HashMap; +import java.util.Map; + +/** + * The TrustedSqlFunctionEnum enum class is used to enumerate and manage a list of trusted built-in SQL functions. + * By using this enum, you can verify whether a given SQL function is part of the trusted functions list + * to avoid potential SQL injection risks. + * + * @author blake.qiu + */ +public enum TrustedDerbylFunctionEnum { + + /** + * NOW(). + */ + NOW("NOW()", "CURRENT_TIMESTAMP"); + + private static final Map LOOKUP_MAP = new HashMap<>(); + + static { + for (TrustedDerbylFunctionEnum entry : TrustedDerbylFunctionEnum.values()) { + LOOKUP_MAP.put(entry.functionName, entry); + } + } + + private final String functionName; + + private final String function; + + TrustedDerbylFunctionEnum(String functionName, String function) { + this.functionName = functionName; + this.function = function; + } + + /** + * Get the function name. + * + * @param functionName function name + * @return function + */ + public static String getFunctionByName(String functionName) { + TrustedDerbylFunctionEnum entry = LOOKUP_MAP.get(functionName); + if (entry != null) { + return entry.function; + } + throw new IllegalArgumentException(String.format("Invalid function name: %s", functionName)); + } +} diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/enums/mysql/TrustedMysqlFunctionEnum.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/enums/mysql/TrustedMysqlFunctionEnum.java new file mode 100644 index 00000000000..781ba938ddb --- /dev/null +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/enums/mysql/TrustedMysqlFunctionEnum.java @@ -0,0 +1,66 @@ +/* + * Copyright 1999-2018 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.plugin.datasource.enums.mysql; + +import java.util.HashMap; +import java.util.Map; + +/** + * The TrustedSqlFunctionEnum enum class is used to enumerate and manage a list of trusted built-in SQL functions. + * By using this enum, you can verify whether a given SQL function is part of the trusted functions list + * to avoid potential SQL injection risks. + * + * @author blake.qiu + */ +public enum TrustedMysqlFunctionEnum { + + /** + * NOW(). + */ + NOW("NOW()", "NOW(3)"); + + private static final Map LOOKUP_MAP = new HashMap<>(); + + static { + for (TrustedMysqlFunctionEnum entry : TrustedMysqlFunctionEnum.values()) { + LOOKUP_MAP.put(entry.functionName, entry); + } + } + + private final String functionName; + + private final String function; + + TrustedMysqlFunctionEnum(String functionName, String function) { + this.functionName = functionName; + this.function = function; + } + + /** + * Get the function name. + * + * @param functionName function name + * @return function + */ + public static String getFunctionByName(String functionName) { + TrustedMysqlFunctionEnum entry = LOOKUP_MAP.get(functionName); + if (entry != null) { + return entry.function; + } + throw new IllegalArgumentException(String.format("Invalid function name: %s", functionName)); + } +} diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/AbstractMapperByDerby.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/AbstractMapperByDerby.java new file mode 100644 index 00000000000..c15171d436b --- /dev/null +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/AbstractMapperByDerby.java @@ -0,0 +1,34 @@ +/* + * Copyright 1999-2022 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.plugin.datasource.impl.derby; + +import com.alibaba.nacos.plugin.datasource.enums.derby.TrustedDerbylFunctionEnum; +import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper; + +/** + * The abstract derby mapper contains CRUD methods. + * + * @author blake.qiu + **/ +public abstract class AbstractMapperByDerby extends AbstractMapper { + + @Override + public String getFunction(String functionName) { + return TrustedDerbylFunctionEnum.getFunctionByName(functionName); + } + +} diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoAggrMapperByDerby.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoAggrMapperByDerby.java index 01ba4a8177f..3750ab86512 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoAggrMapperByDerby.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoAggrMapperByDerby.java @@ -19,7 +19,6 @@ import com.alibaba.nacos.common.utils.CollectionUtils; import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; import com.alibaba.nacos.plugin.datasource.constants.FieldConstant; -import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper; import com.alibaba.nacos.plugin.datasource.mapper.ConfigInfoAggrMapper; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; @@ -31,8 +30,8 @@ * * @author hyx **/ -public class ConfigInfoAggrMapperByDerby extends AbstractMapper implements ConfigInfoAggrMapper { - +public class ConfigInfoAggrMapperByDerby extends AbstractMapperByDerby implements ConfigInfoAggrMapper { + @Override public MapperResult findConfigInfoAggrByPageFetchRows(MapperContext context) { final Integer startRow = context.getStartRow(); @@ -40,7 +39,7 @@ public MapperResult findConfigInfoAggrByPageFetchRows(MapperContext context) { final String dataId = (String) context.getWhereParameter(FieldConstant.DATA_ID); final String groupId = (String) context.getWhereParameter(FieldConstant.GROUP_ID); final String tenantId = (String) context.getWhereParameter(FieldConstant.TENANT_ID); - + String sql = "SELECT data_id,group_id,tenant_id,datum_id,app_name,content FROM config_info_aggr WHERE data_id=? AND " + "group_id=? AND tenant_id=? ORDER BY datum_id OFFSET " + startRow + " ROWS FETCH NEXT " diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoBetaMapperByDerby.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoBetaMapperByDerby.java index da3556e0096..6d08bd399ba 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoBetaMapperByDerby.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoBetaMapperByDerby.java @@ -17,7 +17,6 @@ package com.alibaba.nacos.plugin.datasource.impl.derby; import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; -import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper; import com.alibaba.nacos.plugin.datasource.mapper.ConfigInfoBetaMapper; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; @@ -31,17 +30,17 @@ * @author hyx **/ -public class ConfigInfoBetaMapperByDerby extends AbstractMapper implements ConfigInfoBetaMapper { +public class ConfigInfoBetaMapperByDerby extends AbstractMapperByDerby implements ConfigInfoBetaMapper { @Override public MapperResult findAllConfigInfoBetaForDumpAllFetchRows(MapperContext context) { Integer startRow = context.getStartRow(); int pageSize = context.getPageSize(); - + String sql = "SELECT t.id,data_id,group_id,tenant_id,app_name,content,md5,gmt_modified,beta_ips " + " FROM ( SELECT id FROM config_info_beta ORDER BY id OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY )" + " g, config_info_beta t WHERE g.id = t.id"; - + List paramList = new ArrayList<>(); paramList.add(startRow); paramList.add(pageSize); diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoMapperByDerby.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoMapperByDerby.java index 2ed72f578f7..e3cfb04afa4 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoMapperByDerby.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoMapperByDerby.java @@ -16,14 +16,15 @@ package com.alibaba.nacos.plugin.datasource.impl.derby; +import com.alibaba.nacos.common.utils.ArrayUtils; import com.alibaba.nacos.common.utils.CollectionUtils; import com.alibaba.nacos.common.utils.NamespaceUtil; import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.plugin.datasource.constants.ContextConstant; import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; import com.alibaba.nacos.plugin.datasource.constants.FieldConstant; -import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper; import com.alibaba.nacos.plugin.datasource.mapper.ConfigInfoMapper; +import com.alibaba.nacos.plugin.datasource.mapper.ext.WhereBuilder; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; @@ -38,7 +39,7 @@ * @author hyx **/ -public class ConfigInfoMapperByDerby extends AbstractMapper implements ConfigInfoMapper { +public class ConfigInfoMapperByDerby extends AbstractMapperByDerby implements ConfigInfoMapper { @Override public MapperResult findConfigInfoByAppFetchRows(MapperContext context) { @@ -234,33 +235,29 @@ public MapperResult findConfigInfoLike4PageFetchRows(MapperContext context) { final String group = (String) context.getWhereParameter(FieldConstant.GROUP_ID); final String appName = (String) context.getWhereParameter(FieldConstant.APP_NAME); final String content = (String) context.getWhereParameter(FieldConstant.CONTENT); + final String[] types = (String[]) context.getWhereParameter(FieldConstant.TYPE); - List paramList = new ArrayList<>(); - - final String sqlFetchRows = "SELECT id,data_id,group_id,tenant_id,app_name,content,encrypted_data_key FROM config_info"; - StringBuilder where = new StringBuilder(" WHERE "); - where.append(" tenant_id LIKE ? "); - paramList.add(tenantId); - if (!StringUtils.isBlank(dataId)) { - where.append(" AND data_id LIKE ? "); - paramList.add(dataId); + WhereBuilder where = new WhereBuilder( + "SELECT id,data_id,group_id,tenant_id,app_name,content,encrypted_data_key,type FROM config_info"); + where.like("tenant_id", tenantId); + if (StringUtils.isNotBlank(dataId)) { + where.and().like("data_id", dataId); } - if (!StringUtils.isBlank(group)) { - where.append(" AND group_id LIKE ? "); - paramList.add(group); + if (StringUtils.isNotBlank(group)) { + where.and().like("group_id", group); } - if (!StringUtils.isBlank(appName)) { - where.append(" AND app_name = ? "); - paramList.add(appName); + if (StringUtils.isNotBlank(appName)) { + where.and().eq("app_name", appName); } - if (!StringUtils.isBlank(content)) { - where.append(" AND content LIKE ? "); - paramList.add(content); + if (StringUtils.isNotBlank(content)) { + where.and().like("content", content); } - String sql = - sqlFetchRows + where + " OFFSET " + context.getStartRow() + " ROWS FETCH NEXT " + context.getPageSize() - + " ROWS ONLY"; - return new MapperResult(sql, paramList); + if (!ArrayUtils.isEmpty(types)) { + where.and().in("type", types); + } + + where.offset(context.getStartRow(), context.getPageSize()); + return where.build(); } @Override diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoTagMapperByDerby.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoTagMapperByDerby.java index 3134871e47e..fd6db41547a 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoTagMapperByDerby.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoTagMapperByDerby.java @@ -17,7 +17,6 @@ package com.alibaba.nacos.plugin.datasource.impl.derby; import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; -import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper; import com.alibaba.nacos.plugin.datasource.mapper.ConfigInfoTagMapper; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; @@ -30,8 +29,8 @@ * @author hyx **/ -public class ConfigInfoTagMapperByDerby extends AbstractMapper implements ConfigInfoTagMapper { - +public class ConfigInfoTagMapperByDerby extends AbstractMapperByDerby implements ConfigInfoTagMapper { + @Override public MapperResult findAllConfigInfoTagForDumpAllFetchRows(MapperContext context) { String sql = "SELECT t.id,data_id,group_id,tenant_id,tag_id,app_name,content,md5,gmt_modified " @@ -40,7 +39,7 @@ public MapperResult findAllConfigInfoTagForDumpAllFetchRows(MapperContext contex + " g, config_info_tag t WHERE g.id = t.id"; return new MapperResult(sql, Collections.emptyList()); } - + @Override public String getDataSource() { return DataSourceConstant.DERBY; diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoTagsRelationMapperByDerby.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoTagsRelationMapperByDerby.java index d8de7c03762..0c277124287 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoTagsRelationMapperByDerby.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoTagsRelationMapperByDerby.java @@ -16,11 +16,12 @@ package com.alibaba.nacos.plugin.datasource.impl.derby; +import com.alibaba.nacos.common.utils.ArrayUtils; import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; import com.alibaba.nacos.plugin.datasource.constants.FieldConstant; -import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper; import com.alibaba.nacos.plugin.datasource.mapper.ConfigTagsRelationMapper; +import com.alibaba.nacos.plugin.datasource.mapper.ext.WhereBuilder; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; @@ -33,7 +34,7 @@ * @author hyx **/ -public class ConfigInfoTagsRelationMapperByDerby extends AbstractMapper implements ConfigTagsRelationMapper { +public class ConfigInfoTagsRelationMapperByDerby extends AbstractMapperByDerby implements ConfigTagsRelationMapper { @Override public MapperResult findConfigInfo4PageFetchRows(MapperContext context) { @@ -91,45 +92,35 @@ public MapperResult findConfigInfoLike4PageFetchRows(MapperContext context) { final String content = (String) context.getWhereParameter(FieldConstant.CONTENT); final String tenantId = (String) context.getWhereParameter(FieldConstant.TENANT_ID); final String[] tagArr = (String[]) context.getWhereParameter(FieldConstant.TAG_ARR); + final String[] types = (String[]) context.getWhereParameter(FieldConstant.TYPE); - List paramList = new ArrayList<>(); - StringBuilder where = new StringBuilder(" WHERE "); - final String baseSql = - "SELECT a.ID,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content FROM config_info a LEFT JOIN " - + "config_tags_relation b ON a.id=b.id "; + WhereBuilder where = new WhereBuilder( + "SELECT a.ID,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content,a.type FROM config_info a LEFT JOIN " + + "config_tags_relation b ON a.id=b.id"); - where.append(" a.tenant_id LIKE ? "); - paramList.add(tenantId); + where.like("a.tenant_id", tenantId); - if (!StringUtils.isBlank(dataId)) { - where.append(" AND a.data_id LIKE ? "); - paramList.add(dataId); + if (StringUtils.isNotBlank(dataId)) { + where.and().like("a.data_id", dataId); } - if (!StringUtils.isBlank(group)) { - where.append(" AND a.group_id LIKE ? "); - paramList.add(group); + if (StringUtils.isNotBlank(group)) { + where.and().like("a.group_id", group); } - if (!StringUtils.isBlank(appName)) { - where.append(" AND a.app_name = ? "); - paramList.add(appName); + if (StringUtils.isNotBlank(appName)) { + where.and().eq("a.app_name", appName); } - if (!StringUtils.isBlank(content)) { - where.append(" AND a.content LIKE ? "); - paramList.add(content); + if (StringUtils.isNotBlank(content)) { + where.and().like("a.content", content); } - - where.append(" AND b.tag_name IN ("); - for (int i = 0; i < tagArr.length; i++) { - if (i != 0) { - where.append(", "); - } - where.append('?'); - paramList.add(tagArr[i]); + if (!ArrayUtils.isEmpty(tagArr)) { + where.and().in("b.tag_name", tagArr); } - where.append(") "); - String sql = baseSql + where + " OFFSET " + context.getStartRow() + " ROWS FETCH NEXT " + context.getPageSize() - + " ROWS ONLY"; - return new MapperResult(sql, paramList); + if (!ArrayUtils.isEmpty(types)) { + where.and().in("a.type", types); + } + + where.offset(context.getStartRow(), context.getPageSize()); + return where.build(); } @Override diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/GroupCapacityMapperByDerby.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/GroupCapacityMapperByDerby.java index 39a74583c4b..3913cc52744 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/GroupCapacityMapperByDerby.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/GroupCapacityMapperByDerby.java @@ -19,7 +19,6 @@ import com.alibaba.nacos.common.utils.CollectionUtils; import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; import com.alibaba.nacos.plugin.datasource.constants.FieldConstant; -import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper; import com.alibaba.nacos.plugin.datasource.mapper.GroupCapacityMapper; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; @@ -29,13 +28,13 @@ * * @author lixiaoshuang */ -public class GroupCapacityMapperByDerby extends AbstractMapper implements GroupCapacityMapper { - +public class GroupCapacityMapperByDerby extends AbstractMapperByDerby implements GroupCapacityMapper { + @Override public String getDataSource() { return DataSourceConstant.DERBY; } - + @Override public MapperResult selectGroupInfoBySize(MapperContext context) { String sql = "SELECT id, group_id FROM group_capacity WHERE id > ? OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY"; diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/HistoryConfigInfoMapperByDerby.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/HistoryConfigInfoMapperByDerby.java index d17f12ddd7e..08942c9a4fe 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/HistoryConfigInfoMapperByDerby.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/HistoryConfigInfoMapperByDerby.java @@ -19,7 +19,6 @@ import com.alibaba.nacos.common.utils.CollectionUtils; import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; import com.alibaba.nacos.plugin.datasource.constants.FieldConstant; -import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper; import com.alibaba.nacos.plugin.datasource.mapper.HistoryConfigInfoMapper; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; @@ -30,8 +29,8 @@ * @author hyx **/ -public class HistoryConfigInfoMapperByDerby extends AbstractMapper implements HistoryConfigInfoMapper { - +public class HistoryConfigInfoMapperByDerby extends AbstractMapperByDerby implements HistoryConfigInfoMapper { + @Override public MapperResult removeConfigHistory(MapperContext context) { String sql = "DELETE FROM his_config_info WHERE id IN( " @@ -39,7 +38,7 @@ public MapperResult removeConfigHistory(MapperContext context) { return new MapperResult(sql, CollectionUtils.list(context.getWhereParameter(FieldConstant.START_TIME), context.getWhereParameter(FieldConstant.LIMIT_SIZE))); } - + @Override public MapperResult pageFindConfigHistoryFetchRows(MapperContext context) { String sql = diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/TenantCapacityMapperByDerby.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/TenantCapacityMapperByDerby.java index d185ccade6a..13d8f02fbc5 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/TenantCapacityMapperByDerby.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/TenantCapacityMapperByDerby.java @@ -19,7 +19,6 @@ import com.alibaba.nacos.common.utils.CollectionUtils; import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; import com.alibaba.nacos.plugin.datasource.constants.FieldConstant; -import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper; import com.alibaba.nacos.plugin.datasource.mapper.TenantCapacityMapper; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; @@ -30,13 +29,13 @@ * @author hyx **/ -public class TenantCapacityMapperByDerby extends AbstractMapper implements TenantCapacityMapper { - +public class TenantCapacityMapperByDerby extends AbstractMapperByDerby implements TenantCapacityMapper { + @Override public String getDataSource() { return DataSourceConstant.DERBY; } - + @Override public MapperResult getCapacityList4CorrectUsage(MapperContext context) { String sql = "SELECT id, tenant_id FROM tenant_capacity WHERE id>? OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY"; diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/TenantInfoMapperByDerby.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/TenantInfoMapperByDerby.java index 6fd12d13b7f..fb9c67dbf86 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/TenantInfoMapperByDerby.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/derby/TenantInfoMapperByDerby.java @@ -17,7 +17,6 @@ package com.alibaba.nacos.plugin.datasource.impl.derby; import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; -import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper; import com.alibaba.nacos.plugin.datasource.mapper.TenantInfoMapper; /** @@ -26,7 +25,7 @@ * @author hyx **/ -public class TenantInfoMapperByDerby extends AbstractMapper implements TenantInfoMapper { +public class TenantInfoMapperByDerby extends AbstractMapperByDerby implements TenantInfoMapper { @Override public String getDataSource() { diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/AbstractMapperByMysql.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/AbstractMapperByMysql.java new file mode 100644 index 00000000000..776a7ac1e9c --- /dev/null +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/AbstractMapperByMysql.java @@ -0,0 +1,33 @@ +/* + * Copyright 1999-2022 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.plugin.datasource.impl.mysql; + +import com.alibaba.nacos.plugin.datasource.enums.mysql.TrustedMysqlFunctionEnum; +import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper; + +/** + * The abstract mysql mapper contains CRUD methods. + * + * @author blake.qiu + **/ +public abstract class AbstractMapperByMysql extends AbstractMapper { + + @Override + public String getFunction(String functionName) { + return TrustedMysqlFunctionEnum.getFunctionByName(functionName); + } +} diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoAggrMapperByMySql.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoAggrMapperByMySql.java index f9bad4153f7..03382271cb0 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoAggrMapperByMySql.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoAggrMapperByMySql.java @@ -19,7 +19,6 @@ import com.alibaba.nacos.common.utils.CollectionUtils; import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; import com.alibaba.nacos.plugin.datasource.constants.FieldConstant; -import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper; import com.alibaba.nacos.plugin.datasource.mapper.ConfigInfoAggrMapper; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; @@ -31,16 +30,16 @@ * * @author hyx **/ -public class ConfigInfoAggrMapperByMySql extends AbstractMapper implements ConfigInfoAggrMapper { - +public class ConfigInfoAggrMapperByMySql extends AbstractMapperByMysql implements ConfigInfoAggrMapper { + @Override public MapperResult findConfigInfoAggrByPageFetchRows(MapperContext context) { - int startRow = context.getStartRow(); - int pageSize = context.getPageSize(); + int startRow = context.getStartRow(); + int pageSize = context.getPageSize(); String dataId = (String) context.getWhereParameter(FieldConstant.DATA_ID); String groupId = (String) context.getWhereParameter(FieldConstant.GROUP_ID); String tenantId = (String) context.getWhereParameter(FieldConstant.TENANT_ID); - + String sql = "SELECT data_id,group_id,tenant_id,datum_id,app_name,content FROM config_info_aggr WHERE data_id= ? AND " + "group_id= ? AND tenant_id= ? ORDER BY datum_id LIMIT " + startRow + "," + pageSize; diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoBetaMapperByMySql.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoBetaMapperByMySql.java index 6fe9b12070d..94da53ff77e 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoBetaMapperByMySql.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoBetaMapperByMySql.java @@ -17,7 +17,6 @@ package com.alibaba.nacos.plugin.datasource.impl.mysql; import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; -import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper; import com.alibaba.nacos.plugin.datasource.mapper.ConfigInfoBetaMapper; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; @@ -31,7 +30,7 @@ * @author hyx **/ -public class ConfigInfoBetaMapperByMySql extends AbstractMapper implements ConfigInfoBetaMapper { +public class ConfigInfoBetaMapperByMySql extends AbstractMapperByMysql implements ConfigInfoBetaMapper { @Override public MapperResult findAllConfigInfoBetaForDumpAllFetchRows(MapperContext context) { diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoMapperByMySql.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoMapperByMySql.java index f4c05ac71fb..dd4de5b6efe 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoMapperByMySql.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoMapperByMySql.java @@ -16,14 +16,15 @@ package com.alibaba.nacos.plugin.datasource.impl.mysql; +import com.alibaba.nacos.common.utils.ArrayUtils; import com.alibaba.nacos.common.utils.CollectionUtils; import com.alibaba.nacos.common.utils.NamespaceUtil; import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.plugin.datasource.constants.ContextConstant; import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; import com.alibaba.nacos.plugin.datasource.constants.FieldConstant; -import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper; import com.alibaba.nacos.plugin.datasource.mapper.ConfigInfoMapper; +import com.alibaba.nacos.plugin.datasource.mapper.ext.WhereBuilder; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; @@ -38,7 +39,7 @@ * @author hyx **/ -public class ConfigInfoMapperByMySql extends AbstractMapper implements ConfigInfoMapper { +public class ConfigInfoMapperByMySql extends AbstractMapperByMysql implements ConfigInfoMapper { private static final String DATA_ID = "dataId"; @@ -84,9 +85,10 @@ public MapperResult findAllConfigKey(MapperContext context) { @Override public MapperResult findAllConfigInfoBaseFetchRows(MapperContext context) { - String sql = "SELECT t.id,data_id,group_id,content,md5" - + " FROM ( SELECT id FROM config_info ORDER BY id LIMIT " + context.getStartRow() + "," - + context.getPageSize() + " )" + " g, config_info t WHERE g.id = t.id "; + String sql = + "SELECT t.id,data_id,group_id,content,md5" + " FROM ( SELECT id FROM config_info ORDER BY id LIMIT " + + context.getStartRow() + "," + context.getPageSize() + " )" + + " g, config_info t WHERE g.id = t.id "; return new MapperResult(sql, Collections.emptyList()); } @@ -229,33 +231,29 @@ public MapperResult findConfigInfoLike4PageFetchRows(MapperContext context) { final String group = (String) context.getWhereParameter(FieldConstant.GROUP_ID); final String appName = (String) context.getWhereParameter(FieldConstant.APP_NAME); final String content = (String) context.getWhereParameter(FieldConstant.CONTENT); + final String[] types = (String[]) context.getWhereParameter(FieldConstant.TYPE); - List paramList = new ArrayList<>(); + WhereBuilder where = new WhereBuilder( + "SELECT id,data_id,group_id,tenant_id,app_name,content,encrypted_data_key,type FROM config_info"); + where.like("tenant_id", tenant); - final String sqlFetchRows = "SELECT id,data_id,group_id,tenant_id,app_name,content,encrypted_data_key FROM config_info"; - StringBuilder where = new StringBuilder(" WHERE "); - where.append(" tenant_id LIKE ? "); - paramList.add(tenant); - - if (!StringUtils.isBlank(dataId)) { - where.append(" AND data_id LIKE ? "); - paramList.add(dataId); - + if (StringUtils.isNotBlank(dataId)) { + where.and().like("data_id", dataId); } - if (!StringUtils.isBlank(group)) { - where.append(" AND group_id LIKE ? "); - paramList.add(group); + if (StringUtils.isNotBlank(group)) { + where.and().like("group_id", group); } - if (!StringUtils.isBlank(appName)) { - where.append(" AND app_name = ? "); - paramList.add(appName); + if (StringUtils.isNotBlank(appName)) { + where.and().eq("app_name", appName); } - if (!StringUtils.isBlank(content)) { - where.append(" AND content LIKE ? "); - paramList.add(content); + if (StringUtils.isNotBlank(content)) { + where.and().like("content", content); } - return new MapperResult(sqlFetchRows + where + " LIMIT " + context.getStartRow() + "," + context.getPageSize(), - paramList); + if (!ArrayUtils.isEmpty(types)) { + where.in("type", types); + } + where.limit(context.getStartRow(), context.getPageSize()); + return where.build(); } @Override diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoTagMapperByMySql.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoTagMapperByMySql.java index 25dbb0720c2..917d84ec0ba 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoTagMapperByMySql.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoTagMapperByMySql.java @@ -17,7 +17,6 @@ package com.alibaba.nacos.plugin.datasource.impl.mysql; import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; -import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper; import com.alibaba.nacos.plugin.datasource.mapper.ConfigInfoTagMapper; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; @@ -30,8 +29,8 @@ * @author hyx **/ -public class ConfigInfoTagMapperByMySql extends AbstractMapper implements ConfigInfoTagMapper { - +public class ConfigInfoTagMapperByMySql extends AbstractMapperByMysql implements ConfigInfoTagMapper { + @Override public MapperResult findAllConfigInfoTagForDumpAllFetchRows(MapperContext context) { String sql = " SELECT t.id,data_id,group_id,tenant_id,tag_id,app_name,content,md5,gmt_modified " @@ -39,7 +38,7 @@ public MapperResult findAllConfigInfoTagForDumpAllFetchRows(MapperContext contex + context.getPageSize() + " ) " + "g, config_info_tag t WHERE g.id = t.id "; return new MapperResult(sql, Collections.emptyList()); } - + @Override public String getDataSource() { return DataSourceConstant.MYSQL; diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigTagsRelationMapperByMySql.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigTagsRelationMapperByMySql.java index 728aee2f442..c921fa6ccb5 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigTagsRelationMapperByMySql.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigTagsRelationMapperByMySql.java @@ -16,11 +16,12 @@ package com.alibaba.nacos.plugin.datasource.impl.mysql; +import com.alibaba.nacos.common.utils.ArrayUtils; import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; import com.alibaba.nacos.plugin.datasource.constants.FieldConstant; -import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper; import com.alibaba.nacos.plugin.datasource.mapper.ConfigTagsRelationMapper; +import com.alibaba.nacos.plugin.datasource.mapper.ext.WhereBuilder; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; @@ -33,7 +34,7 @@ * @author hyx **/ -public class ConfigTagsRelationMapperByMySql extends AbstractMapper implements ConfigTagsRelationMapper { +public class ConfigTagsRelationMapperByMySql extends AbstractMapperByMysql implements ConfigTagsRelationMapper { @Override public MapperResult findConfigInfo4PageFetchRows(MapperContext context) { @@ -90,43 +91,36 @@ public MapperResult findConfigInfoLike4PageFetchRows(MapperContext context) { final String appName = (String) context.getWhereParameter(FieldConstant.APP_NAME); final String content = (String) context.getWhereParameter(FieldConstant.CONTENT); final String[] tagArr = (String[]) context.getWhereParameter(FieldConstant.TAG_ARR); + final String[] types = (String[]) context.getWhereParameter(FieldConstant.TYPE); - List paramList = new ArrayList<>(); + WhereBuilder where = new WhereBuilder( + "SELECT a.id,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content,a.type " + + "FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id"); - StringBuilder where = new StringBuilder(" WHERE "); - final String sqlFetchRows = "SELECT a.id,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content " - + "FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id "; + where.like("a.tenant_id", tenant); - where.append(" a.tenant_id LIKE ? "); - paramList.add(tenant); - if (!StringUtils.isBlank(dataId)) { - where.append(" AND a.data_id LIKE ? "); - paramList.add(dataId); + if (StringUtils.isNotBlank(dataId)) { + where.and().like("a.data_id", dataId); } - if (!StringUtils.isBlank(group)) { - where.append(" AND a.group_id LIKE ? "); - paramList.add(group); + if (StringUtils.isNotBlank(group)) { + where.and().like("a.group_id", group); } - if (!StringUtils.isBlank(appName)) { - where.append(" AND a.app_name = ? "); - paramList.add(appName); + if (StringUtils.isNotBlank(appName)) { + where.and().eq("a.app_name", appName); } - if (!StringUtils.isBlank(content)) { - where.append(" AND a.content LIKE ? "); - paramList.add(content); + if (StringUtils.isNotBlank(content)) { + where.and().like("a.content", content); } - - where.append(" AND b.tag_name IN ("); - for (int i = 0; i < tagArr.length; i++) { - if (i != 0) { - where.append(", "); - } - where.append('?'); - paramList.add(tagArr[i]); + if (!ArrayUtils.isEmpty(tagArr)) { + where.and().in("b.tag_name", tagArr); } - where.append(") "); - return new MapperResult(sqlFetchRows + where + " LIMIT " + context.getStartRow() + "," + context.getPageSize(), - paramList); + if (!ArrayUtils.isEmpty(types)) { + where.and().in("a.type", types); + } + + where.limit(context.getStartRow(), context.getPageSize()); + + return where.build(); } @Override diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/GroupCapacityMapperByMysql.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/GroupCapacityMapperByMysql.java index 3c4fc9460b1..070578d1cc1 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/GroupCapacityMapperByMysql.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/GroupCapacityMapperByMysql.java @@ -19,7 +19,6 @@ import com.alibaba.nacos.common.utils.CollectionUtils; import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; import com.alibaba.nacos.plugin.datasource.constants.FieldConstant; -import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper; import com.alibaba.nacos.plugin.datasource.mapper.GroupCapacityMapper; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; @@ -29,13 +28,13 @@ * * @author lixiaoshuang */ -public class GroupCapacityMapperByMysql extends AbstractMapper implements GroupCapacityMapper { - +public class GroupCapacityMapperByMysql extends AbstractMapperByMysql implements GroupCapacityMapper { + @Override public String getDataSource() { return DataSourceConstant.MYSQL; } - + @Override public MapperResult selectGroupInfoBySize(MapperContext context) { String sql = "SELECT id, group_id FROM group_capacity WHERE id > ? LIMIT ?"; diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/HistoryConfigInfoMapperByMySql.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/HistoryConfigInfoMapperByMySql.java index ecbbe700f9c..39ec2a8ca0e 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/HistoryConfigInfoMapperByMySql.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/HistoryConfigInfoMapperByMySql.java @@ -19,7 +19,6 @@ import com.alibaba.nacos.common.utils.CollectionUtils; import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; import com.alibaba.nacos.plugin.datasource.constants.FieldConstant; -import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper; import com.alibaba.nacos.plugin.datasource.mapper.HistoryConfigInfoMapper; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; @@ -30,15 +29,15 @@ * @author hyx **/ -public class HistoryConfigInfoMapperByMySql extends AbstractMapper implements HistoryConfigInfoMapper { - +public class HistoryConfigInfoMapperByMySql extends AbstractMapperByMysql implements HistoryConfigInfoMapper { + @Override public MapperResult removeConfigHistory(MapperContext context) { String sql = "DELETE FROM his_config_info WHERE gmt_modified < ? LIMIT ?"; return new MapperResult(sql, CollectionUtils.list(context.getWhereParameter(FieldConstant.START_TIME), context.getWhereParameter(FieldConstant.LIMIT_SIZE))); } - + @Override public MapperResult pageFindConfigHistoryFetchRows(MapperContext context) { String sql = diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/TenantCapacityMapperByMySql.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/TenantCapacityMapperByMySql.java index 7b8dc09417e..43aa074f30f 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/TenantCapacityMapperByMySql.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/TenantCapacityMapperByMySql.java @@ -19,7 +19,6 @@ import com.alibaba.nacos.common.utils.CollectionUtils; import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; import com.alibaba.nacos.plugin.datasource.constants.FieldConstant; -import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper; import com.alibaba.nacos.plugin.datasource.mapper.TenantCapacityMapper; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; @@ -30,13 +29,13 @@ * @author hyx **/ -public class TenantCapacityMapperByMySql extends AbstractMapper implements TenantCapacityMapper { - +public class TenantCapacityMapperByMySql extends AbstractMapperByMysql implements TenantCapacityMapper { + @Override public String getDataSource() { return DataSourceConstant.MYSQL; } - + @Override public MapperResult getCapacityList4CorrectUsage(MapperContext context) { String sql = "SELECT id, tenant_id FROM tenant_capacity WHERE id>? LIMIT ?"; diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/TenantInfoMapperByMySql.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/TenantInfoMapperByMySql.java index 1de0be12d2a..fb2e5506403 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/TenantInfoMapperByMySql.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/mysql/TenantInfoMapperByMySql.java @@ -17,7 +17,6 @@ package com.alibaba.nacos.plugin.datasource.impl.mysql; import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; -import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper; import com.alibaba.nacos.plugin.datasource.mapper.TenantInfoMapper; /** @@ -26,7 +25,7 @@ * @author hyx **/ -public class TenantInfoMapperByMySql extends AbstractMapper implements TenantInfoMapper { +public class TenantInfoMapperByMySql extends AbstractMapperByMysql implements TenantInfoMapper { @Override public String getDataSource() { diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/AbstractMapper.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/AbstractMapper.java index 571c7219ade..ba85b7ffaaa 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/AbstractMapper.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/AbstractMapper.java @@ -27,7 +27,7 @@ **/ public abstract class AbstractMapper implements Mapper { - + @Override public String select(List columns, List where) { StringBuilder sql = new StringBuilder(); @@ -44,36 +44,41 @@ public String select(List columns, List where) { sql.append("FROM "); sql.append(getTableName()); sql.append(" "); - + if (CollectionUtils.isEmpty(where)) { return sql.toString(); } - + appendWhereClause(where, sql); return sql.toString(); } - + @Override public String insert(List columns) { StringBuilder sql = new StringBuilder(); String method = "INSERT INTO "; sql.append(method); sql.append(getTableName()); - + int size = columns.size(); sql.append("("); for (int i = 0; i < size; i++) { - sql.append(columns.get(i)); + sql.append(columns.get(i).split("@")[0]); if (i != columns.size() - 1) { sql.append(", "); } } sql.append(") "); - + sql.append("VALUES"); sql.append("("); for (int i = 0; i < size; i++) { - sql.append("?"); + String[] parts = columns.get(i).split("@"); + if (parts.length == 2) { + sql.append(getFunction(parts[1])); + } else { + sql.append("?"); + } if (i != columns.size() - 1) { sql.append(","); } @@ -81,31 +86,37 @@ public String insert(List columns) { sql.append(")"); return sql.toString(); } - + @Override public String update(List columns, List where) { StringBuilder sql = new StringBuilder(); String method = "UPDATE "; sql.append(method); sql.append(getTableName()).append(" ").append("SET "); - + for (int i = 0; i < columns.size(); i++) { - sql.append(columns.get(i)).append(" = ").append("?"); + String[] parts = columns.get(i).split("@"); + String column = parts[0]; + if (parts.length == 2) { + sql.append(column).append(" = ").append(getFunction(parts[1])); + } else { + sql.append(column).append(" = ").append("?"); + } if (i != columns.size() - 1) { sql.append(","); } } - + if (CollectionUtils.isEmpty(where)) { return sql.toString(); } - + sql.append(" "); appendWhereClause(where, sql); - + return sql.toString(); } - + @Override public String delete(List params) { StringBuilder sql = new StringBuilder(); @@ -117,10 +128,10 @@ public String delete(List params) { sql.append("AND "); } } - + return sql.toString(); } - + @Override public String count(List where) { StringBuilder sql = new StringBuilder(); @@ -129,21 +140,21 @@ public String count(List where) { sql.append("COUNT(*) FROM "); sql.append(getTableName()); sql.append(" "); - + if (null == where || where.size() == 0) { return sql.toString(); } - + appendWhereClause(where, sql); - + return sql.toString(); } - + @Override public String[] getPrimaryKeyGeneratedKeys() { - return new String[] {"id"}; + return new String[]{"id"}; } - + private void appendWhereClause(List where, StringBuilder sql) { sql.append("WHERE "); for (int i = 0; i < where.size(); i++) { diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/ConfigInfoBetaMapper.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/ConfigInfoBetaMapper.java index 511ca2bf57b..95fa4a385ff 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/ConfigInfoBetaMapper.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/ConfigInfoBetaMapper.java @@ -42,17 +42,18 @@ public interface ConfigInfoBetaMapper extends Mapper { * @return The result of updating beta configuration information. */ default MapperResult updateConfigInfo4BetaCas(MapperContext context) { - final String sql = "UPDATE config_info_beta SET content = ?,md5 = ?,beta_ips = ?,src_ip = ?,src_user = ?,gmt_modified = ?,app_name = ? " + final String sql = "UPDATE config_info_beta SET content = ?,md5 = ?,beta_ips = ?,src_ip = ?,src_user = ?,gmt_modified = " + + getFunction("NOW()") + + ",app_name = ? " + "WHERE data_id = ? AND group_id = ? AND tenant_id = ? AND (md5 = ? OR md5 is null OR md5 = '')"; - + List paramList = new ArrayList<>(); - + paramList.add(context.getUpdateParameter(FieldConstant.CONTENT)); paramList.add(context.getUpdateParameter(FieldConstant.MD5)); paramList.add(context.getUpdateParameter(FieldConstant.BETA_IPS)); paramList.add(context.getUpdateParameter(FieldConstant.SRC_IP)); paramList.add(context.getUpdateParameter(FieldConstant.SRC_USER)); - paramList.add(context.getUpdateParameter(FieldConstant.GMT_MODIFIED)); paramList.add(context.getUpdateParameter(FieldConstant.APP_NAME)); paramList.add(context.getWhereParameter(FieldConstant.DATA_ID)); diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/ConfigInfoMapper.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/ConfigInfoMapper.java index ba7f7a521d2..a24e37a2bf9 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/ConfigInfoMapper.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/ConfigInfoMapper.java @@ -16,11 +16,13 @@ package com.alibaba.nacos.plugin.datasource.mapper; +import com.alibaba.nacos.common.utils.ArrayUtils; import com.alibaba.nacos.common.utils.CollectionUtils; import com.alibaba.nacos.common.utils.NamespaceUtil; import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.plugin.datasource.constants.FieldConstant; import com.alibaba.nacos.plugin.datasource.constants.TableConstant; +import com.alibaba.nacos.plugin.datasource.mapper.ext.WhereBuilder; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; @@ -73,7 +75,7 @@ default MapperResult findConfigInfoByAppCountRows(MapperContext context) { /** * Query configuration information based on group.
    The default sql: SELECT - * id,data_id,group_id,tenant_id,app_name,content FROM config_info WHERE tenant_id LIKE ? AND app_name=? + * id,data_id,group_id,tenant_id,app_name,content FROM config_info WHERE tenant_id LIKE ? AND app_name=? LIMIT startRow, pageSize * * @param context The context of startRow, pageSize * @return The sql of querying configration information based on group. @@ -114,7 +116,7 @@ default MapperResult configInfoLikeTenantCount(MapperContext context) { /** * Query all configuration information by page. The default sql: SELECT data_id,group_id,app_name FROM ( SELECT id * FROM config_info WHERE tenant_id LIKE ? ORDER BY id LIMIT startRow, pageSize ) g, config_info t WHERE g.id = t.id - * " + * * * @param context The context of startRow, pageSize * @return The sql of querying all configuration information. @@ -131,9 +133,9 @@ default MapperResult configInfoLikeTenantCount(MapperContext context) { MapperResult findAllConfigInfoBaseFetchRows(MapperContext context); /** - * Query all config info. The default sql: SELECT - * id,data_id,group_id,tenant_id,app_name,content,md5,gmt_modified,type,encrypted_data_key FROM config_info WHERE id - * > ? ORDER BY id ASC LIMIT startRow,pageSize + * Query all config info. The default sql: "SELECT + * id,data_id,group_id,tenant_id,app_name,"+ (needContent ? "content," : "") + "md5,gmt_modified,type,encrypted_data_key FROM config_info WHERE id + * > ? ORDER BY id ASC LIMIT startRow,pageSize" * * @param context The context of startRow, pageSize * @return The sql of querying all config info. @@ -141,8 +143,8 @@ default MapperResult configInfoLikeTenantCount(MapperContext context) { MapperResult findAllConfigInfoFragment(MapperContext context); /** - * Query change config.
    The default sql: SELECT data_id, group_id, tenant_id, app_name, content, - * gmt_modified,encrypted_data_key FROM config_info WHERE gmt_modified >=? AND gmt_modified <= ? + * Query change config.
    The default sql: SELECT id, data_id, group_id, tenant_id, app_name, md5, + * gmt_modified,encrypted_data_key FROM config_info WHERE gmt_modified >=? AND id > ? ORDER BY id LIMIT pageSize * * @param context sql paramMap * @return The sql of querying change config. @@ -207,7 +209,7 @@ default MapperResult findChangeConfigCountRows(MapperContext context) { /** * According to the time period and configuration conditions to query the eligible configuration. The default sql: - * SELECT id,data_id,group_id,tenant_id,app_name,content,type,md5,gmt_modified FROM config_info WHERE ... + * SELECT id,data_id,group_id,tenant_id,app_name,type,md5,gmt_modified FROM config_info WHERE ... * * @param context The map of params, the key is the parameter name(dataId, groupId, tenantId, appName, startTime, * endTime, content, startTime, endTime), the value is the key's value. @@ -365,7 +367,7 @@ default MapperResult findConfigInfo4PageCountRows(MapperContext context) { /** * Query configuration information based on group. The default sql: SELECT id,data_id,group_id,content FROM - * config_info WHERE group_id=? AND tenant_id=? + * config_info WHERE group_id=? AND tenant_id=? LIMIT startRow, pageSize * * @param context The context of startRow, pageSize * @return Query configuration information based on group. @@ -384,30 +386,27 @@ default MapperResult findConfigInfoLike4PageCountRows(MapperContext context) { final String content = (String) context.getWhereParameter(FieldConstant.CONTENT); final String appName = (String) context.getWhereParameter(FieldConstant.APP_NAME); final String tenantId = (String) context.getWhereParameter(FieldConstant.TENANT_ID); + final String[] types = (String[]) context.getWhereParameter(FieldConstant.TYPE); - final List paramList = new ArrayList<>(); + WhereBuilder where = new WhereBuilder("SELECT count(*) FROM config_info"); - final String sqlCountRows = "SELECT count(*) FROM config_info"; - StringBuilder where = new StringBuilder(" WHERE "); - where.append(" tenant_id LIKE ? "); - paramList.add(tenantId); - if (!StringUtils.isBlank(dataId)) { - where.append(" AND data_id LIKE ? "); - paramList.add(dataId); + where.like("tenant_id", tenantId); + if (StringUtils.isNotBlank(dataId)) { + where.and().like("data_id", dataId); } - if (!StringUtils.isBlank(group)) { - where.append(" AND group_id LIKE ? "); - paramList.add(group); + if (StringUtils.isNotBlank(group)) { + where.and().like("group_id", group); } - if (!StringUtils.isBlank(appName)) { - where.append(" AND app_name = ? "); - paramList.add(appName); + if (StringUtils.isNotBlank(appName)) { + where.and().eq("app_name", appName); } - if (!StringUtils.isBlank(content)) { - where.append(" AND content LIKE ? "); - paramList.add(content); + if (StringUtils.isNotBlank(content)) { + where.and().like("content", content); } - return new MapperResult(sqlCountRows + where, paramList); + if (!ArrayUtils.isEmpty(types)) { + where.and().in("type", types); + } + return where.build(); } /** @@ -492,7 +491,6 @@ default MapperResult updateConfigInfoAtomicCas(MapperContext context) { paramList.add(context.getUpdateParameter(FieldConstant.MD5)); paramList.add(context.getUpdateParameter(FieldConstant.SRC_IP)); paramList.add(context.getUpdateParameter(FieldConstant.SRC_USER)); - paramList.add(context.getUpdateParameter(FieldConstant.GMT_MODIFIED)); paramList.add(context.getUpdateParameter(FieldConstant.APP_NAME)); paramList.add(context.getUpdateParameter(FieldConstant.C_DESC)); paramList.add(context.getUpdateParameter(FieldConstant.C_USE)); @@ -504,8 +502,9 @@ default MapperResult updateConfigInfoAtomicCas(MapperContext context) { paramList.add(context.getWhereParameter(FieldConstant.GROUP_ID)); paramList.add(context.getWhereParameter(FieldConstant.TENANT_ID)); paramList.add(context.getWhereParameter(FieldConstant.MD5)); - String sql = "UPDATE config_info SET " + "content=?, md5 = ?, src_ip=?,src_user=?,gmt_modified=?," - + " app_name=?,c_desc=?,c_use=?,effect=?,type=?,c_schema=?,encrypted_data_key=? " + String sql = "UPDATE config_info SET " + "content=?, md5=?, src_ip=?, src_user=?, gmt_modified=" + + getFunction("NOW()") + + ", app_name=?, c_desc=?, c_use=?, effect=?, type=?, c_schema=?, encrypted_data_key=? " + "WHERE data_id=? AND group_id=? AND tenant_id=? AND (md5=? OR md5 IS NULL OR md5='')"; return new MapperResult(sql, paramList); } diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/ConfigTagsRelationMapper.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/ConfigTagsRelationMapper.java index 0440c5b8025..643ef0af9ee 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/ConfigTagsRelationMapper.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/ConfigTagsRelationMapper.java @@ -16,9 +16,11 @@ package com.alibaba.nacos.plugin.datasource.mapper; +import com.alibaba.nacos.common.utils.ArrayUtils; import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.plugin.datasource.constants.FieldConstant; import com.alibaba.nacos.plugin.datasource.constants.TableConstant; +import com.alibaba.nacos.plugin.datasource.mapper.ext.WhereBuilder; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; @@ -111,40 +113,31 @@ default MapperResult findConfigInfoLike4PageCountRows(final MapperContext contex final String group = (String) context.getWhereParameter(FieldConstant.GROUP_ID); final String content = (String) context.getWhereParameter(FieldConstant.CONTENT); final String[] tagArr = (String[]) context.getWhereParameter(FieldConstant.TAG_ARR); + final String[] types = (String[]) context.getWhereParameter(FieldConstant.TYPE); - List paramList = new ArrayList<>(); - StringBuilder where = new StringBuilder(" WHERE "); - final String sqlCount = "SELECT count(*) FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id "; + WhereBuilder where = new WhereBuilder("SELECT count(*) FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id"); - where.append(" a.tenant_id LIKE ? "); - paramList.add(tenantId); - if (!StringUtils.isBlank(dataId)) { - where.append(" AND a.data_id LIKE ? "); - paramList.add(dataId); + where.like("a.tenant_id", tenantId); + if (StringUtils.isNotBlank(dataId)) { + where.and().like("a.data_id", dataId); } if (StringUtils.isNotBlank(group)) { - where.append(" AND a.group_id LIKE ? "); - paramList.add(group); + where.and().like("a.group_id", group); } if (StringUtils.isNotBlank(appName)) { - where.append(" AND a.app_name = ? "); - paramList.add(appName); + where.and().eq("a.app_name", appName); } if (StringUtils.isNotBlank(content)) { - where.append(" AND a.content LIKE ? "); - paramList.add(content); + where.and().like("a.content", content); } - - where.append(" AND b.tag_name IN ("); - for (int i = 0; i < tagArr.length; i++) { - if (i != 0) { - where.append(", "); - } - where.append('?'); - paramList.add(tagArr[i]); + if (!ArrayUtils.isEmpty(tagArr)) { + where.and().in("b.tag_name", tagArr); } - where.append(") "); - return new MapperResult(sqlCount + where, paramList); + if (!ArrayUtils.isEmpty(types)) { + where.and().in("a.type", types); + } + + return where.build(); } /** diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/Mapper.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/Mapper.java index 20259194b1b..1cd5939c7c0 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/Mapper.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/Mapper.java @@ -75,7 +75,7 @@ public interface Mapper { * @return The name of datasource. */ String getDataSource(); - + /** * Get config_info table primary keys name. * The old default value: Statement.RETURN_GENERATED_KEYS @@ -83,4 +83,12 @@ public interface Mapper { * @return an array of column names indicating the columns */ String[] getPrimaryKeyGeneratedKeys(); + + /** + * Get function by functionName. + * + * @param functionName functionName + * @return function + */ + String getFunction(String functionName); } \ No newline at end of file diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/ext/WhereBuilder.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/ext/WhereBuilder.java new file mode 100644 index 00000000000..f0b4b7f3673 --- /dev/null +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/mapper/ext/WhereBuilder.java @@ -0,0 +1,162 @@ +/* + * Copyright 1999-2018 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.plugin.datasource.mapper.ext; + +import com.alibaba.nacos.common.constant.Symbols; +import com.alibaba.nacos.plugin.datasource.model.MapperResult; + +import java.util.ArrayList; +import java.util.List; + +/** + * Where Builder. + * + * @author haiqi.wang + * @date 2024/08/13 + */ +public final class WhereBuilder { + + /** + * Base sql. + */ + private final String sql; + + /** + * Parameters. + */ + private final List parameters = new ArrayList<>(); + + /** + * Where Conditional. + */ + private final StringBuilder where = new StringBuilder(" WHERE "); + + /** + * Default Construct. + * + * @param sql Sql Script + */ + public WhereBuilder(String sql) { + this.sql = sql; + } + + /** + * Build AND. + * + * @return Return {@link WhereBuilder} + */ + public WhereBuilder and() { + where.append(" AND "); + return this; + } + + /** + * Build OR. + * + * @return Return {@link WhereBuilder} + */ + public WhereBuilder or() { + where.append(" OR "); + return this; + } + + /** + * Build Equals. + * + * @param filed Filed name + * @param parameter Parameters + * @return Return {@link WhereBuilder} + */ + public WhereBuilder eq(String filed, Object parameter) { + where.append(filed).append(" = ? "); + parameters.add(parameter); + return this; + } + + /** + * Build LIKE. + * + * @param filed Filed name + * @param parameter Parameters + * @return Return {@link WhereBuilder} + */ + public WhereBuilder like(String filed, Object parameter) { + where.append(filed).append(" LIKE ? "); + parameters.add(parameter); + return this; + } + + /** + * Build IN. + * + * @param filed Filed name + * @param parameterArr Parameters Array + * @return Return {@link WhereBuilder} + */ + public WhereBuilder in(String filed, Object[] parameterArr) { + where.append(filed).append(" IN ("); + for (int i = 0; i < parameterArr.length; i++) { + if (i != 0) { + where.append(", "); + } + where.append('?'); + parameters.add(parameterArr[i]); + } + where.append(") "); + return this; + } + + /** + * Build offset. + * + * @param startRow Start row + * @param pageSize Page size + * @return Return {@link WhereBuilder} + */ + public WhereBuilder offset(int startRow, int pageSize) { + where.append(" OFFSET ") + .append(startRow) + .append(" ROWS FETCH NEXT ") + .append(pageSize) + .append(" ROWS ONLY"); + return this; + } + + /** + * Build limit. + * + * @param startRow Start row + * @param pageSize Page size + * @return Return {@link WhereBuilder} + */ + public WhereBuilder limit(int startRow, int pageSize) { + where.append(" LIMIT ") + .append(startRow) + .append(Symbols.COMMA) + .append(pageSize); + return this; + } + + /** + * Build. + * + * @return Return {@link WhereBuilder} + */ + public MapperResult build() { + return new MapperResult(sql + where, parameters); + } +} \ No newline at end of file diff --git a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/proxy/MapperProxy.java b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/proxy/MapperProxy.java index 2a5a4fbede2..b8d2a77adaf 100644 --- a/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/proxy/MapperProxy.java +++ b/plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/proxy/MapperProxy.java @@ -25,8 +25,12 @@ import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; +import java.util.Arrays; +import java.util.HashSet; import java.util.Map; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; /** * DataSource plugin Mapper sql proxy. @@ -40,10 +44,21 @@ public class MapperProxy implements InvocationHandler { private Mapper mapper; private static final Map SINGLE_MAPPER_PROXY_MAP = new ConcurrentHashMap<>(16); - + + /** + * Creates a proxy instance for the sub-interfaces of Mapper.class implemented by the given object. + */ public R createProxy(Mapper mapper) { this.mapper = mapper; - return (R) Proxy.newProxyInstance(MapperProxy.class.getClassLoader(), mapper.getClass().getInterfaces(), this); + Class clazz = mapper.getClass(); + Set> interfacesSet = new HashSet<>(); + while (!clazz.equals(Object.class)) { + interfacesSet.addAll(Arrays.stream(clazz.getInterfaces()) + .filter(Mapper.class::isAssignableFrom) + .collect(Collectors.toSet())); + clazz = clazz.getSuperclass(); + } + return (R) Proxy.newProxyInstance(MapperProxy.class.getClassLoader(), interfacesSet.toArray(new Class[interfacesSet.size()]), this); } /** diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/MapperManagerTest.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/MapperManagerTest.java index 8bca4765686..eff15277ce5 100644 --- a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/MapperManagerTest.java +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/MapperManagerTest.java @@ -17,41 +17,45 @@ package com.alibaba.nacos.plugin.datasource; import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; -import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper; +import com.alibaba.nacos.plugin.datasource.impl.mysql.AbstractMapperByMysql; +import com.alibaba.nacos.plugin.datasource.mapper.ConfigInfoAggrMapper; import com.alibaba.nacos.plugin.datasource.mapper.Mapper; -import org.junit.Assert; -import org.junit.Test; +import com.alibaba.nacos.plugin.datasource.mapper.TestMapper; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.util.Map; -public class MapperManagerTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class MapperManagerTest { @Test - public void testInstance() { + void testInstance() { MapperManager instance = MapperManager.instance(false); - Assert.assertNotNull(instance); + assertNotNull(instance); } @Test - public void testLoadInitial() throws NoSuchFieldException, IllegalAccessException { + void testLoadInitial() throws NoSuchFieldException, IllegalAccessException { MapperManager instance = MapperManager.instance(false); instance.loadInitial(); Class mapperManagerClass = MapperManager.class; Field declaredField = mapperManagerClass.getDeclaredField("MAPPER_SPI_MAP"); declaredField.setAccessible(true); Map> map = (Map>) declaredField.get(instance); - Assert.assertEquals(2, map.size()); + assertEquals(2, map.size()); } @Test - public void testJoin() { - MapperManager.join(new AbstractMapper() { + void testJoin() { + MapperManager.join(new AbstractMapperByMysql() { @Override public String getTableName() { return "test"; } - + @Override public String getDataSource() { return DataSourceConstant.MYSQL; @@ -59,14 +63,23 @@ public String getDataSource() { }); MapperManager instance = MapperManager.instance(false); Mapper mapper = instance.findMapper(DataSourceConstant.MYSQL, "test"); - Assert.assertNotNull(mapper); + assertNotNull(mapper); } @Test - public void testFindMapper() { + void testFindMapper() { testJoin(); MapperManager instance = MapperManager.instance(false); Mapper mapper = instance.findMapper(DataSourceConstant.MYSQL, "test"); - Assert.assertNotNull(mapper); + assertNotNull(mapper); + } + + @Test + void testEnableDataSourceLogJoin() { + MapperManager.join(new TestMapper()); + MapperManager instance = MapperManager.instance(true); + ConfigInfoAggrMapper mapper = instance.findMapper(DataSourceConstant.MYSQL, "enable_data_source_log_test"); + assertNotNull(mapper); } -} \ No newline at end of file + +} diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/enums/derby/TrustedDerbyFunctionEnumTest.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/enums/derby/TrustedDerbyFunctionEnumTest.java new file mode 100644 index 00000000000..5649c0a11d1 --- /dev/null +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/enums/derby/TrustedDerbyFunctionEnumTest.java @@ -0,0 +1,38 @@ +/* + * Copyright 1999-2018 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.plugin.datasource.enums.derby; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +/** + * TrustedDerbyFunctionEnumTest. + * + * @author blake.qiu + */ +public class TrustedDerbyFunctionEnumTest { + + @Test + void testGetFunctionByName() { + Assertions.assertEquals("CURRENT_TIMESTAMP", TrustedDerbylFunctionEnum.getFunctionByName("NOW()")); + } + + @Test() + void testGetFunctionByErrorName() { + Assertions.assertThrows(IllegalArgumentException.class, () -> TrustedDerbylFunctionEnum.getFunctionByName("UNKNOWN")); + } +} \ No newline at end of file diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/enums/mysql/TrustedMysqlFunctionEnumTest.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/enums/mysql/TrustedMysqlFunctionEnumTest.java new file mode 100644 index 00000000000..7cb9dbceaa2 --- /dev/null +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/enums/mysql/TrustedMysqlFunctionEnumTest.java @@ -0,0 +1,38 @@ +/* + * Copyright 1999-2018 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.plugin.datasource.enums.mysql; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +/** + * TrustedMysqlFunctionEnumTest. + * + * @author blake.qiu + */ +public class TrustedMysqlFunctionEnumTest { + + @Test + void testGetFunctionByName() { + Assertions.assertEquals("NOW(3)", TrustedMysqlFunctionEnum.getFunctionByName("NOW()")); + } + + @Test() + void testGetFunctionByErrorName() { + Assertions.assertThrows(IllegalArgumentException.class, () -> TrustedMysqlFunctionEnum.getFunctionByName("UNKNOWN")); + } +} \ No newline at end of file diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/TestInterface.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/TestInterface.java new file mode 100644 index 00000000000..1ad19e46110 --- /dev/null +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/TestInterface.java @@ -0,0 +1,26 @@ +/* + * Copyright 1999-2022 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.plugin.datasource.impl; + +/** + * A custom interface. just for test + * + * @author mikolls + **/ +public interface TestInterface { + +} diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoAggrMapperByDerbyTest.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoAggrMapperByDerbyTest.java index 6e66fed33fc..e0abf043c1e 100644 --- a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoAggrMapperByDerbyTest.java +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoAggrMapperByDerbyTest.java @@ -22,24 +22,25 @@ import com.alibaba.nacos.plugin.datasource.constants.TableConstant; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; -public class ConfigInfoAggrMapperByDerbyTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ConfigInfoAggrMapperByDerbyTest { private ConfigInfoAggrMapperByDerby configInfoAggrMapperByDerby; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { this.configInfoAggrMapperByDerby = new ConfigInfoAggrMapperByDerby(); } @Test - public void testBatchRemoveAggr() { + void testBatchRemoveAggr() { List datumList = Arrays.asList("1", "2", "3", "4", "5"); String dataId = "data-id"; String groupId = "group-id"; @@ -57,13 +58,13 @@ public void testBatchRemoveAggr() { String sql = result.getSql(); List paramList = result.getParamList(); - Assert.assertEquals(sql, "DELETE FROM config_info_aggr WHERE data_id = ? AND group_id = ? AND tenant_id = ? " - + "AND datum_id IN (?, ?, ?, ?, ?)"); - Assert.assertEquals(paramList, argList); + assertEquals(sql, + "DELETE FROM config_info_aggr WHERE data_id = ? AND group_id = ? AND tenant_id = ? " + "AND datum_id IN (?, ?, ?, ?, ?)"); + assertEquals(paramList, argList); } @Test - public void testAggrConfigInfoCount() { + void testAggrConfigInfoCount() { List datumIds = Arrays.asList("1", "2", "3", "4", "5"); String dataId = "data-id"; String groupId = "group-id"; @@ -82,14 +83,13 @@ public void testAggrConfigInfoCount() { String sql = mapperResult.getSql(); List paramList = mapperResult.getParamList(); - Assert.assertEquals(sql, - "SELECT count(*) FROM config_info_aggr WHERE data_id = ? AND group_id = ? AND tenant_id = ? " - + "AND datum_id IN (?, ?, ?, ?, ?)"); - Assert.assertEquals(paramList, argList); + assertEquals(sql, "SELECT count(*) FROM config_info_aggr WHERE data_id = ? AND group_id = ? AND tenant_id = ? " + + "AND datum_id IN (?, ?, ?, ?, ?)"); + assertEquals(paramList, argList); } @Test - public void testFindConfigInfoAggrIsOrdered() { + void testFindConfigInfoAggrIsOrdered() { String dataId = "data-id"; String groupId = "group-id"; String tenantId = "tenant-id"; @@ -103,13 +103,13 @@ public void testFindConfigInfoAggrIsOrdered() { String sql = mapperResult.getSql(); List paramList = mapperResult.getParamList(); - Assert.assertEquals(sql, "SELECT data_id,group_id,tenant_id,datum_id,app_name,content FROM " + assertEquals(sql, "SELECT data_id,group_id,tenant_id,datum_id,app_name,content FROM " + "config_info_aggr WHERE data_id = ? AND group_id = ? AND tenant_id = ? ORDER BY datum_id"); - Assert.assertEquals(paramList, CollectionUtils.list(dataId, groupId, tenantId)); + assertEquals(paramList, CollectionUtils.list(dataId, groupId, tenantId)); } @Test - public void testFindConfigInfoAggrByPageFetchRows() { + void testFindConfigInfoAggrByPageFetchRows() { String dataId = "data-id"; String groupId = "group-id"; String tenantId = "tenant-id"; @@ -126,27 +126,26 @@ public void testFindConfigInfoAggrByPageFetchRows() { MapperResult mapperResult = configInfoAggrMapperByDerby.findConfigInfoAggrByPageFetchRows(context); String sql = mapperResult.getSql(); List paramList = mapperResult.getParamList(); - Assert.assertEquals(sql, - "SELECT data_id,group_id,tenant_id,datum_id,app_name,content FROM config_info_aggr WHERE " - + "data_id=? AND group_id=? AND tenant_id=? ORDER BY datum_id OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY"); - Assert.assertEquals(paramList, CollectionUtils.list(dataId, groupId, tenantId)); + assertEquals(sql, "SELECT data_id,group_id,tenant_id,datum_id,app_name,content FROM config_info_aggr WHERE " + + "data_id=? AND group_id=? AND tenant_id=? ORDER BY datum_id OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY"); + assertEquals(paramList, CollectionUtils.list(dataId, groupId, tenantId)); } @Test - public void testFindAllAggrGroupByDistinct() { + void testFindAllAggrGroupByDistinct() { MapperResult sql = configInfoAggrMapperByDerby.findAllAggrGroupByDistinct(null); - Assert.assertEquals(sql.getSql(), "SELECT DISTINCT data_id, group_id, tenant_id FROM config_info_aggr"); + assertEquals("SELECT DISTINCT data_id, group_id, tenant_id FROM config_info_aggr", sql.getSql()); } @Test - public void testGetTableName() { + void testGetTableName() { String tableName = configInfoAggrMapperByDerby.getTableName(); - Assert.assertEquals(tableName, TableConstant.CONFIG_INFO_AGGR); + assertEquals(TableConstant.CONFIG_INFO_AGGR, tableName); } @Test - public void testGetDataSource() { + void testGetDataSource() { String dataSource = configInfoAggrMapperByDerby.getDataSource(); - Assert.assertEquals(dataSource, DataSourceConstant.DERBY); + assertEquals(DataSourceConstant.DERBY, dataSource); } } diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoBetaMapperByDerbyTest.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoBetaMapperByDerbyTest.java index 2ed3be3c601..e3db96e628f 100644 --- a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoBetaMapperByDerbyTest.java +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoBetaMapperByDerbyTest.java @@ -22,17 +22,17 @@ import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.sql.Timestamp; import java.util.Arrays; import java.util.List; -public class ConfigInfoBetaMapperByDerbyTest { - - private ConfigInfoBetaMapperByDerby configInfoBetaMapperByDerby; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ConfigInfoBetaMapperByDerbyTest { int startRow = 0; @@ -52,8 +52,10 @@ public class ConfigInfoBetaMapperByDerbyTest { MapperContext context; - @Before - public void setUp() throws Exception { + private ConfigInfoBetaMapperByDerby configInfoBetaMapperByDerby; + + @BeforeEach + void setUp() throws Exception { configInfoBetaMapperByDerby = new ConfigInfoBetaMapperByDerby(); context = new MapperContext(startRow, pageSize); @@ -67,12 +69,11 @@ public void setUp() throws Exception { } @Test - public void testUpdateConfigInfo4BetaCas() { + void testUpdateConfigInfo4BetaCas() { String newContent = "new Content"; String newMD5 = "newMD5"; String srcIp = "1.1.1.1"; Object srcUser = "nacos"; - Object time = new Timestamp(System.currentTimeMillis()); Object appNameTmp = "newAppName"; Object desc = "description"; Object use = "use"; @@ -86,7 +87,6 @@ public void testUpdateConfigInfo4BetaCas() { context.putUpdateParameter(FieldConstant.BETA_IPS, betaIps); context.putUpdateParameter(FieldConstant.SRC_IP, srcIp); context.putUpdateParameter(FieldConstant.SRC_USER, srcUser); - context.putUpdateParameter(FieldConstant.GMT_MODIFIED, time); context.putUpdateParameter(FieldConstant.APP_NAME, appNameTmp); context.putUpdateParameter(FieldConstant.C_DESC, desc); context.putUpdateParameter(FieldConstant.C_USE, use); @@ -106,35 +106,33 @@ public void testUpdateConfigInfo4BetaCas() { MapperResult mapperResult = configInfoBetaMapperByDerby.updateConfigInfo4BetaCas(context); String sql = mapperResult.getSql(); - Assert.assertEquals(sql, "UPDATE config_info_beta SET content = ?,md5 = ?,beta_ips = ?,src_ip = ?,src_user = ?," - + "gmt_modified = ?,app_name = ? WHERE data_id = ? AND group_id = ? AND tenant_id = ? AND " + assertEquals(sql, "UPDATE config_info_beta SET content = ?,md5 = ?,beta_ips = ?,src_ip = ?,src_user = ?," + + "gmt_modified = CURRENT_TIMESTAMP,app_name = ? WHERE data_id = ? AND group_id = ? AND tenant_id = ? AND " + "(md5 = ? OR md5 is null OR md5 = '')"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), - new Object[] {newContent, newMD5, betaIps, srcIp, srcUser, time, appNameTmp, dataId, group, tenantId, - md5}); + assertArrayEquals(new Object[]{newContent, newMD5, betaIps, srcIp, srcUser, appNameTmp, dataId, group, tenantId, md5}, + mapperResult.getParamList().toArray()); } @Test - public void testFindAllConfigInfoBetaForDumpAllFetchRows() { + void testFindAllConfigInfoBetaForDumpAllFetchRows() { MapperResult result = configInfoBetaMapperByDerby.findAllConfigInfoBetaForDumpAllFetchRows(context); String sql = result.getSql(); List paramList = result.getParamList(); - Assert.assertEquals(sql, - "SELECT t.id,data_id,group_id,tenant_id,app_name,content,md5,gmt_modified,beta_ips FROM " - + "( SELECT id FROM config_info_beta ORDER BY id OFFSET " + startRow + " ROWS FETCH NEXT " - + pageSize + " ROWS ONLY ) g, " + "config_info_beta t WHERE g.id = t.id"); - Assert.assertEquals(paramList, Arrays.asList(startRow, pageSize)); + assertEquals(sql, "SELECT t.id,data_id,group_id,tenant_id,app_name,content,md5,gmt_modified,beta_ips FROM " + + "( SELECT id FROM config_info_beta ORDER BY id OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY ) g, " + + "config_info_beta t WHERE g.id = t.id"); + assertEquals(paramList, Arrays.asList(startRow, pageSize)); } @Test - public void testGetTableName() { + void testGetTableName() { String tableName = configInfoBetaMapperByDerby.getTableName(); - Assert.assertEquals(tableName, TableConstant.CONFIG_INFO_BETA); + assertEquals(TableConstant.CONFIG_INFO_BETA, tableName); } @Test - public void testGetDataSource() { + void testGetDataSource() { String dataSource = configInfoBetaMapperByDerby.getDataSource(); - Assert.assertEquals(dataSource, DataSourceConstant.DERBY); + assertEquals(DataSourceConstant.DERBY, dataSource); } } diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoMapperByDerbyTest.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoMapperByDerbyTest.java index 29c382781f6..4856c1dfc5e 100644 --- a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoMapperByDerbyTest.java +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoMapperByDerbyTest.java @@ -23,16 +23,16 @@ import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.sql.Timestamp; import java.util.List; -public class ConfigInfoMapperByDerbyTest { - - private ConfigInfoMapperByDerby configInfoMapperByDerby; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ConfigInfoMapperByDerbyTest { private final Object[] emptyObjs = new Object[] {}; @@ -58,8 +58,10 @@ public class ConfigInfoMapperByDerbyTest { MapperContext context; - @Before - public void setUp() throws Exception { + private ConfigInfoMapperByDerby configInfoMapperByDerby; + + @BeforeEach + void setUp() throws Exception { configInfoMapperByDerby = new ConfigInfoMapperByDerby(); context = new MapperContext(startRow, pageSize); @@ -74,261 +76,247 @@ public void setUp() throws Exception { } @Test - public void testFindConfigMaxId() { + void testFindConfigMaxId() { MapperResult mapperResult = configInfoMapperByDerby.findConfigMaxId(null); - Assert.assertEquals(mapperResult.getSql(), "SELECT MAX(id) FROM config_info"); + assertEquals("SELECT MAX(id) FROM config_info", mapperResult.getSql()); } @Test - public void testFindAllDataIdAndGroup() { + void testFindAllDataIdAndGroup() { MapperResult mapperResult = configInfoMapperByDerby.findAllDataIdAndGroup(null); - Assert.assertEquals(mapperResult.getSql(), "SELECT DISTINCT data_id, group_id FROM config_info"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); + assertEquals("SELECT DISTINCT data_id, group_id FROM config_info", mapperResult.getSql()); + assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); } @Test - public void testFindConfigInfoByAppCountRows() { + void testFindConfigInfoByAppCountRows() { MapperResult mapperResult = configInfoMapperByDerby.findConfigInfoByAppCountRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT count(*) FROM config_info WHERE tenant_id LIKE ? AND app_name = ?"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName}); + assertEquals("SELECT count(*) FROM config_info WHERE tenant_id LIKE ? AND app_name = ?", mapperResult.getSql()); + assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray()); } @Test - public void testFindConfigInfoByAppFetchRows() { + void testFindConfigInfoByAppFetchRows() { MapperResult mapperResult = configInfoMapperByDerby.findConfigInfoByAppFetchRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT ID,data_id,group_id,tenant_id,app_name,content FROM config_info WHERE tenant_id LIKE" - + " ? AND app_name = ? OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName}); + assertEquals(mapperResult.getSql(), "SELECT ID,data_id,group_id,tenant_id,app_name,content FROM config_info WHERE tenant_id LIKE" + + " ? AND app_name = ? OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY"); + assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray()); } @Test - public void testConfigInfoLikeTenantCount() { + void testConfigInfoLikeTenantCount() { MapperResult mapperResult = configInfoMapperByDerby.configInfoLikeTenantCount(context); - Assert.assertEquals(mapperResult.getSql(), "SELECT count(*) FROM config_info WHERE tenant_id LIKE ?"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId}); + assertEquals("SELECT count(*) FROM config_info WHERE tenant_id LIKE ?", mapperResult.getSql()); + assertArrayEquals(new Object[] {tenantId}, mapperResult.getParamList().toArray()); } @Test - public void testGetTenantIdList() { + void testGetTenantIdList() { MapperResult mapperResult = configInfoMapperByDerby.getTenantIdList(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT tenant_id FROM config_info WHERE tenant_id != '' GROUP BY tenant_id OFFSET " + startRow - + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); + assertEquals(mapperResult.getSql(), + "SELECT tenant_id FROM config_info WHERE tenant_id != '' GROUP BY tenant_id OFFSET " + startRow + " ROWS FETCH NEXT " + + pageSize + " ROWS ONLY"); + assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); } @Test - public void testGetGroupIdList() { + void testGetGroupIdList() { MapperResult mapperResult = configInfoMapperByDerby.getGroupIdList(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT group_id FROM config_info WHERE tenant_id ='' GROUP BY group_id OFFSET " + startRow - + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); + assertEquals(mapperResult.getSql(), + "SELECT group_id FROM config_info WHERE tenant_id ='' GROUP BY group_id OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + + " ROWS ONLY"); + assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); } @Test - public void testFindAllConfigKey() { + void testFindAllConfigKey() { MapperResult mapperResult = configInfoMapperByDerby.findAllConfigKey(context); - Assert.assertEquals(mapperResult.getSql(), - " SELECT data_id,group_id,app_name FROM ( SELECT id FROM config_info WHERE tenant_id LIKE" - + " ? ORDER BY id OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize - + " ROWS ONLY ) g, config_info t WHERE g.id = t.id "); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId}); + assertEquals(mapperResult.getSql(), + " SELECT data_id,group_id,app_name FROM ( SELECT id FROM config_info WHERE tenant_id LIKE" + " ? ORDER BY id OFFSET " + + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY ) g, config_info t WHERE g.id = t.id "); + assertArrayEquals(new Object[] {tenantId}, mapperResult.getParamList().toArray()); } @Test - public void testFindAllConfigInfoBaseFetchRows() { + void testFindAllConfigInfoBaseFetchRows() { MapperResult mapperResult = configInfoMapperByDerby.findAllConfigInfoBaseFetchRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT t.id,data_id,group_id,content,md5 FROM ( SELECT id FROM config_info ORDER BY " + "id OFFSET " - + startRow + " ROWS FETCH NEXT " + pageSize - + " ROWS ONLY ) g, config_info t WHERE g.id = t.id "); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); + assertEquals(mapperResult.getSql(), + "SELECT t.id,data_id,group_id,content,md5 FROM ( SELECT id FROM config_info ORDER BY " + "id OFFSET " + startRow + + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY ) g, config_info t WHERE g.id = t.id "); + assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); } @Test - public void testFindAllConfigInfoFragment() { + void testFindAllConfigInfoFragment() { //with content context.putContextParameter(ContextConstant.NEED_CONTENT, "true"); MapperResult mapperResult = configInfoMapperByDerby.findAllConfigInfoFragment(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT id,data_id,group_id,tenant_id,app_name,content,md5,gmt_modified,type FROM config_info " - + "WHERE id > ? ORDER BY id ASC OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize - + " ROWS ONLY"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {id}); + assertEquals(mapperResult.getSql(), "SELECT id,data_id,group_id,tenant_id,app_name,content,md5,gmt_modified,type FROM config_info " + + "WHERE id > ? ORDER BY id ASC OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY"); + assertArrayEquals(new Object[] {id}, mapperResult.getParamList().toArray()); //with out content context.putContextParameter(ContextConstant.NEED_CONTENT, "false"); - + MapperResult mapperResult2 = configInfoMapperByDerby.findAllConfigInfoFragment(context); - Assert.assertEquals(mapperResult2.getSql(), - "SELECT id,data_id,group_id,tenant_id,app_name,md5,gmt_modified,type FROM config_info " - + "WHERE id > ? ORDER BY id ASC OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize - + " ROWS ONLY"); - Assert.assertArrayEquals(mapperResult2.getParamList().toArray(), new Object[] {id}); + assertEquals(mapperResult2.getSql(), "SELECT id,data_id,group_id,tenant_id,app_name,md5,gmt_modified,type FROM config_info " + + "WHERE id > ? ORDER BY id ASC OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY"); + assertArrayEquals(new Object[] {id}, mapperResult2.getParamList().toArray()); } @Test - public void testFindChangeConfig() { + void testFindChangeConfig() { MapperResult mapperResult = configInfoMapperByDerby.findChangeConfig(context); - Assert.assertEquals(mapperResult.getSql(), + assertEquals(mapperResult.getSql(), "SELECT id, data_id, group_id, tenant_id, app_name, content, gmt_modified, encrypted_data_key FROM config_info " + "WHERE gmt_modified >= ? and id > ? order by id OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {startTime, lastMaxId, pageSize}); + assertArrayEquals(new Object[] {startTime, lastMaxId, pageSize}, mapperResult.getParamList().toArray()); } @Test - public void testFindChangeConfigCountRows() { + void testFindChangeConfigCountRows() { MapperResult mapperResult = configInfoMapperByDerby.findChangeConfigCountRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT count(*) FROM config_info WHERE 1=1 AND app_name = ? AND gmt_modified >=? AND gmt_modified <=? "); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {appName, startTime, endTime}); + assertEquals("SELECT count(*) FROM config_info WHERE 1=1 AND app_name = ? AND gmt_modified >=? AND gmt_modified <=? ", + mapperResult.getSql()); + assertArrayEquals(new Object[] {appName, startTime, endTime}, mapperResult.getParamList().toArray()); } @Test - public void testFindChangeConfigFetchRows() { + void testFindChangeConfigFetchRows() { MapperResult mapperResult = configInfoMapperByDerby.findChangeConfigFetchRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT id,data_id,group_id,tenant_id,app_name,content,type,md5,gmt_modified FROM config_info " - + "WHERE 1=1 AND app_name = ? AND gmt_modified >=? AND gmt_modified <=? OFFSET " + startRow - + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {appName, startTime, endTime}); + assertEquals(mapperResult.getSql(), "SELECT id,data_id,group_id,tenant_id,app_name,content,type,md5,gmt_modified FROM config_info " + + "WHERE 1=1 AND app_name = ? AND gmt_modified >=? AND gmt_modified <=? OFFSET " + startRow + " ROWS FETCH NEXT " + + pageSize + " ROWS ONLY"); + assertArrayEquals(new Object[] {appName, startTime, endTime}, mapperResult.getParamList().toArray()); } @Test - public void testListGroupKeyMd5ByPageFetchRows() { + void testListGroupKeyMd5ByPageFetchRows() { MapperResult mapperResult = configInfoMapperByDerby.listGroupKeyMd5ByPageFetchRows(context); - Assert.assertEquals(mapperResult.getSql(), + assertEquals(mapperResult.getSql(), " SELECT t.id,data_id,group_id,tenant_id,app_name,type,md5,gmt_modified FROM ( SELECT id FROM config_info " + "ORDER BY id OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY ) g, config_info t WHERE g.id = t.id"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); + assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); } @Test - public void testFindAllConfigInfo4Export() { + void testFindAllConfigInfo4Export() { MapperResult mapperResult = configInfoMapperByDerby.findAllConfigInfo4Export(context); - Assert.assertEquals(mapperResult.getSql(), + assertEquals(mapperResult.getSql(), "SELECT id,data_id,group_id,tenant_id,app_name,content,type,md5,gmt_create,gmt_modified,src_user," + "src_ip,c_desc,c_use,effect,c_schema,encrypted_data_key FROM config_info WHERE id IN (?, ?, ?, ?, ?) "); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), ids.toArray()); + assertArrayEquals(mapperResult.getParamList().toArray(), ids.toArray()); context.putWhereParameter(FieldConstant.IDS, null); mapperResult = configInfoMapperByDerby.findAllConfigInfo4Export(context); - Assert.assertEquals(mapperResult.getSql(), + assertEquals(mapperResult.getSql(), "SELECT id,data_id,group_id,tenant_id,app_name,content,type,md5,gmt_create,gmt_modified,src_user," + "src_ip,c_desc,c_use,effect,c_schema,encrypted_data_key FROM config_info WHERE tenant_id = ? AND app_name= ? "); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName}); + assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray()); } @Test - public void testFindConfigInfoBaseLikeCountRows() { + void testFindConfigInfoBaseLikeCountRows() { MapperResult mapperResult = configInfoMapperByDerby.findConfigInfoBaseLikeCountRows(context); - Assert.assertEquals(mapperResult.getSql(), "SELECT count(*) FROM config_info WHERE 1=1 AND tenant_id='' "); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); + assertEquals("SELECT count(*) FROM config_info WHERE 1=1 AND tenant_id='' ", mapperResult.getSql()); + assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); } @Test - public void testFindConfigInfoBaseLikeFetchRows() { + void testFindConfigInfoBaseLikeFetchRows() { MapperResult mapperResult = configInfoMapperByDerby.findConfigInfoBaseLikeFetchRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT id,data_id,group_id,tenant_id,content FROM config_info WHERE 1=1 AND tenant_id='' " - + "OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); + assertEquals(mapperResult.getSql(), + "SELECT id,data_id,group_id,tenant_id,content FROM config_info WHERE 1=1 AND tenant_id='' " + "OFFSET " + startRow + + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY"); + assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); } @Test - public void testFindConfigInfo4PageCountRows() { + void testFindConfigInfo4PageCountRows() { MapperResult mapperResult = configInfoMapperByDerby.findConfigInfo4PageCountRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT count(*) FROM config_info WHERE tenant_id=? AND app_name=? "); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName}); + assertEquals("SELECT count(*) FROM config_info WHERE tenant_id=? AND app_name=? ", mapperResult.getSql()); + assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray()); } @Test - public void testFindConfigInfo4PageFetchRows() { + void testFindConfigInfo4PageFetchRows() { MapperResult mapperResult = configInfoMapperByDerby.findConfigInfo4PageFetchRows(context); - Assert.assertEquals(mapperResult.getSql(), + assertEquals(mapperResult.getSql(), "SELECT id,data_id,group_id,tenant_id,app_name,content,type FROM config_info WHERE tenant_id=? AND app_name=? " + " OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName}); + assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray()); } @Test - public void testFindConfigInfoBaseByGroupFetchRows() { + void testFindConfigInfoBaseByGroupFetchRows() { context.putWhereParameter(FieldConstant.GROUP_ID, groupId); MapperResult mapperResult = configInfoMapperByDerby.findConfigInfoBaseByGroupFetchRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT id,data_id,group_id,content FROM config_info WHERE group_id=? AND tenant_id=? " + "OFFSET " - + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {groupId, tenantId}); + assertEquals(mapperResult.getSql(), + "SELECT id,data_id,group_id,content FROM config_info WHERE group_id=? AND tenant_id=? " + "OFFSET " + startRow + + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY"); + assertArrayEquals(new Object[] {groupId, tenantId}, mapperResult.getParamList().toArray()); } @Test - public void testFindConfigInfoLike4PageCountRows() { + void testFindConfigInfoLike4PageCountRows() { MapperResult mapperResult = configInfoMapperByDerby.findConfigInfoLike4PageCountRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT count(*) FROM config_info WHERE tenant_id LIKE ? AND app_name = ? "); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName}); + assertEquals("SELECT count(*) FROM config_info WHERE tenant_id LIKE ? AND app_name = ? ", mapperResult.getSql()); + assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray()); } @Test - public void testFindConfigInfoLike4PageFetchRows() { + void testFindConfigInfoLike4PageFetchRows() { MapperResult mapperResult = configInfoMapperByDerby.findConfigInfoLike4PageFetchRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT id,data_id,group_id,tenant_id,app_name,content,encrypted_data_key FROM config_info " - + "WHERE tenant_id LIKE ? AND app_name = ? OFFSET " + startRow + " ROWS FETCH NEXT " - + pageSize + " ROWS ONLY"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName}); + assertEquals(mapperResult.getSql(), "SELECT id,data_id,group_id,tenant_id,app_name,content,encrypted_data_key,type FROM config_info " + + "WHERE tenant_id LIKE ? AND app_name = ? OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY"); + assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray()); } @Test - public void testFindAllConfigInfoFetchRows() { + void testFindAllConfigInfoFetchRows() { MapperResult mapperResult = configInfoMapperByDerby.findAllConfigInfoFetchRows(context); - Assert.assertEquals(mapperResult.getSql(), + assertEquals(mapperResult.getSql(), " SELECT t.id,data_id,group_id,tenant_id,app_name,content,md5 FROM ( SELECT id FROM config_info " + "WHERE tenant_id LIKE ? ORDER BY id OFFSET ? ROWS FETCH NEXT ? ROWS ONLY ) g, config_info t WHERE g.id = t.id "); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, startRow, pageSize}); + assertArrayEquals(new Object[] {tenantId, startRow, pageSize}, mapperResult.getParamList().toArray()); } @Test - public void testFindConfigInfosByIds() { + void testFindConfigInfosByIds() { MapperResult mapperResult = configInfoMapperByDerby.findConfigInfosByIds(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT id,data_id,group_id,tenant_id,app_name,content,md5 FROM config_info WHERE id IN (?, ?, ?, ?, ?) "); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), ids.toArray()); + assertEquals("SELECT id,data_id,group_id,tenant_id,app_name,content,md5 FROM config_info WHERE id IN (?, ?, ?, ?, ?) ", + mapperResult.getSql()); + assertArrayEquals(mapperResult.getParamList().toArray(), ids.toArray()); } @Test - public void testRemoveConfigInfoByIdsAtomic() { + void testRemoveConfigInfoByIdsAtomic() { MapperResult mapperResult = configInfoMapperByDerby.removeConfigInfoByIdsAtomic(context); - Assert.assertEquals(mapperResult.getSql(), "DELETE FROM config_info WHERE id IN (?, ?, ?, ?, ?) "); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), ids.toArray()); + assertEquals("DELETE FROM config_info WHERE id IN (?, ?, ?, ?, ?) ", mapperResult.getSql()); + assertArrayEquals(mapperResult.getParamList().toArray(), ids.toArray()); } @Test - public void testGetTableName() { + void testGetTableName() { String sql = configInfoMapperByDerby.getTableName(); - Assert.assertEquals(sql, TableConstant.CONFIG_INFO); + assertEquals(TableConstant.CONFIG_INFO, sql); } @Test - public void testGetDataSource() { + void testGetDataSource() { String sql = configInfoMapperByDerby.getDataSource(); - Assert.assertEquals(sql, DataSourceConstant.DERBY); + assertEquals(DataSourceConstant.DERBY, sql); } @Test - public void testUpdateConfigInfoAtomicCas() { + void testUpdateConfigInfoAtomicCas() { String newContent = "new Content"; String newMD5 = "newMD5"; String srcIp = "1.1.1.1"; Object srcUser = "nacos"; - Object time = new Timestamp(System.currentTimeMillis()); Object appNameTmp = "newAppName"; Object desc = "description"; Object use = "use"; @@ -340,7 +328,6 @@ public void testUpdateConfigInfoAtomicCas() { context.putUpdateParameter(FieldConstant.MD5, newMD5); context.putUpdateParameter(FieldConstant.SRC_IP, srcIp); context.putUpdateParameter(FieldConstant.SRC_USER, srcUser); - context.putUpdateParameter(FieldConstant.GMT_MODIFIED, time); context.putUpdateParameter(FieldConstant.APP_NAME, appNameTmp); context.putUpdateParameter(FieldConstant.C_DESC, desc); context.putUpdateParameter(FieldConstant.C_USE, use); @@ -358,12 +345,12 @@ public void testUpdateConfigInfoAtomicCas() { context.putWhereParameter(FieldConstant.MD5, md5); MapperResult mapperResult = configInfoMapperByDerby.updateConfigInfoAtomicCas(context); - Assert.assertEquals(mapperResult.getSql(), "UPDATE config_info SET " - + "content=?, md5 = ?, src_ip=?,src_user=?,gmt_modified=?, app_name=?,c_desc=?,c_use=?," - + "effect=?,type=?,c_schema=?,encrypted_data_key=? " - + "WHERE data_id=? AND group_id=? AND tenant_id=? AND (md5=? OR md5 IS NULL OR md5='')"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), - new Object[] {newContent, newMD5, srcIp, srcUser, time, appNameTmp, desc, use, effect, type, schema, - encrypedDataKey, dataId, group, tenantId, md5}); + assertEquals(mapperResult.getSql(), + "UPDATE config_info SET " + "content=?, md5=?, src_ip=?, src_user=?, gmt_modified=CURRENT_TIMESTAMP," + + " app_name=?, c_desc=?, c_use=?, effect=?, type=?, c_schema=?, encrypted_data_key=? " + + "WHERE data_id=? AND group_id=? AND tenant_id=? AND (md5=? OR md5 IS NULL OR md5='')"); + assertArrayEquals( + new Object[]{newContent, newMD5, srcIp, srcUser, appNameTmp, desc, use, effect, type, schema, encrypedDataKey, + dataId, group, tenantId, md5}, mapperResult.getParamList().toArray()); } } diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoTagMapperByDerbyTest.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoTagMapperByDerbyTest.java index 0c552144a5a..92206ff868f 100644 --- a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoTagMapperByDerbyTest.java +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoTagMapperByDerbyTest.java @@ -22,16 +22,16 @@ import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.sql.Timestamp; import java.util.List; -public class ConfigInfoTagMapperByDerbyTest { - - private ConfigInfoTagMapperByDerby configInfoTagMapperByDerby; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ConfigInfoTagMapperByDerbyTest { private final Object[] emptyObjs = new Object[] {}; @@ -53,8 +53,10 @@ public class ConfigInfoTagMapperByDerbyTest { MapperContext context; - @Before - public void setUp() throws Exception { + private ConfigInfoTagMapperByDerby configInfoTagMapperByDerby; + + @BeforeEach + void setUp() throws Exception { configInfoTagMapperByDerby = new ConfigInfoTagMapperByDerby(); context = new MapperContext(startRow, pageSize); @@ -68,7 +70,7 @@ public void setUp() throws Exception { } @Test - public void testUpdateConfigInfo4TagCas() { + void testUpdateConfigInfo4TagCas() { String newContent = "new Content"; String newMD5 = "newMD5"; String srcIp = "1.1.1.1"; @@ -106,34 +108,31 @@ public void testUpdateConfigInfo4TagCas() { MapperResult mapperResult = configInfoTagMapperByDerby.updateConfigInfo4TagCas(context); - Assert.assertEquals(mapperResult.getSql(), - "UPDATE config_info_tag SET content = ?, md5 = ?, src_ip = ?,src_user = ?,gmt_modified = ?," - + "app_name = ? WHERE data_id = ? AND group_id = ? AND tenant_id = ? AND tag_id = ? AND " - + "(md5 = ? OR md5 IS NULL OR md5 = '')"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), - new Object[] {newContent, newMD5, srcIp, srcUser, time, appNameTmp, dataId, group, tenantId, tagId, - md5}); + assertEquals(mapperResult.getSql(), "UPDATE config_info_tag SET content = ?, md5 = ?, src_ip = ?,src_user = ?,gmt_modified = ?," + + "app_name = ? WHERE data_id = ? AND group_id = ? AND tenant_id = ? AND tag_id = ? AND " + + "(md5 = ? OR md5 IS NULL OR md5 = '')"); + assertArrayEquals(new Object[] {newContent, newMD5, srcIp, srcUser, time, appNameTmp, dataId, group, tenantId, tagId, md5}, + mapperResult.getParamList().toArray()); } @Test - public void testFindAllConfigInfoTagForDumpAllFetchRows() { + void testFindAllConfigInfoTagForDumpAllFetchRows() { MapperResult mapperResult = configInfoTagMapperByDerby.findAllConfigInfoTagForDumpAllFetchRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT t.id,data_id,group_id,tenant_id,tag_id,app_name,content,md5,gmt_modified FROM " - + "( SELECT id FROM config_info_tag ORDER BY id OFFSET " + startRow + " ROWS FETCH NEXT " - + pageSize + " ROWS ONLY ) g, " + "config_info_tag t WHERE g.id = t.id"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); + assertEquals(mapperResult.getSql(), "SELECT t.id,data_id,group_id,tenant_id,tag_id,app_name,content,md5,gmt_modified FROM " + + "( SELECT id FROM config_info_tag ORDER BY id OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY ) g, " + + "config_info_tag t WHERE g.id = t.id"); + assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); } @Test - public void testGetTableName() { + void testGetTableName() { String tableName = configInfoTagMapperByDerby.getTableName(); - Assert.assertEquals(tableName, TableConstant.CONFIG_INFO_TAG); + assertEquals(TableConstant.CONFIG_INFO_TAG, tableName); } @Test - public void testGetDataSource() { + void testGetDataSource() { String dataSource = configInfoTagMapperByDerby.getDataSource(); - Assert.assertEquals(dataSource, DataSourceConstant.DERBY); + assertEquals(DataSourceConstant.DERBY, dataSource); } } diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoTagsRelationMapperByDerbyTest.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoTagsRelationMapperByDerbyTest.java index 6dbe42121eb..9fd51b29ee3 100644 --- a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoTagsRelationMapperByDerbyTest.java +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/ConfigInfoTagsRelationMapperByDerbyTest.java @@ -22,16 +22,16 @@ import com.alibaba.nacos.plugin.datasource.constants.TableConstant; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; -public class ConfigInfoTagsRelationMapperByDerbyTest { - - private ConfigInfoTagsRelationMapperByDerby configInfoTagsRelationMapperByDerby; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ConfigInfoTagsRelationMapperByDerbyTest { int startRow = 0; @@ -43,8 +43,10 @@ public class ConfigInfoTagsRelationMapperByDerbyTest { MapperContext context; - @Before - public void setUp() throws Exception { + private ConfigInfoTagsRelationMapperByDerby configInfoTagsRelationMapperByDerby; + + @BeforeEach + void setUp() throws Exception { this.configInfoTagsRelationMapperByDerby = new ConfigInfoTagsRelationMapperByDerby(); context = new MapperContext(startRow, pageSize); context.putWhereParameter(FieldConstant.TENANT_ID, tenantId); @@ -52,60 +54,57 @@ public void setUp() throws Exception { } @Test - public void testFindConfigInfo4PageCountRows() { + void testFindConfigInfo4PageCountRows() { MapperResult mapperResult = configInfoTagsRelationMapperByDerby.findConfigInfoLike4PageCountRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT count(*) FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id WHERE " - + "a.tenant_id LIKE ? AND b.tag_name IN (?, ?, ?, ?, ?) "); + assertEquals(mapperResult.getSql(), "SELECT count(*) FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id WHERE " + + "a.tenant_id LIKE ? AND b.tag_name IN (?, ?, ?, ?, ?) "); List list = CollectionUtils.list(tenantId); list.addAll(Arrays.asList(tagArr)); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); + assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); } @Test - public void testFindConfigInfo4PageFetchRows() { + void testFindConfigInfo4PageFetchRows() { MapperResult mapperResult = configInfoTagsRelationMapperByDerby.findConfigInfo4PageFetchRows(context); - Assert.assertEquals(mapperResult.getSql(), + assertEquals(mapperResult.getSql(), "SELECT a.id,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content FROM config_info a LEFT JOIN " + "config_tags_relation b ON a.id=b.id WHERE a.tenant_id=? AND b.tag_name IN (?, ?, ?, ?, ?) " + "OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY"); List list = CollectionUtils.list(tenantId); list.addAll(Arrays.asList(tagArr)); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); + assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); } @Test - public void testFindConfigInfoLike4PageCountRows() { + void testFindConfigInfoLike4PageCountRows() { MapperResult mapperResult = configInfoTagsRelationMapperByDerby.findConfigInfoLike4PageCountRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT count(*) FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id " - + "WHERE a.tenant_id LIKE ? AND b.tag_name IN (?, ?, ?, ?, ?) "); + assertEquals(mapperResult.getSql(), "SELECT count(*) FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id " + + "WHERE a.tenant_id LIKE ? AND b.tag_name IN (?, ?, ?, ?, ?) "); List list = CollectionUtils.list(tenantId); list.addAll(Arrays.asList(tagArr)); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); + assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); } @Test - public void tsetFindConfigInfoLike4PageFetchRows() { + void tsetFindConfigInfoLike4PageFetchRows() { MapperResult mapperResult = configInfoTagsRelationMapperByDerby.findConfigInfoLike4PageFetchRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT a.ID,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content FROM config_info a " - + "LEFT JOIN config_tags_relation b ON a.id=b.id WHERE a.tenant_id LIKE ? AND b.tag_name " - + "IN (?, ?, ?, ?, ?) OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY"); + assertEquals(mapperResult.getSql(), "SELECT a.ID,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content,a.type FROM config_info a " + + "LEFT JOIN config_tags_relation b ON a.id=b.id WHERE a.tenant_id LIKE ? AND b.tag_name " + + "IN (?, ?, ?, ?, ?) OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY"); List list = CollectionUtils.list(tenantId); list.addAll(Arrays.asList(tagArr)); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); + assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); } @Test - public void testGetTableName() { + void testGetTableName() { String tableName = configInfoTagsRelationMapperByDerby.getTableName(); - Assert.assertEquals(tableName, TableConstant.CONFIG_TAGS_RELATION); + assertEquals(TableConstant.CONFIG_TAGS_RELATION, tableName); } @Test - public void testGetDataSource() { + void testGetDataSource() { String dataSource = configInfoTagsRelationMapperByDerby.getDataSource(); - Assert.assertEquals(dataSource, DataSourceConstant.DERBY); + assertEquals(DataSourceConstant.DERBY, dataSource); } } diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/GroupCapacityMapperByDerbyTest.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/GroupCapacityMapperByDerbyTest.java index 6e749b01948..e6a94b3e24d 100644 --- a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/GroupCapacityMapperByDerbyTest.java +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/GroupCapacityMapperByDerbyTest.java @@ -21,15 +21,15 @@ import com.alibaba.nacos.plugin.datasource.constants.TableConstant; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.sql.Timestamp; -public class GroupCapacityMapperByDerbyTest { - - private GroupCapacityMapperByDerby groupCapacityMapperByDerby; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class GroupCapacityMapperByDerbyTest { private final Object[] emptyObjs = new Object[] {}; @@ -45,8 +45,10 @@ public class GroupCapacityMapperByDerbyTest { MapperContext context; - @Before - public void setUp() throws Exception { + private GroupCapacityMapperByDerby groupCapacityMapperByDerby; + + @BeforeEach + void setUp() throws Exception { this.groupCapacityMapperByDerby = new GroupCapacityMapperByDerby(); context = new MapperContext(startRow, pageSize); context.putUpdateParameter(FieldConstant.GMT_MODIFIED, modified); @@ -56,19 +58,19 @@ public void setUp() throws Exception { } @Test - public void testGetTableName() { + void testGetTableName() { String tableName = groupCapacityMapperByDerby.getTableName(); - Assert.assertEquals(tableName, TableConstant.GROUP_CAPACITY); + assertEquals(TableConstant.GROUP_CAPACITY, tableName); } @Test - public void testGetDataSource() { + void testGetDataSource() { String dataSource = groupCapacityMapperByDerby.getDataSource(); - Assert.assertEquals(dataSource, DataSourceConstant.DERBY); + assertEquals(DataSourceConstant.DERBY, dataSource); } @Test - public void testInsertIntoSelect() { + void testInsertIntoSelect() { Object group = "group"; Object quota = "quota"; Object maxAggrSize = 10; @@ -85,16 +87,16 @@ public void testInsertIntoSelect() { context.putUpdateParameter(FieldConstant.GMT_MODIFIED, modified); MapperResult mapperResult = groupCapacityMapperByDerby.insertIntoSelect(context); - Assert.assertEquals(mapperResult.getSql(), + assertEquals(mapperResult.getSql(), "INSERT INTO group_capacity (group_id, quota, usage, max_size, max_aggr_count, max_aggr_size,gmt_create," + " gmt_modified) SELECT ?, ?, count(*), ?, ?, ?, ?, ? FROM config_info"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), - new Object[] {group, quota, maxSize, maxAggrCount, maxAggrSize, createTime, modified}); + assertArrayEquals(new Object[] {group, quota, maxSize, maxAggrCount, maxAggrSize, createTime, modified}, + mapperResult.getParamList().toArray()); } @Test - public void testInsertIntoSelectByWhere() { + void testInsertIntoSelectByWhere() { Object group = "group"; Object quota = "quota"; Object maxAggrSize = 10; @@ -112,74 +114,72 @@ public void testInsertIntoSelectByWhere() { context.putUpdateParameter(FieldConstant.GMT_MODIFIED, modified); MapperResult mapperResult = groupCapacityMapperByDerby.insertIntoSelectByWhere(context); - Assert.assertEquals(mapperResult.getSql(), + assertEquals(mapperResult.getSql(), "INSERT INTO group_capacity (group_id, quota, usage, max_size, max_aggr_count, max_aggr_size, gmt_create," + " gmt_modified) SELECT ?, ?, count(*), ?, ?, ?, ?, ? FROM config_info WHERE group_id=? AND tenant_id = ''"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), - new Object[] {group, quota, maxSize, maxAggrCount, maxAggrSize, createTime, modified, group}); + assertArrayEquals(new Object[] {group, quota, maxSize, maxAggrCount, maxAggrSize, createTime, modified, group}, + mapperResult.getParamList().toArray()); } @Test - public void testIncrementUsageByWhereQuotaEqualZero() { + void testIncrementUsageByWhereQuotaEqualZero() { Object usage = 1; context.putWhereParameter(FieldConstant.USAGE, usage); MapperResult mapperResult = groupCapacityMapperByDerby.incrementUsageByWhereQuotaEqualZero(context); - Assert.assertEquals(mapperResult.getSql(), - "UPDATE group_capacity SET usage = usage + 1, gmt_modified = ? WHERE group_id = ? AND usage < ? AND quota = 0"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, groupId, usage}); + assertEquals("UPDATE group_capacity SET usage = usage + 1, gmt_modified = ? WHERE group_id = ? AND usage < ? AND quota = 0", + mapperResult.getSql()); + assertArrayEquals(new Object[] {modified, groupId, usage}, mapperResult.getParamList().toArray()); } @Test - public void testIncrementUsageByWhereQuotaNotEqualZero() { + void testIncrementUsageByWhereQuotaNotEqualZero() { MapperResult mapperResult = groupCapacityMapperByDerby.incrementUsageByWhereQuotaNotEqualZero(context); - Assert.assertEquals(mapperResult.getSql(), - "UPDATE group_capacity SET usage = usage + 1, gmt_modified = ? WHERE group_id = ? AND usage < quota AND quota != 0"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, groupId}); + assertEquals("UPDATE group_capacity SET usage = usage + 1, gmt_modified = ? WHERE group_id = ? AND usage < quota AND quota != 0", + mapperResult.getSql()); + assertArrayEquals(new Object[] {modified, groupId}, mapperResult.getParamList().toArray()); } @Test - public void testIncrementUsageByWhere() { + void testIncrementUsageByWhere() { MapperResult mapperResult = groupCapacityMapperByDerby.incrementUsageByWhere(context); - Assert.assertEquals(mapperResult.getSql(), - "UPDATE group_capacity SET usage = usage + 1, gmt_modified = ? WHERE group_id = ?"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, groupId}); + assertEquals("UPDATE group_capacity SET usage = usage + 1, gmt_modified = ? WHERE group_id = ?", mapperResult.getSql()); + assertArrayEquals(new Object[] {modified, groupId}, mapperResult.getParamList().toArray()); } @Test - public void testDecrementUsageByWhere() { + void testDecrementUsageByWhere() { MapperResult mapperResult = groupCapacityMapperByDerby.decrementUsageByWhere(context); - Assert.assertEquals(mapperResult.getSql(), - "UPDATE group_capacity SET usage = usage - 1, gmt_modified = ? WHERE group_id = ? AND usage > 0"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, groupId}); + assertEquals("UPDATE group_capacity SET usage = usage - 1, gmt_modified = ? WHERE group_id = ? AND usage > 0", + mapperResult.getSql()); + assertArrayEquals(new Object[] {modified, groupId}, mapperResult.getParamList().toArray()); } @Test - public void testUpdateUsage() { + void testUpdateUsage() { MapperResult mapperResult = groupCapacityMapperByDerby.updateUsage(context); - Assert.assertEquals(mapperResult.getSql(), - "UPDATE group_capacity SET usage = (SELECT count(*) FROM config_info), gmt_modified = ? WHERE group_id = ?"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, groupId}); + assertEquals("UPDATE group_capacity SET usage = (SELECT count(*) FROM config_info), gmt_modified = ? WHERE group_id = ?", + mapperResult.getSql()); + assertArrayEquals(new Object[] {modified, groupId}, mapperResult.getParamList().toArray()); } @Test - public void testUpdateUsageByWhere() { + void testUpdateUsageByWhere() { MapperResult mapperResult = groupCapacityMapperByDerby.updateUsageByWhere(context); - Assert.assertEquals(mapperResult.getSql(), + assertEquals(mapperResult.getSql(), "UPDATE group_capacity SET usage = (SELECT count(*) FROM config_info WHERE group_id=? AND tenant_id = '')," + " gmt_modified = ? WHERE group_id= ?"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {groupId, modified, groupId}); + assertArrayEquals(new Object[] {groupId, modified, groupId}, mapperResult.getParamList().toArray()); } @Test - public void testSelectGroupInfoBySize() { + void testSelectGroupInfoBySize() { Object id = 1; context.putWhereParameter(FieldConstant.ID, id); MapperResult mapperResult = groupCapacityMapperByDerby.selectGroupInfoBySize(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT id, group_id FROM group_capacity WHERE id > ? OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY"); + assertEquals("SELECT id, group_id FROM group_capacity WHERE id > ? OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY", mapperResult.getSql()); context.putWhereParameter(FieldConstant.GMT_CREATE, createTime); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {id, pageSize}); + assertArrayEquals(new Object[] {id, pageSize}, mapperResult.getParamList().toArray()); } } diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/HistoryConfigInfoMapperByDerbyTest.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/HistoryConfigInfoMapperByDerbyTest.java index 631fb4b5d36..434a4d583fc 100644 --- a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/HistoryConfigInfoMapperByDerbyTest.java +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/HistoryConfigInfoMapperByDerbyTest.java @@ -21,15 +21,15 @@ import com.alibaba.nacos.plugin.datasource.constants.TableConstant; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.sql.Timestamp; -public class HistoryConfigInfoMapperByDerbyTest { - - private HistoryConfigInfoMapperByDerby historyConfigInfoMapperByDerby; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class HistoryConfigInfoMapperByDerbyTest { int startRow = 0; @@ -45,8 +45,10 @@ public class HistoryConfigInfoMapperByDerbyTest { MapperContext context; - @Before - public void setUp() throws Exception { + private HistoryConfigInfoMapperByDerby historyConfigInfoMapperByDerby; + + @BeforeEach + void setUp() throws Exception { historyConfigInfoMapperByDerby = new HistoryConfigInfoMapperByDerby(); context = new MapperContext(startRow, pageSize); context.putWhereParameter(FieldConstant.START_TIME, startTime); @@ -58,33 +60,32 @@ public void setUp() throws Exception { } @Test - public void testRemoveConfigHistory() { + void testRemoveConfigHistory() { MapperResult mapperResult = historyConfigInfoMapperByDerby.removeConfigHistory(context); - Assert.assertEquals(mapperResult.getSql(), + assertEquals(mapperResult.getSql(), "DELETE FROM his_config_info WHERE id IN( SELECT id FROM his_config_info WHERE gmt_modified < ? " + "OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY)"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {startTime, limitSize}); + assertArrayEquals(new Object[] {startTime, limitSize}, mapperResult.getParamList().toArray()); } @Test - public void testFindConfigHistoryCountByTime() { + void testFindConfigHistoryCountByTime() { MapperResult mapperResult = historyConfigInfoMapperByDerby.findConfigHistoryCountByTime(context); - Assert.assertEquals(mapperResult.getSql(), "SELECT count(*) FROM his_config_info WHERE gmt_modified < ?"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {startTime}); + assertEquals("SELECT count(*) FROM his_config_info WHERE gmt_modified < ?", mapperResult.getSql()); + assertArrayEquals(new Object[] {startTime}, mapperResult.getParamList().toArray()); } @Test - public void testFindDeletedConfig() { + void testFindDeletedConfig() { MapperResult mapperResult = historyConfigInfoMapperByDerby.findDeletedConfig(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT data_id, group_id, tenant_id,gmt_modified,nid FROM his_config_info WHERE op_type = 'D' " - + "AND gmt_modified >= ? and nid > ? order by nid OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY"); + assertEquals(mapperResult.getSql(), "SELECT data_id, group_id, tenant_id,gmt_modified,nid FROM his_config_info WHERE op_type = 'D' " + + "AND gmt_modified >= ? and nid > ? order by nid OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {startTime, lastMaxId, pageSize}); + assertArrayEquals(new Object[] {startTime, lastMaxId, pageSize}, mapperResult.getParamList().toArray()); } @Test - public void testFindConfigHistoryFetchRows() { + void testFindConfigHistoryFetchRows() { Object dataId = "dataId"; Object groupId = "groupId"; Object tenantId = "tenantId"; @@ -94,32 +95,31 @@ public void testFindConfigHistoryFetchRows() { context.putWhereParameter(FieldConstant.TENANT_ID, tenantId); context.putWhereParameter(FieldConstant.DATA_ID, dataId); MapperResult mapperResult = historyConfigInfoMapperByDerby.findConfigHistoryFetchRows(context); - Assert.assertEquals(mapperResult.getSql(), + assertEquals(mapperResult.getSql(), "SELECT nid,data_id,group_id,tenant_id,app_name,src_ip,src_user,op_type,gmt_create,gmt_modified FROM his_config_info " + "WHERE data_id = ? AND group_id = ? AND tenant_id = ? ORDER BY nid DESC"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {dataId, groupId, tenantId}); + assertArrayEquals(new Object[] {dataId, groupId, tenantId}, mapperResult.getParamList().toArray()); } @Test - public void testDetailPreviousConfigHistory() { + void testDetailPreviousConfigHistory() { Object id = "1"; context.putWhereParameter(FieldConstant.ID, id); MapperResult mapperResult = historyConfigInfoMapperByDerby.detailPreviousConfigHistory(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT nid,data_id,group_id,tenant_id,app_name,content,md5,src_user,src_ip,op_type,gmt_create," - + "gmt_modified,encrypted_data_key FROM his_config_info WHERE nid = (SELECT max(nid) FROM his_config_info WHERE id = ?)"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {id}); + assertEquals(mapperResult.getSql(), "SELECT nid,data_id,group_id,tenant_id,app_name,content,md5,src_user,src_ip,op_type,gmt_create," + + "gmt_modified,encrypted_data_key FROM his_config_info WHERE nid = (SELECT max(nid) FROM his_config_info WHERE id = ?)"); + assertArrayEquals(new Object[] {id}, mapperResult.getParamList().toArray()); } @Test - public void testGetTableName() { + void testGetTableName() { String tableName = historyConfigInfoMapperByDerby.getTableName(); - Assert.assertEquals(tableName, TableConstant.HIS_CONFIG_INFO); + assertEquals(TableConstant.HIS_CONFIG_INFO, tableName); } @Test - public void testGetDataSource() { + void testGetDataSource() { String dataSource = historyConfigInfoMapperByDerby.getDataSource(); - Assert.assertEquals(dataSource, DataSourceConstant.DERBY); + assertEquals(DataSourceConstant.DERBY, dataSource); } } diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/TenantCapacityMapperByDerbyTest.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/TenantCapacityMapperByDerbyTest.java index be04ed044ed..46072adb781 100644 --- a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/TenantCapacityMapperByDerbyTest.java +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/TenantCapacityMapperByDerbyTest.java @@ -21,28 +21,30 @@ import com.alibaba.nacos.plugin.datasource.constants.TableConstant; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.sql.Timestamp; -public class TenantCapacityMapperByDerbyTest { - - private TenantCapacityMapperByDerby tenantCapacityMapperByDerby; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class TenantCapacityMapperByDerbyTest { String tenantId = "tenantId"; MapperContext context; + private TenantCapacityMapperByDerby tenantCapacityMapperByDerby; + private Object modified = new Timestamp(System.currentTimeMillis()); private Object oldModified = new Timestamp(System.currentTimeMillis()); private Object usage = 1; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { tenantCapacityMapperByDerby = new TenantCapacityMapperByDerby(); context = new MapperContext(); context.putUpdateParameter(FieldConstant.GMT_MODIFIED, modified); @@ -53,75 +55,70 @@ public void setUp() throws Exception { } @Test - public void testGetTableName() { + void testGetTableName() { String tableName = tenantCapacityMapperByDerby.getTableName(); - Assert.assertEquals(tableName, TableConstant.TENANT_CAPACITY); + assertEquals(TableConstant.TENANT_CAPACITY, tableName); } @Test - public void testGetDataSource() { + void testGetDataSource() { String dataSource = tenantCapacityMapperByDerby.getDataSource(); - Assert.assertEquals(dataSource, DataSourceConstant.DERBY); + assertEquals(DataSourceConstant.DERBY, dataSource); } @Test - public void testIncrementUsageWithDefaultQuotaLimit() { + void testIncrementUsageWithDefaultQuotaLimit() { MapperResult mapperResult = tenantCapacityMapperByDerby.incrementUsageWithDefaultQuotaLimit(context); - Assert.assertEquals(mapperResult.getSql(), - "UPDATE tenant_capacity SET usage = usage + 1, gmt_modified = ? WHERE tenant_id = ? AND usage <" - + " ? AND quota = 0"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, tenantId, usage}); + assertEquals(mapperResult.getSql(), + "UPDATE tenant_capacity SET usage = usage + 1, gmt_modified = ? WHERE tenant_id = ? AND usage <" + " ? AND quota = 0"); + assertArrayEquals(new Object[] {modified, tenantId, usage}, mapperResult.getParamList().toArray()); } @Test - public void testIncrementUsageWithQuotaLimit() { + void testIncrementUsageWithQuotaLimit() { MapperResult mapperResult = tenantCapacityMapperByDerby.incrementUsageWithQuotaLimit(context); - Assert.assertEquals(mapperResult.getSql(), - "UPDATE tenant_capacity SET usage = usage + 1, gmt_modified = ? WHERE tenant_id = ? AND usage < " - + "quota AND quota != 0"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, tenantId}); + assertEquals(mapperResult.getSql(), + "UPDATE tenant_capacity SET usage = usage + 1, gmt_modified = ? WHERE tenant_id = ? AND usage < " + "quota AND quota != 0"); + assertArrayEquals(new Object[] {modified, tenantId}, mapperResult.getParamList().toArray()); } @Test - public void testIncrementUsage() { + void testIncrementUsage() { MapperResult mapperResult = tenantCapacityMapperByDerby.incrementUsage(context); - Assert.assertEquals(mapperResult.getSql(), - "UPDATE tenant_capacity SET usage = usage + 1, gmt_modified = ? WHERE tenant_id = ?"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, tenantId}); + assertEquals("UPDATE tenant_capacity SET usage = usage + 1, gmt_modified = ? WHERE tenant_id = ?", mapperResult.getSql()); + assertArrayEquals(new Object[] {modified, tenantId}, mapperResult.getParamList().toArray()); } @Test - public void testDecrementUsage() { + void testDecrementUsage() { MapperResult mapperResult = tenantCapacityMapperByDerby.decrementUsage(context); - Assert.assertEquals(mapperResult.getSql(), - "UPDATE tenant_capacity SET usage = usage - 1, gmt_modified = ? WHERE tenant_id = ? AND usage > 0"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, tenantId}); + assertEquals("UPDATE tenant_capacity SET usage = usage - 1, gmt_modified = ? WHERE tenant_id = ? AND usage > 0", + mapperResult.getSql()); + assertArrayEquals(new Object[] {modified, tenantId}, mapperResult.getParamList().toArray()); } @Test - public void testCorrectUsage() { + void testCorrectUsage() { MapperResult mapperResult = tenantCapacityMapperByDerby.correctUsage(context); - Assert.assertEquals(mapperResult.getSql(), - "UPDATE tenant_capacity SET usage = (SELECT count(*) FROM config_info WHERE tenant_id = ?), " - + "gmt_modified = ? WHERE tenant_id = ?"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, modified, tenantId}); + assertEquals(mapperResult.getSql(), "UPDATE tenant_capacity SET usage = (SELECT count(*) FROM config_info WHERE tenant_id = ?), " + + "gmt_modified = ? WHERE tenant_id = ?"); + assertArrayEquals(new Object[] {tenantId, modified, tenantId}, mapperResult.getParamList().toArray()); } @Test - public void testGetCapacityList4CorrectUsage() { + void testGetCapacityList4CorrectUsage() { Object id = 1; Object limit = 10; context.putWhereParameter(FieldConstant.ID, id); context.putWhereParameter(FieldConstant.LIMIT_SIZE, limit); MapperResult mapperResult = tenantCapacityMapperByDerby.getCapacityList4CorrectUsage(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT id, tenant_id FROM tenant_capacity WHERE id>? OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {id, limit}); + assertEquals("SELECT id, tenant_id FROM tenant_capacity WHERE id>? OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY", mapperResult.getSql()); + assertArrayEquals(new Object[] {id, limit}, mapperResult.getParamList().toArray()); } @Test - public void testInsertTenantCapacity() { + void testInsertTenantCapacity() { Object group = "group"; Object quota = "quota"; Object maxAggrSize = 10; @@ -142,10 +139,10 @@ public void testInsertTenantCapacity() { context.putWhereParameter(FieldConstant.TENANT_ID, tenantId); MapperResult mapperResult = tenantCapacityMapperByDerby.insertTenantCapacity(context); - Assert.assertEquals(mapperResult.getSql(), + assertEquals(mapperResult.getSql(), "INSERT INTO tenant_capacity (tenant_id, quota, usage, max_size, max_aggr_count, max_aggr_size, " + "gmt_create, gmt_modified) SELECT ?, ?, count(*), ?, ?, ?, ?, ? FROM config_info WHERE tenant_id=?;"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), - new Object[] {tenantId, quota, maxSize, maxAggrCount, maxAggrSize, createTime, modified, tenantId}); + assertArrayEquals(new Object[] {tenantId, quota, maxSize, maxAggrCount, maxAggrSize, createTime, modified, tenantId}, + mapperResult.getParamList().toArray()); } } diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/TenantInfoMapperByDerbyTest.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/TenantInfoMapperByDerbyTest.java index 58723195380..4637ab1a824 100644 --- a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/TenantInfoMapperByDerbyTest.java +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/derby/TenantInfoMapperByDerbyTest.java @@ -18,28 +18,29 @@ import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; import com.alibaba.nacos.plugin.datasource.constants.TableConstant; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class TenantInfoMapperByDerbyTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class TenantInfoMapperByDerbyTest { private TenantInfoMapperByDerby tenantInfoMapperByDerby; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { tenantInfoMapperByDerby = new TenantInfoMapperByDerby(); } @Test - public void testGetTableName() { + void testGetTableName() { String tableName = tenantInfoMapperByDerby.getTableName(); - Assert.assertEquals(tableName, TableConstant.TENANT_INFO); + assertEquals(TableConstant.TENANT_INFO, tableName); } @Test - public void testGetDataSource() { + void testGetDataSource() { String dataSource = tenantInfoMapperByDerby.getDataSource(); - Assert.assertEquals(dataSource, DataSourceConstant.DERBY); + assertEquals(DataSourceConstant.DERBY, dataSource); } -} \ No newline at end of file +} diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoAggrMapperByMySqlTest.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoAggrMapperByMySqlTest.java index ce27ff774ee..a55d20fd88b 100644 --- a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoAggrMapperByMySqlTest.java +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoAggrMapperByMySqlTest.java @@ -22,27 +22,25 @@ import com.alibaba.nacos.plugin.datasource.constants.TableConstant; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; -@RunWith(JUnit4.class) -public class ConfigInfoAggrMapperByMySqlTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ConfigInfoAggrMapperByMySqlTest { private ConfigInfoAggrMapperByMySql configInfoAggrMapperByMySql; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { configInfoAggrMapperByMySql = new ConfigInfoAggrMapperByMySql(); } @Test - public void testBatchRemoveAggr() { + void testBatchRemoveAggr() { List datumList = Arrays.asList("1", "2", "3", "4", "5"); String dataId = "data-id"; String groupId = "group-id"; @@ -61,14 +59,14 @@ public void testBatchRemoveAggr() { String sql = mapperResult.getSql(); List paramList = mapperResult.getParamList(); - Assert.assertEquals(sql, "DELETE FROM config_info_aggr WHERE data_id = ? AND group_id = ? AND tenant_id = ? " - + "AND datum_id IN (?, ?, ?, ?, ?)"); + assertEquals(sql, + "DELETE FROM config_info_aggr WHERE data_id = ? AND group_id = ? AND tenant_id = ? " + "AND datum_id IN (?, ?, ?, ?, ?)"); - Assert.assertEquals(paramList, argList); + assertEquals(paramList, argList); } @Test - public void testAggrConfigInfoCount() { + void testAggrConfigInfoCount() { List datumIds = Arrays.asList("1", "2", "3", "4", "5"); String dataId = "data-id"; String groupId = "group-id"; @@ -87,14 +85,13 @@ public void testAggrConfigInfoCount() { String sql = mapperResult.getSql(); List paramList = mapperResult.getParamList(); - Assert.assertEquals(sql, - "SELECT count(*) FROM config_info_aggr WHERE data_id = ? AND group_id = ? AND tenant_id = ? " - + "AND datum_id IN (?, ?, ?, ?, ?)"); - Assert.assertEquals(paramList, argList); + assertEquals(sql, "SELECT count(*) FROM config_info_aggr WHERE data_id = ? AND group_id = ? AND tenant_id = ? " + + "AND datum_id IN (?, ?, ?, ?, ?)"); + assertEquals(paramList, argList); } @Test - public void testFindConfigInfoAggrIsOrdered() { + void testFindConfigInfoAggrIsOrdered() { String dataId = "data-id"; String groupId = "group-id"; String tenantId = "tenant-id"; @@ -108,13 +105,13 @@ public void testFindConfigInfoAggrIsOrdered() { String sql = mapperResult.getSql(); List paramList = mapperResult.getParamList(); - Assert.assertEquals(sql, "SELECT data_id,group_id,tenant_id,datum_id,app_name,content FROM " + assertEquals(sql, "SELECT data_id,group_id,tenant_id,datum_id,app_name,content FROM " + "config_info_aggr WHERE data_id = ? AND group_id = ? AND tenant_id = ? ORDER BY datum_id"); - Assert.assertEquals(paramList, Arrays.asList(dataId, groupId, tenantId)); + assertEquals(paramList, Arrays.asList(dataId, groupId, tenantId)); } @Test - public void testFindConfigInfoAggrByPageFetchRows() { + void testFindConfigInfoAggrByPageFetchRows() { String dataId = "data-id"; String groupId = "group-id"; String tenantId = "tenant-id"; @@ -132,28 +129,26 @@ public void testFindConfigInfoAggrByPageFetchRows() { String sql = mapperResult.getSql(); List paramList = mapperResult.getParamList(); - Assert.assertEquals(sql, - "SELECT data_id,group_id,tenant_id,datum_id,app_name,content FROM config_info_aggr WHERE " - + "data_id= ? AND group_id= ? AND tenant_id= ? ORDER BY datum_id LIMIT 0,5"); - Assert.assertEquals(paramList, Arrays.asList(dataId, groupId, tenantId)); + assertEquals(sql, "SELECT data_id,group_id,tenant_id,datum_id,app_name,content FROM config_info_aggr WHERE " + + "data_id= ? AND group_id= ? AND tenant_id= ? ORDER BY datum_id LIMIT 0,5"); + assertEquals(paramList, Arrays.asList(dataId, groupId, tenantId)); } @Test - public void testFindAllAggrGroupByDistinct() { + void testFindAllAggrGroupByDistinct() { MapperResult mapperResult = configInfoAggrMapperByMySql.findAllAggrGroupByDistinct(null); - Assert.assertEquals(mapperResult.getSql(), - "SELECT DISTINCT data_id, group_id, tenant_id FROM config_info_aggr"); + assertEquals("SELECT DISTINCT data_id, group_id, tenant_id FROM config_info_aggr", mapperResult.getSql()); } @Test - public void testGetTableName() { + void testGetTableName() { String tableName = configInfoAggrMapperByMySql.getTableName(); - Assert.assertEquals(tableName, TableConstant.CONFIG_INFO_AGGR); + assertEquals(TableConstant.CONFIG_INFO_AGGR, tableName); } @Test - public void testGetDataSource() { + void testGetDataSource() { String dataSource = configInfoAggrMapperByMySql.getDataSource(); - Assert.assertEquals(dataSource, DataSourceConstant.MYSQL); + assertEquals(DataSourceConstant.MYSQL, dataSource); } } diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoBetaMapperByMySqlTest.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoBetaMapperByMySqlTest.java index a06c21437c6..89d6cb8d6fd 100644 --- a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoBetaMapperByMySqlTest.java +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoBetaMapperByMySqlTest.java @@ -22,17 +22,17 @@ import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.sql.Timestamp; import java.util.Arrays; import java.util.List; -public class ConfigInfoBetaMapperByMySqlTest { - - private ConfigInfoBetaMapperByMySql configInfoBetaMapperByMySql; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ConfigInfoBetaMapperByMySqlTest { int startRow = 0; @@ -52,8 +52,10 @@ public class ConfigInfoBetaMapperByMySqlTest { MapperContext context; - @Before - public void setUp() throws Exception { + private ConfigInfoBetaMapperByMySql configInfoBetaMapperByMySql; + + @BeforeEach + void setUp() throws Exception { configInfoBetaMapperByMySql = new ConfigInfoBetaMapperByMySql(); context = new MapperContext(startRow, pageSize); @@ -67,12 +69,11 @@ public void setUp() throws Exception { } @Test - public void testUpdateConfigInfo4BetaCas() { + void testUpdateConfigInfo4BetaCas() { String newContent = "new Content"; String newMD5 = "newMD5"; String srcIp = "1.1.1.1"; Object srcUser = "nacos"; - Object time = new Timestamp(System.currentTimeMillis()); Object appNameTmp = "newAppName"; Object desc = "description"; Object use = "use"; @@ -86,7 +87,6 @@ public void testUpdateConfigInfo4BetaCas() { context.putUpdateParameter(FieldConstant.BETA_IPS, betaIps); context.putUpdateParameter(FieldConstant.SRC_IP, srcIp); context.putUpdateParameter(FieldConstant.SRC_USER, srcUser); - context.putUpdateParameter(FieldConstant.GMT_MODIFIED, time); context.putUpdateParameter(FieldConstant.APP_NAME, appNameTmp); context.putUpdateParameter(FieldConstant.C_DESC, desc); context.putUpdateParameter(FieldConstant.C_USE, use); @@ -106,36 +106,34 @@ public void testUpdateConfigInfo4BetaCas() { MapperResult mapperResult = configInfoBetaMapperByMySql.updateConfigInfo4BetaCas(context); String sql = mapperResult.getSql(); - List paramList = mapperResult.getParamList(); - Assert.assertEquals(sql, - "UPDATE config_info_beta SET content = ?,md5 = ?,beta_ips = ?,src_ip = ?,src_user = ?,gmt_modified = ?,app_name = ? " + assertEquals(sql, + "UPDATE config_info_beta SET content = ?,md5 = ?,beta_ips = ?," + + "src_ip = ?,src_user = ?,gmt_modified = NOW(3),app_name = ? " + "WHERE data_id = ? AND group_id = ? AND tenant_id = ? AND (md5 = ? OR md5 is null OR md5 = '')"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), - new Object[] {newContent, newMD5, betaIps, srcIp, srcUser, time, appNameTmp, dataId, group, tenantId, - md5}); + assertArrayEquals(new Object[]{newContent, newMD5, betaIps, srcIp, srcUser, appNameTmp, dataId, group, tenantId, md5}, + mapperResult.getParamList().toArray()); } @Test - public void testFindAllConfigInfoBetaForDumpAllFetchRows() { + void testFindAllConfigInfoBetaForDumpAllFetchRows() { MapperResult result = configInfoBetaMapperByMySql.findAllConfigInfoBetaForDumpAllFetchRows(context); String sql = result.getSql(); List paramList = result.getParamList(); - Assert.assertEquals(sql, - " SELECT t.id,data_id,group_id,tenant_id,app_name,content,md5,gmt_modified,beta_ips,encrypted_data_key " - + " FROM ( SELECT id FROM config_info_beta ORDER BY id LIMIT " + startRow + "," + pageSize - + " )" + " g, config_info_beta t WHERE g.id = t.id "); - Assert.assertEquals(paramList, Arrays.asList(startRow, pageSize)); + assertEquals(sql, " SELECT t.id,data_id,group_id,tenant_id,app_name,content,md5,gmt_modified,beta_ips,encrypted_data_key " + + " FROM ( SELECT id FROM config_info_beta ORDER BY id LIMIT " + startRow + "," + pageSize + " )" + + " g, config_info_beta t WHERE g.id = t.id "); + assertEquals(paramList, Arrays.asList(startRow, pageSize)); } @Test - public void testGetTableName() { + void testGetTableName() { String tableName = configInfoBetaMapperByMySql.getTableName(); - Assert.assertEquals(tableName, TableConstant.CONFIG_INFO_BETA); + assertEquals(TableConstant.CONFIG_INFO_BETA, tableName); } @Test - public void testGetDataSource() { + void testGetDataSource() { String dataSource = configInfoBetaMapperByMySql.getDataSource(); - Assert.assertEquals(dataSource, DataSourceConstant.MYSQL); + assertEquals(DataSourceConstant.MYSQL, dataSource); } } diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoMapperByMySqlTest.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoMapperByMySqlTest.java index 715a874b1f0..91d1facd6ec 100644 --- a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoMapperByMySqlTest.java +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoMapperByMySqlTest.java @@ -24,16 +24,16 @@ import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.sql.Timestamp; import java.util.List; -public class ConfigInfoMapperByMySqlTest { - - private ConfigInfoMapperByMySql configInfoMapperByMySql; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ConfigInfoMapperByMySqlTest { private final Object[] emptyObjs = new Object[] {}; @@ -59,8 +59,10 @@ public class ConfigInfoMapperByMySqlTest { MapperContext context; - @Before - public void setUp() throws Exception { + private ConfigInfoMapperByMySql configInfoMapperByMySql; + + @BeforeEach + void setUp() throws Exception { configInfoMapperByMySql = new ConfigInfoMapperByMySql(); context = new MapperContext(startRow, pageSize); @@ -76,258 +78,243 @@ public void setUp() throws Exception { } @Test - public void testFindConfigMaxId() { + void testFindConfigMaxId() { MapperResult mapperResult = configInfoMapperByMySql.findConfigMaxId(null); - Assert.assertEquals(mapperResult.getSql(), "SELECT MAX(id) FROM config_info"); + assertEquals("SELECT MAX(id) FROM config_info", mapperResult.getSql()); } @Test - public void testFindAllDataIdAndGroup() { + void testFindAllDataIdAndGroup() { MapperResult mapperResult = configInfoMapperByMySql.findAllDataIdAndGroup(null); - Assert.assertEquals(mapperResult.getSql(), "SELECT DISTINCT data_id, group_id FROM config_info"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); + assertEquals("SELECT DISTINCT data_id, group_id FROM config_info", mapperResult.getSql()); + assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); } @Test - public void testFindConfigInfoByAppCountRows() { + void testFindConfigInfoByAppCountRows() { MapperResult mapperResult = configInfoMapperByMySql.findConfigInfoByAppCountRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT count(*) FROM config_info WHERE tenant_id LIKE ? AND app_name = ?"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName}); + assertEquals("SELECT count(*) FROM config_info WHERE tenant_id LIKE ? AND app_name = ?", mapperResult.getSql()); + assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray()); } @Test - public void testFindConfigInfoByAppFetchRows() { + void testFindConfigInfoByAppFetchRows() { MapperResult mapperResult = configInfoMapperByMySql.findConfigInfoByAppFetchRows(context); - Assert.assertEquals(mapperResult.getSql(), + assertEquals(mapperResult.getSql(), "SELECT id,data_id,group_id,tenant_id,app_name,content FROM config_info WHERE tenant_id LIKE ? AND app_name= ? LIMIT " + startRow + "," + pageSize); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName}); + assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray()); } @Test - public void testConfigInfoLikeTenantCount() { + void testConfigInfoLikeTenantCount() { MapperResult mapperResult = configInfoMapperByMySql.configInfoLikeTenantCount(context); - Assert.assertEquals(mapperResult.getSql(), "SELECT count(*) FROM config_info WHERE tenant_id LIKE ?"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId}); + assertEquals("SELECT count(*) FROM config_info WHERE tenant_id LIKE ?", mapperResult.getSql()); + assertArrayEquals(new Object[] {tenantId}, mapperResult.getParamList().toArray()); } @Test - public void testGetTenantIdList() { + void testGetTenantIdList() { MapperResult mapperResult = configInfoMapperByMySql.getTenantIdList(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT tenant_id FROM config_info WHERE tenant_id != '" + NamespaceUtil.getNamespaceDefaultId() - + "' GROUP BY tenant_id LIMIT " + startRow + "," + pageSize); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); + assertEquals(mapperResult.getSql(), "SELECT tenant_id FROM config_info WHERE tenant_id != '" + NamespaceUtil.getNamespaceDefaultId() + + "' GROUP BY tenant_id LIMIT " + startRow + "," + pageSize); + assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); } @Test - public void testGetGroupIdList() { + void testGetGroupIdList() { MapperResult mapperResult = configInfoMapperByMySql.getGroupIdList(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT group_id FROM config_info WHERE tenant_id ='' GROUP BY group_id LIMIT " + startRow + "," - + pageSize); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); + assertEquals(mapperResult.getSql(), + "SELECT group_id FROM config_info WHERE tenant_id ='' GROUP BY group_id LIMIT " + startRow + "," + pageSize); + assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); } @Test - public void testFindAllConfigKey() { + void testFindAllConfigKey() { MapperResult mapperResult = configInfoMapperByMySql.findAllConfigKey(context); - Assert.assertEquals(mapperResult.getSql(), " SELECT data_id,group_id,app_name FROM ( " - + " SELECT id FROM config_info WHERE tenant_id LIKE ? ORDER BY id LIMIT " + context.getStartRow() + "," - + context.getPageSize() + " )" + " g, config_info t WHERE g.id = t.id "); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId}); + assertEquals(mapperResult.getSql(), + " SELECT data_id,group_id,app_name FROM ( " + " SELECT id FROM config_info WHERE tenant_id LIKE ? ORDER BY id LIMIT " + + context.getStartRow() + "," + context.getPageSize() + " )" + " g, config_info t WHERE g.id = t.id "); + assertArrayEquals(new Object[] {tenantId}, mapperResult.getParamList().toArray()); } @Test - public void testFindAllConfigInfoBaseFetchRows() { + void testFindAllConfigInfoBaseFetchRows() { MapperResult mapperResult = configInfoMapperByMySql.findAllConfigInfoBaseFetchRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT t.id,data_id,group_id,content,md5 FROM ( SELECT id FROM config_info ORDER BY id LIMIT " + context.getStartRow() + "," - + context.getPageSize() + " ) g, config_info t WHERE g.id = t.id "); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); + assertEquals(mapperResult.getSql(), + "SELECT t.id,data_id,group_id,content,md5 FROM ( SELECT id FROM config_info ORDER BY id LIMIT " + context.getStartRow() + + "," + context.getPageSize() + " ) g, config_info t WHERE g.id = t.id "); + assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); } @Test - public void testFindAllConfigInfoFragment() { + void testFindAllConfigInfoFragment() { //with content context.putContextParameter(ContextConstant.NEED_CONTENT, "true"); MapperResult mapperResult = configInfoMapperByMySql.findAllConfigInfoFragment(context); - Assert.assertEquals( - "SELECT id,data_id,group_id,tenant_id,app_name,content,md5,gmt_modified,type,encrypted_data_key " - + "FROM config_info WHERE id > ? ORDER BY id ASC LIMIT " + startRow + "," + pageSize, - mapperResult.getSql()); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {id}); + assertEquals("SELECT id,data_id,group_id,tenant_id,app_name,content,md5,gmt_modified,type,encrypted_data_key " + + "FROM config_info WHERE id > ? ORDER BY id ASC LIMIT " + startRow + "," + pageSize, mapperResult.getSql()); + assertArrayEquals(new Object[] {id}, mapperResult.getParamList().toArray()); context.putContextParameter(ContextConstant.NEED_CONTENT, "false"); MapperResult mapperResult2 = configInfoMapperByMySql.findAllConfigInfoFragment(context); - Assert.assertEquals("SELECT id,data_id,group_id,tenant_id,app_name,md5,gmt_modified,type,encrypted_data_key " - + "FROM config_info WHERE id > ? ORDER BY id ASC LIMIT " + startRow + "," + pageSize, - mapperResult2.getSql()); - Assert.assertArrayEquals(mapperResult2.getParamList().toArray(), new Object[] {id}); + assertEquals("SELECT id,data_id,group_id,tenant_id,app_name,md5,gmt_modified,type,encrypted_data_key " + + "FROM config_info WHERE id > ? ORDER BY id ASC LIMIT " + startRow + "," + pageSize, mapperResult2.getSql()); + assertArrayEquals(new Object[] {id}, mapperResult2.getParamList().toArray()); } @Test - public void testFindChangeConfig() { + void testFindChangeConfig() { MapperResult mapperResult = configInfoMapperByMySql.findChangeConfig(context); - Assert.assertEquals(mapperResult.getSql(), + assertEquals(mapperResult.getSql(), "SELECT id, data_id, group_id, tenant_id, app_name,md5, gmt_modified, encrypted_data_key FROM config_info" + " WHERE gmt_modified >= ? and id > ? order by id limit ? "); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {startTime, lastMaxId, pageSize}); + assertArrayEquals(new Object[] {startTime, lastMaxId, pageSize}, mapperResult.getParamList().toArray()); } @Test - public void testFindChangeConfigCountRows() { + void testFindChangeConfigCountRows() { MapperResult mapperResult = configInfoMapperByMySql.findChangeConfigCountRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT count(*) FROM config_info WHERE 1=1 AND app_name = ? AND gmt_modified >=? AND gmt_modified <=? "); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {appName, startTime, endTime}); + assertEquals("SELECT count(*) FROM config_info WHERE 1=1 AND app_name = ? AND gmt_modified >=? AND gmt_modified <=? ", + mapperResult.getSql()); + assertArrayEquals(new Object[] {appName, startTime, endTime}, mapperResult.getParamList().toArray()); } @Test - public void testFindChangeConfigFetchRows() { + void testFindChangeConfigFetchRows() { Object lastMaxId = 100; context.putWhereParameter(FieldConstant.LAST_MAX_ID, lastMaxId); MapperResult mapperResult = configInfoMapperByMySql.findChangeConfigFetchRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT id,data_id,group_id,tenant_id,app_name,type,md5,gmt_modified FROM config_info " - + "WHERE 1=1 AND tenant_id = ? AND app_name = ? AND gmt_modified >=? AND gmt_modified <=? AND id > " - + lastMaxId + " ORDER BY id ASC LIMIT " + startRow + "," + pageSize); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), - new Object[] {tenantId, appName, startTime, endTime}); + assertEquals(mapperResult.getSql(), "SELECT id,data_id,group_id,tenant_id,app_name,type,md5,gmt_modified FROM config_info " + + "WHERE 1=1 AND tenant_id = ? AND app_name = ? AND gmt_modified >=? AND gmt_modified <=? AND id > " + lastMaxId + + " ORDER BY id ASC LIMIT " + startRow + "," + pageSize); + assertArrayEquals(new Object[] {tenantId, appName, startTime, endTime}, mapperResult.getParamList().toArray()); } @Test - public void testListGroupKeyMd5ByPageFetchRows() { + void testListGroupKeyMd5ByPageFetchRows() { MapperResult mapperResult = configInfoMapperByMySql.listGroupKeyMd5ByPageFetchRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT t.id,data_id,group_id,tenant_id,app_name,md5,type,gmt_modified,encrypted_data_key FROM " - + "( SELECT id FROM config_info ORDER BY id LIMIT 0,5 ) g, config_info t WHERE g.id = t.id"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); + assertEquals(mapperResult.getSql(), "SELECT t.id,data_id,group_id,tenant_id,app_name,md5,type,gmt_modified,encrypted_data_key FROM " + + "( SELECT id FROM config_info ORDER BY id LIMIT 0,5 ) g, config_info t WHERE g.id = t.id"); + assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); } @Test - public void testFindAllConfigInfo4Export() { + void testFindAllConfigInfo4Export() { MapperResult mapperResult = configInfoMapperByMySql.findAllConfigInfo4Export(context); - Assert.assertEquals(mapperResult.getSql(), + assertEquals(mapperResult.getSql(), "SELECT id,data_id,group_id,tenant_id,app_name,content,type,md5,gmt_create,gmt_modified,src_user," + "src_ip,c_desc,c_use,effect,c_schema,encrypted_data_key FROM config_info WHERE id IN (?, ?, ?, ?, ?) "); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), ids.toArray()); + assertArrayEquals(mapperResult.getParamList().toArray(), ids.toArray()); context.putWhereParameter(FieldConstant.IDS, null); mapperResult = configInfoMapperByMySql.findAllConfigInfo4Export(context); - Assert.assertEquals(mapperResult.getSql(), + assertEquals(mapperResult.getSql(), "SELECT id,data_id,group_id,tenant_id,app_name,content,type,md5,gmt_create,gmt_modified,src_user," + "src_ip,c_desc,c_use,effect,c_schema,encrypted_data_key FROM config_info WHERE tenant_id = ? AND app_name= ? "); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName}); + assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray()); } @Test - public void testFindConfigInfoBaseLikeCountRows() { + void testFindConfigInfoBaseLikeCountRows() { MapperResult mapperResult = configInfoMapperByMySql.findConfigInfoBaseLikeCountRows(context); - Assert.assertEquals(mapperResult.getSql(), "SELECT count(*) FROM config_info WHERE 1=1 AND tenant_id='' "); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); + assertEquals("SELECT count(*) FROM config_info WHERE 1=1 AND tenant_id='' ", mapperResult.getSql()); + assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); } @Test - public void testFindConfigInfoBaseLikeFetchRows() { + void testFindConfigInfoBaseLikeFetchRows() { MapperResult mapperResult = configInfoMapperByMySql.findConfigInfoBaseLikeFetchRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT id,data_id,group_id,tenant_id,content FROM config_info WHERE 1=1 AND tenant_id='' LIMIT " - + startRow + "," + pageSize); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); + assertEquals(mapperResult.getSql(), + "SELECT id,data_id,group_id,tenant_id,content FROM config_info WHERE 1=1 AND tenant_id='' LIMIT " + startRow + "," + + pageSize); + assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); } @Test - public void testFindConfigInfo4PageCountRows() { + void testFindConfigInfo4PageCountRows() { MapperResult mapperResult = configInfoMapperByMySql.findConfigInfo4PageCountRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT count(*) FROM config_info WHERE tenant_id=? AND app_name=? "); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName}); + assertEquals("SELECT count(*) FROM config_info WHERE tenant_id=? AND app_name=? ", mapperResult.getSql()); + assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray()); } @Test - public void testFindConfigInfo4PageFetchRows() { + void testFindConfigInfo4PageFetchRows() { MapperResult mapperResult = configInfoMapperByMySql.findConfigInfo4PageFetchRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT id,data_id,group_id,tenant_id,app_name,content,type,encrypted_data_key FROM config_info" - + " WHERE tenant_id=? AND app_name=? LIMIT " + startRow + "," + pageSize); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName}); + assertEquals(mapperResult.getSql(), "SELECT id,data_id,group_id,tenant_id,app_name,content,type,encrypted_data_key FROM config_info" + + " WHERE tenant_id=? AND app_name=? LIMIT " + startRow + "," + pageSize); + assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray()); } @Test - public void testFindConfigInfoBaseByGroupFetchRows() { + void testFindConfigInfoBaseByGroupFetchRows() { context.putWhereParameter(FieldConstant.GROUP_ID, groupId); MapperResult mapperResult = configInfoMapperByMySql.findConfigInfoBaseByGroupFetchRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT id,data_id,group_id,content FROM config_info WHERE group_id=? AND tenant_id=? LIMIT " + startRow - + "," + pageSize); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {groupId, tenantId}); + assertEquals(mapperResult.getSql(), + "SELECT id,data_id,group_id,content FROM config_info WHERE group_id=? AND tenant_id=? LIMIT " + startRow + "," + pageSize); + assertArrayEquals(new Object[] {groupId, tenantId}, mapperResult.getParamList().toArray()); } @Test - public void testFindConfigInfoLike4PageCountRows() { + void testFindConfigInfoLike4PageCountRows() { MapperResult mapperResult = configInfoMapperByMySql.findConfigInfoLike4PageCountRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT count(*) FROM config_info WHERE tenant_id LIKE ? AND app_name = ? "); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName}); + assertEquals("SELECT count(*) FROM config_info WHERE tenant_id LIKE ? AND app_name = ? ", mapperResult.getSql()); + assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray()); } @Test - public void testFindConfigInfoLike4PageFetchRows() { + void testFindConfigInfoLike4PageFetchRows() { MapperResult mapperResult = configInfoMapperByMySql.findConfigInfoLike4PageFetchRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT id,data_id,group_id,tenant_id,app_name,content,encrypted_data_key FROM config_info " - + "WHERE tenant_id LIKE ? AND app_name = ? LIMIT " + startRow + "," + pageSize); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, appName}); + assertEquals(mapperResult.getSql(), "SELECT id,data_id,group_id,tenant_id,app_name,content,encrypted_data_key,type FROM config_info " + + "WHERE tenant_id LIKE ? AND app_name = ? LIMIT " + startRow + "," + pageSize); + assertArrayEquals(new Object[] {tenantId, appName}, mapperResult.getParamList().toArray()); } @Test - public void testFindAllConfigInfoFetchRows() { + void testFindAllConfigInfoFetchRows() { MapperResult mapperResult = configInfoMapperByMySql.findAllConfigInfoFetchRows(context); - Assert.assertEquals(mapperResult.getSql(), + assertEquals(mapperResult.getSql(), "SELECT t.id,data_id,group_id,tenant_id,app_name,content,md5 FROM ( SELECT id FROM config_info " + "WHERE tenant_id LIKE ? ORDER BY id LIMIT ?,? ) g, config_info t WHERE g.id = t.id "); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, startRow, pageSize}); + assertArrayEquals(new Object[] {tenantId, startRow, pageSize}, mapperResult.getParamList().toArray()); } @Test - public void testFindConfigInfosByIds() { + void testFindConfigInfosByIds() { MapperResult mapperResult = configInfoMapperByMySql.findConfigInfosByIds(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT id,data_id,group_id,tenant_id,app_name,content,md5 FROM config_info WHERE id IN (?, ?, ?, ?, ?) "); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), ids.toArray()); + assertEquals("SELECT id,data_id,group_id,tenant_id,app_name,content,md5 FROM config_info WHERE id IN (?, ?, ?, ?, ?) ", + mapperResult.getSql()); + assertArrayEquals(mapperResult.getParamList().toArray(), ids.toArray()); } @Test - public void testRemoveConfigInfoByIdsAtomic() { + void testRemoveConfigInfoByIdsAtomic() { MapperResult mapperResult = configInfoMapperByMySql.removeConfigInfoByIdsAtomic(context); - Assert.assertEquals(mapperResult.getSql(), "DELETE FROM config_info WHERE id IN (?, ?, ?, ?, ?) "); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), ids.toArray()); + assertEquals("DELETE FROM config_info WHERE id IN (?, ?, ?, ?, ?) ", mapperResult.getSql()); + assertArrayEquals(mapperResult.getParamList().toArray(), ids.toArray()); } @Test - public void testGetTableName() { + void testGetTableName() { String sql = configInfoMapperByMySql.getTableName(); - Assert.assertEquals(sql, TableConstant.CONFIG_INFO); + assertEquals(TableConstant.CONFIG_INFO, sql); } @Test - public void testGetDataSource() { + void testGetDataSource() { String sql = configInfoMapperByMySql.getDataSource(); - Assert.assertEquals(sql, DataSourceConstant.MYSQL); + assertEquals(DataSourceConstant.MYSQL, sql); } @Test - public void testUpdateConfigInfoAtomicCas() { + void testUpdateConfigInfoAtomicCas() { String newContent = "new Content"; String newMD5 = "newMD5"; String srcIp = "1.1.1.1"; Object srcUser = "nacos"; - Object time = new Timestamp(System.currentTimeMillis()); Object appNameTmp = "newAppName"; Object desc = "description"; Object use = "use"; @@ -339,7 +326,6 @@ public void testUpdateConfigInfoAtomicCas() { context.putUpdateParameter(FieldConstant.MD5, newMD5); context.putUpdateParameter(FieldConstant.SRC_IP, srcIp); context.putUpdateParameter(FieldConstant.SRC_USER, srcUser); - context.putUpdateParameter(FieldConstant.GMT_MODIFIED, time); context.putUpdateParameter(FieldConstant.APP_NAME, appNameTmp); context.putUpdateParameter(FieldConstant.C_DESC, desc); context.putUpdateParameter(FieldConstant.C_USE, use); @@ -357,12 +343,12 @@ public void testUpdateConfigInfoAtomicCas() { context.putWhereParameter(FieldConstant.MD5, md5); MapperResult mapperResult = configInfoMapperByMySql.updateConfigInfoAtomicCas(context); - Assert.assertEquals(mapperResult.getSql(), "UPDATE config_info SET " - + "content=?, md5 = ?, src_ip=?,src_user=?,gmt_modified=?, app_name=?,c_desc=?," - + "c_use=?,effect=?,type=?,c_schema=?,encrypted_data_key=? " - + "WHERE data_id=? AND group_id=? AND tenant_id=? AND (md5=? OR md5 IS NULL OR md5='')"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), - new Object[] {newContent, newMD5, srcIp, srcUser, time, appNameTmp, desc, use, effect, type, schema, - encryptedDataKey, dataId, group, tenantId, md5}); + assertEquals(mapperResult.getSql(), + "UPDATE config_info SET " + "content=?, md5=?, src_ip=?, src_user=?, gmt_modified=NOW(3)," + + " app_name=?, c_desc=?, c_use=?, effect=?, type=?, c_schema=?, encrypted_data_key=? " + + "WHERE data_id=? AND group_id=? AND tenant_id=? AND (md5=? OR md5 IS NULL OR md5='')"); + assertArrayEquals( + new Object[]{newContent, newMD5, srcIp, srcUser, appNameTmp, desc, use, effect, type, schema, + encryptedDataKey, dataId, group, tenantId, md5}, mapperResult.getParamList().toArray()); } } diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoTagMapperByMySqlTest.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoTagMapperByMySqlTest.java index 7632785b5d4..f2a25b21ea6 100644 --- a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoTagMapperByMySqlTest.java +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigInfoTagMapperByMySqlTest.java @@ -22,16 +22,16 @@ import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.sql.Timestamp; import java.util.List; -public class ConfigInfoTagMapperByMySqlTest { - - private ConfigInfoTagMapperByMySql configInfoTagMapperByMySql; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ConfigInfoTagMapperByMySqlTest { private final Object[] emptyObjs = new Object[] {}; @@ -53,8 +53,10 @@ public class ConfigInfoTagMapperByMySqlTest { MapperContext context; - @Before - public void setUp() throws Exception { + private ConfigInfoTagMapperByMySql configInfoTagMapperByMySql; + + @BeforeEach + void setUp() throws Exception { configInfoTagMapperByMySql = new ConfigInfoTagMapperByMySql(); context = new MapperContext(startRow, pageSize); @@ -68,7 +70,7 @@ public void setUp() throws Exception { } @Test - public void testUpdateConfigInfo4TagCas() { + void testUpdateConfigInfo4TagCas() { String newContent = "new Content"; String newMD5 = "newMD5"; String srcIp = "1.1.1.1"; @@ -106,34 +108,31 @@ public void testUpdateConfigInfo4TagCas() { MapperResult mapperResult = configInfoTagMapperByMySql.updateConfigInfo4TagCas(context); - Assert.assertEquals(mapperResult.getSql(), - "UPDATE config_info_tag SET content = ?, md5 = ?, src_ip = ?,src_user = ?,gmt_modified = ?," - + "app_name = ? WHERE data_id = ? AND group_id = ? AND tenant_id = ? AND tag_id = ? AND " - + "(md5 = ? OR md5 IS NULL OR md5 = '')"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), - new Object[] {newContent, newMD5, srcIp, srcUser, time, appNameTmp, dataId, group, tenantId, tagId, - md5}); + assertEquals(mapperResult.getSql(), "UPDATE config_info_tag SET content = ?, md5 = ?, src_ip = ?,src_user = ?,gmt_modified = ?," + + "app_name = ? WHERE data_id = ? AND group_id = ? AND tenant_id = ? AND tag_id = ? AND " + + "(md5 = ? OR md5 IS NULL OR md5 = '')"); + assertArrayEquals(new Object[] {newContent, newMD5, srcIp, srcUser, time, appNameTmp, dataId, group, tenantId, tagId, md5}, + mapperResult.getParamList().toArray()); } @Test - public void testFindAllConfigInfoTagForDumpAllFetchRows() { + void testFindAllConfigInfoTagForDumpAllFetchRows() { MapperResult mapperResult = configInfoTagMapperByMySql.findAllConfigInfoTagForDumpAllFetchRows(context); - Assert.assertEquals(mapperResult.getSql(), - " SELECT t.id,data_id,group_id,tenant_id,tag_id,app_name,content,md5,gmt_modified FROM ( " - + "SELECT id FROM config_info_tag ORDER BY id LIMIT " + startRow + "," + pageSize - + " ) g, config_info_tag t WHERE g.id = t.id "); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); + assertEquals(mapperResult.getSql(), " SELECT t.id,data_id,group_id,tenant_id,tag_id,app_name,content,md5,gmt_modified FROM ( " + + "SELECT id FROM config_info_tag ORDER BY id LIMIT " + startRow + "," + pageSize + + " ) g, config_info_tag t WHERE g.id = t.id "); + assertArrayEquals(mapperResult.getParamList().toArray(), emptyObjs); } @Test - public void testGetTableName() { + void testGetTableName() { String tableName = configInfoTagMapperByMySql.getTableName(); - Assert.assertEquals(tableName, TableConstant.CONFIG_INFO_TAG); + assertEquals(TableConstant.CONFIG_INFO_TAG, tableName); } @Test - public void testGetDataSource() { + void testGetDataSource() { String dataSource = configInfoTagMapperByMySql.getDataSource(); - Assert.assertEquals(dataSource, DataSourceConstant.MYSQL); + assertEquals(DataSourceConstant.MYSQL, dataSource); } } diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigTagsRelationMapperByMySqlTest.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigTagsRelationMapperByMySqlTest.java index 78899040a95..e9ab1aa83f0 100644 --- a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigTagsRelationMapperByMySqlTest.java +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/ConfigTagsRelationMapperByMySqlTest.java @@ -22,16 +22,16 @@ import com.alibaba.nacos.plugin.datasource.constants.TableConstant; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; -public class ConfigTagsRelationMapperByMySqlTest { - - private ConfigTagsRelationMapperByMySql configTagsRelationMapperByMySql; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ConfigTagsRelationMapperByMySqlTest { int startRow = 0; @@ -43,8 +43,10 @@ public class ConfigTagsRelationMapperByMySqlTest { MapperContext context; - @Before - public void setUp() throws Exception { + private ConfigTagsRelationMapperByMySql configTagsRelationMapperByMySql; + + @BeforeEach + void setUp() throws Exception { configTagsRelationMapperByMySql = new ConfigTagsRelationMapperByMySql(); context = new MapperContext(startRow, pageSize); context.putWhereParameter(FieldConstant.TENANT_ID, tenantId); @@ -52,59 +54,55 @@ public void setUp() throws Exception { } @Test - public void testFindConfigInfoLike4PageCountRows() { + void testFindConfigInfoLike4PageCountRows() { MapperResult mapperResult = configTagsRelationMapperByMySql.findConfigInfoLike4PageCountRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT count(*) FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id WHERE " - + "a.tenant_id LIKE ? AND b.tag_name IN (?, ?, ?, ?, ?) "); + assertEquals(mapperResult.getSql(), "SELECT count(*) FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id WHERE " + + "a.tenant_id LIKE ? AND b.tag_name IN (?, ?, ?, ?, ?) "); List list = CollectionUtils.list(tenantId); list.addAll(Arrays.asList(tagArr)); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); + assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); } @Test - public void testFindConfigInfo4PageCountRows() { + void testFindConfigInfo4PageCountRows() { MapperResult mapperResult = configTagsRelationMapperByMySql.findConfigInfo4PageCountRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT count(*) FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id " - + "WHERE a.tenant_id=? AND b.tag_name IN (?, ?, ?, ?, ?) "); + assertEquals(mapperResult.getSql(), "SELECT count(*) FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id " + + "WHERE a.tenant_id=? AND b.tag_name IN (?, ?, ?, ?, ?) "); List list = CollectionUtils.list(tenantId); list.addAll(Arrays.asList(tagArr)); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); + assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); } @Test - public void testFindConfigInfo4PageFetchRows() { + void testFindConfigInfo4PageFetchRows() { context.putWhereParameter(FieldConstant.DATA_ID, "dataID1"); context.putWhereParameter(FieldConstant.GROUP_ID, "groupID1"); context.putWhereParameter(FieldConstant.APP_NAME, "AppName1"); context.putWhereParameter(FieldConstant.CONTENT, "Content1"); MapperResult mapperResult = configTagsRelationMapperByMySql.findConfigInfo4PageFetchRows(context); - Assert.assertEquals( - "SELECT a.id,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content FROM config_info " - + "a LEFT JOIN config_tags_relation b ON a.id=b.id " - + "WHERE a.tenant_id=? AND a.data_id=? AND a.group_id=? AND a.app_name=? AND a.content LIKE ? " - + " AND b.tag_name IN (?, ?, ?, ?, ?) LIMIT " - + startRow + "," + pageSize, mapperResult.getSql()); + assertEquals("SELECT a.id,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content FROM config_info " + + "a LEFT JOIN config_tags_relation b ON a.id=b.id " + + "WHERE a.tenant_id=? AND a.data_id=? AND a.group_id=? AND a.app_name=? AND a.content LIKE ? " + + " AND b.tag_name IN (?, ?, ?, ?, ?) LIMIT " + startRow + "," + pageSize, mapperResult.getSql()); List list = CollectionUtils.list(tenantId); list.add("dataID1"); list.add("groupID1"); list.add("AppName1"); list.add("Content1"); list.addAll(Arrays.asList(tagArr)); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); + assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); } @Test - public void testFindConfigInfoLike4PageCountRowss() { + void testFindConfigInfoLike4PageCountRowss() { context.putWhereParameter(FieldConstant.DATA_ID, "dataID1"); context.putWhereParameter(FieldConstant.GROUP_ID, "groupID1"); context.putWhereParameter(FieldConstant.APP_NAME, "AppName1"); context.putWhereParameter(FieldConstant.CONTENT, "Content1"); MapperResult mapperResult = configTagsRelationMapperByMySql.findConfigInfoLike4PageCountRows(context); - Assert.assertEquals("SELECT count(*) FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id " - + "WHERE a.tenant_id LIKE ? AND a.data_id LIKE ? AND a.group_id LIKE ? AND a.app_name = ? " + assertEquals("SELECT count(*) FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id " + + "WHERE a.tenant_id LIKE ? AND a.data_id LIKE ? AND a.group_id LIKE ? AND a.app_name = ? " + "AND a.content LIKE ? AND b.tag_name IN (?, ?, ?, ?, ?) ", mapperResult.getSql()); List list = CollectionUtils.list(tenantId); list.add("dataID1"); @@ -112,39 +110,38 @@ public void testFindConfigInfoLike4PageCountRowss() { list.add("AppName1"); list.add("Content1"); list.addAll(Arrays.asList(tagArr)); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); + assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); } @Test - public void tsetFindConfigInfoLike4PageFetchRows() { + void tsetFindConfigInfoLike4PageFetchRows() { context.putWhereParameter(FieldConstant.DATA_ID, "dataID1"); context.putWhereParameter(FieldConstant.GROUP_ID, "groupID1"); context.putWhereParameter(FieldConstant.APP_NAME, "AppName1"); context.putWhereParameter(FieldConstant.CONTENT, "Content1"); MapperResult mapperResult = configTagsRelationMapperByMySql.findConfigInfoLike4PageFetchRows(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT a.id,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content FROM config_info a LEFT JOIN" - + " config_tags_relation b ON a.id=b.id WHERE a.tenant_id LIKE ? AND a.data_id LIKE ? " - + "AND a.group_id LIKE ? AND a.app_name = ? AND a.content LIKE ? AND b.tag_name IN (?, ?, ?, ?, ?) LIMIT " - + startRow + "," + pageSize); + assertEquals(mapperResult.getSql(), "SELECT a.id,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content,a.type FROM config_info a LEFT JOIN" + + " config_tags_relation b ON a.id=b.id WHERE a.tenant_id LIKE ? AND a.data_id LIKE ? " + + "AND a.group_id LIKE ? AND a.app_name = ? AND a.content LIKE ? AND b.tag_name IN (?, ?, ?, ?, ?) LIMIT " + startRow + + "," + pageSize); List list = CollectionUtils.list(tenantId); list.add("dataID1"); list.add("groupID1"); list.add("AppName1"); list.add("Content1"); list.addAll(Arrays.asList(tagArr)); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); + assertArrayEquals(mapperResult.getParamList().toArray(), list.toArray()); } @Test - public void testGetTableName() { + void testGetTableName() { String tableName = configTagsRelationMapperByMySql.getTableName(); - Assert.assertEquals(tableName, TableConstant.CONFIG_TAGS_RELATION); + assertEquals(TableConstant.CONFIG_TAGS_RELATION, tableName); } @Test - public void testGetDataSource() { + void testGetDataSource() { String dataSource = configTagsRelationMapperByMySql.getDataSource(); - Assert.assertEquals(dataSource, DataSourceConstant.MYSQL); + assertEquals(DataSourceConstant.MYSQL, dataSource); } } diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/GroupCapacityMapperByMysqlTest.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/GroupCapacityMapperByMysqlTest.java index 8f84bde5325..fed0ce32ed8 100644 --- a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/GroupCapacityMapperByMysqlTest.java +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/GroupCapacityMapperByMysqlTest.java @@ -21,15 +21,15 @@ import com.alibaba.nacos.plugin.datasource.constants.TableConstant; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.sql.Timestamp; -public class GroupCapacityMapperByMysqlTest { - - private GroupCapacityMapperByMysql groupCapacityMapperByMysql; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class GroupCapacityMapperByMysqlTest { private final Object[] emptyObjs = new Object[] {}; @@ -45,8 +45,10 @@ public class GroupCapacityMapperByMysqlTest { MapperContext context; - @Before - public void setUp() throws Exception { + private GroupCapacityMapperByMysql groupCapacityMapperByMysql; + + @BeforeEach + void setUp() throws Exception { groupCapacityMapperByMysql = new GroupCapacityMapperByMysql(); context = new MapperContext(startRow, pageSize); context.putUpdateParameter(FieldConstant.GMT_MODIFIED, modified); @@ -56,19 +58,19 @@ public void setUp() throws Exception { } @Test - public void testGetTableName() { + void testGetTableName() { String tableName = groupCapacityMapperByMysql.getTableName(); - Assert.assertEquals(tableName, TableConstant.GROUP_CAPACITY); + assertEquals(TableConstant.GROUP_CAPACITY, tableName); } @Test - public void testGetDataSource() { + void testGetDataSource() { String dataSource = groupCapacityMapperByMysql.getDataSource(); - Assert.assertEquals(dataSource, DataSourceConstant.MYSQL); + assertEquals(DataSourceConstant.MYSQL, dataSource); } @Test - public void testInsertIntoSelect() { + void testInsertIntoSelect() { Object group = "group"; Object quota = "quota"; Object maxAggrSize = 10; @@ -80,21 +82,21 @@ public void testInsertIntoSelect() { context.putUpdateParameter(FieldConstant.MAX_SIZE, maxSize); context.putUpdateParameter(FieldConstant.MAX_AGGR_SIZE, maxAggrSize); context.putUpdateParameter(FieldConstant.MAX_AGGR_COUNT, maxAggrCount); - + context.putUpdateParameter(FieldConstant.GMT_CREATE, createTime); context.putUpdateParameter(FieldConstant.GMT_MODIFIED, modified); MapperResult mapperResult = groupCapacityMapperByMysql.insertIntoSelect(context); - Assert.assertEquals(mapperResult.getSql(), + assertEquals(mapperResult.getSql(), "INSERT INTO group_capacity (group_id, quota, usage, max_size, max_aggr_count, max_aggr_size,gmt_create," + " gmt_modified) SELECT ?, ?, count(*), ?, ?, ?, ?, ? FROM config_info"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), - new Object[] {group, quota, maxSize, maxAggrCount, maxAggrSize, createTime, modified}); + assertArrayEquals(new Object[] {group, quota, maxSize, maxAggrCount, maxAggrSize, createTime, modified}, + mapperResult.getParamList().toArray()); } @Test - public void testInsertIntoSelectByWhere() { + void testInsertIntoSelectByWhere() { Object group = "group"; Object quota = "quota"; Object maxAggrSize = 10; @@ -112,72 +114,71 @@ public void testInsertIntoSelectByWhere() { context.putUpdateParameter(FieldConstant.GMT_MODIFIED, modified); MapperResult mapperResult = groupCapacityMapperByMysql.insertIntoSelectByWhere(context); - Assert.assertEquals(mapperResult.getSql(), + assertEquals(mapperResult.getSql(), "INSERT INTO group_capacity (group_id, quota, usage, max_size, max_aggr_count, max_aggr_size, gmt_create," + " gmt_modified) SELECT ?, ?, count(*), ?, ?, ?, ?, ? FROM config_info WHERE group_id=? AND tenant_id = ''"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), - new Object[] {group, quota, maxSize, maxAggrCount, maxAggrSize, createTime, modified, group}); + assertArrayEquals(new Object[] {group, quota, maxSize, maxAggrCount, maxAggrSize, createTime, modified, group}, + mapperResult.getParamList().toArray()); } @Test - public void testIncrementUsageByWhereQuotaEqualZero() { + void testIncrementUsageByWhereQuotaEqualZero() { Object usage = 1; context.putWhereParameter(FieldConstant.USAGE, usage); MapperResult mapperResult = groupCapacityMapperByMysql.incrementUsageByWhereQuotaEqualZero(context); - Assert.assertEquals(mapperResult.getSql(), - "UPDATE group_capacity SET usage = usage + 1, gmt_modified = ? WHERE group_id = ? AND usage < ? AND quota = 0"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, groupId, usage}); + assertEquals("UPDATE group_capacity SET usage = usage + 1, gmt_modified = ? WHERE group_id = ? AND usage < ? AND quota = 0", + mapperResult.getSql()); + assertArrayEquals(new Object[] {modified, groupId, usage}, mapperResult.getParamList().toArray()); } @Test - public void testIncrementUsageByWhereQuotaNotEqualZero() { + void testIncrementUsageByWhereQuotaNotEqualZero() { MapperResult mapperResult = groupCapacityMapperByMysql.incrementUsageByWhereQuotaNotEqualZero(context); - Assert.assertEquals(mapperResult.getSql(), - "UPDATE group_capacity SET usage = usage + 1, gmt_modified = ? WHERE group_id = ? AND usage < quota AND quota != 0"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, groupId}); + assertEquals("UPDATE group_capacity SET usage = usage + 1, gmt_modified = ? WHERE group_id = ? AND usage < quota AND quota != 0", + mapperResult.getSql()); + assertArrayEquals(new Object[] {modified, groupId}, mapperResult.getParamList().toArray()); } @Test - public void testIncrementUsageByWhere() { + void testIncrementUsageByWhere() { MapperResult mapperResult = groupCapacityMapperByMysql.incrementUsageByWhere(context); - Assert.assertEquals(mapperResult.getSql(), - "UPDATE group_capacity SET usage = usage + 1, gmt_modified = ? WHERE group_id = ?"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, groupId}); + assertEquals("UPDATE group_capacity SET usage = usage + 1, gmt_modified = ? WHERE group_id = ?", mapperResult.getSql()); + assertArrayEquals(new Object[] {modified, groupId}, mapperResult.getParamList().toArray()); } @Test - public void testDecrementUsageByWhere() { + void testDecrementUsageByWhere() { MapperResult mapperResult = groupCapacityMapperByMysql.decrementUsageByWhere(context); - Assert.assertEquals(mapperResult.getSql(), - "UPDATE group_capacity SET usage = usage - 1, gmt_modified = ? WHERE group_id = ? AND usage > 0"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, groupId}); + assertEquals("UPDATE group_capacity SET usage = usage - 1, gmt_modified = ? WHERE group_id = ? AND usage > 0", + mapperResult.getSql()); + assertArrayEquals(new Object[] {modified, groupId}, mapperResult.getParamList().toArray()); } @Test - public void testUpdateUsage() { + void testUpdateUsage() { MapperResult mapperResult = groupCapacityMapperByMysql.updateUsage(context); - Assert.assertEquals(mapperResult.getSql(), - "UPDATE group_capacity SET usage = (SELECT count(*) FROM config_info), gmt_modified = ? WHERE group_id = ?"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, groupId}); + assertEquals("UPDATE group_capacity SET usage = (SELECT count(*) FROM config_info), gmt_modified = ? WHERE group_id = ?", + mapperResult.getSql()); + assertArrayEquals(new Object[] {modified, groupId}, mapperResult.getParamList().toArray()); } @Test - public void testUpdateUsageByWhere() { + void testUpdateUsageByWhere() { MapperResult mapperResult = groupCapacityMapperByMysql.updateUsageByWhere(context); - Assert.assertEquals(mapperResult.getSql(), + assertEquals(mapperResult.getSql(), "UPDATE group_capacity SET usage = (SELECT count(*) FROM config_info WHERE group_id=? AND tenant_id = '')," + " gmt_modified = ? WHERE group_id= ?"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {groupId, modified, groupId}); + assertArrayEquals(new Object[] {groupId, modified, groupId}, mapperResult.getParamList().toArray()); } @Test - public void testSelectGroupInfoBySize() { + void testSelectGroupInfoBySize() { Object id = 1; context.putWhereParameter(FieldConstant.ID, id); MapperResult mapperResult = groupCapacityMapperByMysql.selectGroupInfoBySize(context); - Assert.assertEquals(mapperResult.getSql(), "SELECT id, group_id FROM group_capacity WHERE id > ? LIMIT ?"); + assertEquals("SELECT id, group_id FROM group_capacity WHERE id > ? LIMIT ?", mapperResult.getSql()); context.putWhereParameter(FieldConstant.GMT_CREATE, createTime); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {id, pageSize}); + assertArrayEquals(new Object[] {id, pageSize}, mapperResult.getParamList().toArray()); } } diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/HistoryConfigInfoMapperByMySqlTest.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/HistoryConfigInfoMapperByMySqlTest.java index ef4a5cffcfd..c69efda736f 100644 --- a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/HistoryConfigInfoMapperByMySqlTest.java +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/HistoryConfigInfoMapperByMySqlTest.java @@ -21,15 +21,15 @@ import com.alibaba.nacos.plugin.datasource.constants.TableConstant; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.sql.Timestamp; -public class HistoryConfigInfoMapperByMySqlTest { - - private HistoryConfigInfoMapperByMySql historyConfigInfoMapperByMySql; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class HistoryConfigInfoMapperByMySqlTest { int startRow = 0; @@ -45,8 +45,10 @@ public class HistoryConfigInfoMapperByMySqlTest { MapperContext context; - @Before - public void setUp() throws Exception { + private HistoryConfigInfoMapperByMySql historyConfigInfoMapperByMySql; + + @BeforeEach + void setUp() throws Exception { historyConfigInfoMapperByMySql = new HistoryConfigInfoMapperByMySql(); context = new MapperContext(startRow, pageSize); context.putWhereParameter(FieldConstant.START_TIME, startTime); @@ -57,31 +59,30 @@ public void setUp() throws Exception { } @Test - public void testRemoveConfigHistory() { + void testRemoveConfigHistory() { MapperResult mapperResult = historyConfigInfoMapperByMySql.removeConfigHistory(context); - Assert.assertEquals(mapperResult.getSql(), "DELETE FROM his_config_info WHERE gmt_modified < ? LIMIT ?"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {startTime, limitSize}); + assertEquals("DELETE FROM his_config_info WHERE gmt_modified < ? LIMIT ?", mapperResult.getSql()); + assertArrayEquals(new Object[] {startTime, limitSize}, mapperResult.getParamList().toArray()); } @Test - public void testFindConfigHistoryCountByTime() { + void testFindConfigHistoryCountByTime() { MapperResult mapperResult = historyConfigInfoMapperByMySql.findConfigHistoryCountByTime(context); - Assert.assertEquals(mapperResult.getSql(), "SELECT count(*) FROM his_config_info WHERE gmt_modified < ?"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {startTime}); + assertEquals("SELECT count(*) FROM his_config_info WHERE gmt_modified < ?", mapperResult.getSql()); + assertArrayEquals(new Object[] {startTime}, mapperResult.getParamList().toArray()); } @Test - public void testFindDeletedConfig() { + void testFindDeletedConfig() { MapperResult mapperResult = historyConfigInfoMapperByMySql.findDeletedConfig(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT data_id, group_id, tenant_id,gmt_modified,nid FROM his_config_info " - + "WHERE op_type = 'D' AND gmt_modified >= ? and nid > ? order by nid limit ? "); + assertEquals(mapperResult.getSql(), "SELECT data_id, group_id, tenant_id,gmt_modified,nid FROM his_config_info " + + "WHERE op_type = 'D' AND gmt_modified >= ? and nid > ? order by nid limit ? "); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {startTime, lastMaxId, pageSize}); + assertArrayEquals(new Object[] {startTime, lastMaxId, pageSize}, mapperResult.getParamList().toArray()); } @Test - public void testFindConfigHistoryFetchRows() { + void testFindConfigHistoryFetchRows() { Object dataId = "dataId"; Object groupId = "groupId"; Object tenantId = "tenantId"; @@ -91,32 +92,31 @@ public void testFindConfigHistoryFetchRows() { context.putWhereParameter(FieldConstant.TENANT_ID, tenantId); context.putWhereParameter(FieldConstant.DATA_ID, dataId); MapperResult mapperResult = historyConfigInfoMapperByMySql.findConfigHistoryFetchRows(context); - Assert.assertEquals(mapperResult.getSql(), + assertEquals(mapperResult.getSql(), "SELECT nid,data_id,group_id,tenant_id,app_name,src_ip,src_user,op_type,gmt_create,gmt_modified FROM his_config_info " + "WHERE data_id = ? AND group_id = ? AND tenant_id = ? ORDER BY nid DESC"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {dataId, groupId, tenantId}); + assertArrayEquals(new Object[] {dataId, groupId, tenantId}, mapperResult.getParamList().toArray()); } @Test - public void testDetailPreviousConfigHistory() { + void testDetailPreviousConfigHistory() { Object id = "1"; context.putWhereParameter(FieldConstant.ID, id); MapperResult mapperResult = historyConfigInfoMapperByMySql.detailPreviousConfigHistory(context); - Assert.assertEquals(mapperResult.getSql(), - "SELECT nid,data_id,group_id,tenant_id,app_name,content,md5,src_user,src_ip,op_type,gmt_create," - + "gmt_modified,encrypted_data_key FROM his_config_info WHERE nid = (SELECT max(nid) FROM his_config_info WHERE id = ?)"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {id}); + assertEquals(mapperResult.getSql(), "SELECT nid,data_id,group_id,tenant_id,app_name,content,md5,src_user,src_ip,op_type,gmt_create," + + "gmt_modified,encrypted_data_key FROM his_config_info WHERE nid = (SELECT max(nid) FROM his_config_info WHERE id = ?)"); + assertArrayEquals(new Object[] {id}, mapperResult.getParamList().toArray()); } @Test - public void testGetTableName() { + void testGetTableName() { String tableName = historyConfigInfoMapperByMySql.getTableName(); - Assert.assertEquals(tableName, TableConstant.HIS_CONFIG_INFO); + assertEquals(TableConstant.HIS_CONFIG_INFO, tableName); } @Test - public void testGetDataSource() { + void testGetDataSource() { String dataSource = historyConfigInfoMapperByMySql.getDataSource(); - Assert.assertEquals(dataSource, DataSourceConstant.MYSQL); + assertEquals(DataSourceConstant.MYSQL, dataSource); } } diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/TenantCapacityMapperByMySqlTest.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/TenantCapacityMapperByMySqlTest.java index 7f41e483e29..2d5f2a6918a 100644 --- a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/TenantCapacityMapperByMySqlTest.java +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/TenantCapacityMapperByMySqlTest.java @@ -21,28 +21,30 @@ import com.alibaba.nacos.plugin.datasource.constants.TableConstant; import com.alibaba.nacos.plugin.datasource.model.MapperContext; import com.alibaba.nacos.plugin.datasource.model.MapperResult; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.sql.Timestamp; -public class TenantCapacityMapperByMySqlTest { - - private TenantCapacityMapperByMySql tenantCapacityMapperByMySql; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class TenantCapacityMapperByMySqlTest { String tenantId = "tenantId"; MapperContext context; + private TenantCapacityMapperByMySql tenantCapacityMapperByMySql; + private Object modified = new Timestamp(System.currentTimeMillis()); private Object oldModified = new Timestamp(System.currentTimeMillis()); private Object usage = 1; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { tenantCapacityMapperByMySql = new TenantCapacityMapperByMySql(); context = new MapperContext(); context.putUpdateParameter(FieldConstant.GMT_MODIFIED, modified); @@ -53,74 +55,70 @@ public void setUp() throws Exception { } @Test - public void testGetTableName() { + void testGetTableName() { String tableName = tenantCapacityMapperByMySql.getTableName(); - Assert.assertEquals(tableName, TableConstant.TENANT_CAPACITY); + assertEquals(TableConstant.TENANT_CAPACITY, tableName); } @Test - public void testGetDataSource() { + void testGetDataSource() { String dataSource = tenantCapacityMapperByMySql.getDataSource(); - Assert.assertEquals(dataSource, DataSourceConstant.MYSQL); + assertEquals(DataSourceConstant.MYSQL, dataSource); } @Test - public void testIncrementUsageWithDefaultQuotaLimit() { + void testIncrementUsageWithDefaultQuotaLimit() { MapperResult mapperResult = tenantCapacityMapperByMySql.incrementUsageWithDefaultQuotaLimit(context); - Assert.assertEquals(mapperResult.getSql(), - "UPDATE tenant_capacity SET usage = usage + 1, gmt_modified = ? WHERE tenant_id = ? AND usage <" - + " ? AND quota = 0"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, tenantId, usage}); + assertEquals(mapperResult.getSql(), + "UPDATE tenant_capacity SET usage = usage + 1, gmt_modified = ? WHERE tenant_id = ? AND usage <" + " ? AND quota = 0"); + assertArrayEquals(new Object[] {modified, tenantId, usage}, mapperResult.getParamList().toArray()); } @Test - public void testIncrementUsageWithQuotaLimit() { + void testIncrementUsageWithQuotaLimit() { MapperResult mapperResult = tenantCapacityMapperByMySql.incrementUsageWithQuotaLimit(context); - Assert.assertEquals(mapperResult.getSql(), - "UPDATE tenant_capacity SET usage = usage + 1, gmt_modified = ? WHERE tenant_id = ? AND usage < " - + "quota AND quota != 0"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, tenantId}); + assertEquals(mapperResult.getSql(), + "UPDATE tenant_capacity SET usage = usage + 1, gmt_modified = ? WHERE tenant_id = ? AND usage < " + "quota AND quota != 0"); + assertArrayEquals(new Object[] {modified, tenantId}, mapperResult.getParamList().toArray()); } @Test - public void testIncrementUsage() { + void testIncrementUsage() { MapperResult mapperResult = tenantCapacityMapperByMySql.incrementUsage(context); - Assert.assertEquals(mapperResult.getSql(), - "UPDATE tenant_capacity SET usage = usage + 1, gmt_modified = ? WHERE tenant_id = ?"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, tenantId}); + assertEquals("UPDATE tenant_capacity SET usage = usage + 1, gmt_modified = ? WHERE tenant_id = ?", mapperResult.getSql()); + assertArrayEquals(new Object[] {modified, tenantId}, mapperResult.getParamList().toArray()); } @Test - public void testDecrementUsage() { + void testDecrementUsage() { MapperResult mapperResult = tenantCapacityMapperByMySql.decrementUsage(context); - Assert.assertEquals(mapperResult.getSql(), - "UPDATE tenant_capacity SET usage = usage - 1, gmt_modified = ? WHERE tenant_id = ? AND usage > 0"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {modified, tenantId}); + assertEquals("UPDATE tenant_capacity SET usage = usage - 1, gmt_modified = ? WHERE tenant_id = ? AND usage > 0", + mapperResult.getSql()); + assertArrayEquals(new Object[] {modified, tenantId}, mapperResult.getParamList().toArray()); } @Test - public void testCorrectUsage() { + void testCorrectUsage() { MapperResult mapperResult = tenantCapacityMapperByMySql.correctUsage(context); - Assert.assertEquals(mapperResult.getSql(), - "UPDATE tenant_capacity SET usage = (SELECT count(*) FROM config_info WHERE tenant_id = ?), " - + "gmt_modified = ? WHERE tenant_id = ?"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {tenantId, modified, tenantId}); + assertEquals(mapperResult.getSql(), "UPDATE tenant_capacity SET usage = (SELECT count(*) FROM config_info WHERE tenant_id = ?), " + + "gmt_modified = ? WHERE tenant_id = ?"); + assertArrayEquals(new Object[] {tenantId, modified, tenantId}, mapperResult.getParamList().toArray()); } @Test - public void testGetCapacityList4CorrectUsage() { + void testGetCapacityList4CorrectUsage() { Object id = 1; Object limit = 10; context.putWhereParameter(FieldConstant.ID, id); context.putWhereParameter(FieldConstant.LIMIT_SIZE, limit); MapperResult mapperResult = tenantCapacityMapperByMySql.getCapacityList4CorrectUsage(context); - Assert.assertEquals(mapperResult.getSql(), "SELECT id, tenant_id FROM tenant_capacity WHERE id>? LIMIT ?"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), new Object[] {id, limit}); + assertEquals("SELECT id, tenant_id FROM tenant_capacity WHERE id>? LIMIT ?", mapperResult.getSql()); + assertArrayEquals(new Object[] {id, limit}, mapperResult.getParamList().toArray()); } @Test - public void testInsertTenantCapacity() { + void testInsertTenantCapacity() { Object group = "group"; Object quota = "quota"; Object maxAggrSize = 10; @@ -141,10 +139,10 @@ public void testInsertTenantCapacity() { context.putWhereParameter(FieldConstant.TENANT_ID, tenantId); MapperResult mapperResult = tenantCapacityMapperByMySql.insertTenantCapacity(context); - Assert.assertEquals(mapperResult.getSql(), + assertEquals(mapperResult.getSql(), "INSERT INTO tenant_capacity (tenant_id, quota, usage, max_size, max_aggr_count, max_aggr_size, " + "gmt_create, gmt_modified) SELECT ?, ?, count(*), ?, ?, ?, ?, ? FROM config_info WHERE tenant_id=?;"); - Assert.assertArrayEquals(mapperResult.getParamList().toArray(), - new Object[] {tenantId, quota, maxSize, maxAggrCount, maxAggrSize, createTime, modified, tenantId}); + assertArrayEquals(new Object[] {tenantId, quota, maxSize, maxAggrCount, maxAggrSize, createTime, modified, tenantId}, + mapperResult.getParamList().toArray()); } } diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/TenantInfoMapperByMySqlTest.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/TenantInfoMapperByMySqlTest.java index 56654593174..b54722966b5 100644 --- a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/TenantInfoMapperByMySqlTest.java +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/TenantInfoMapperByMySqlTest.java @@ -18,28 +18,29 @@ import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; import com.alibaba.nacos.plugin.datasource.constants.TableConstant; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class TenantInfoMapperByMySqlTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class TenantInfoMapperByMySqlTest { private TenantInfoMapperByMySql tenantInfoMapperByMySql; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { tenantInfoMapperByMySql = new TenantInfoMapperByMySql(); } @Test - public void testGetTableName() { + void testGetTableName() { String tableName = tenantInfoMapperByMySql.getTableName(); - Assert.assertEquals(tableName, TableConstant.TENANT_INFO); + assertEquals(TableConstant.TENANT_INFO, tableName); } @Test - public void testGetDataSource() { + void testGetDataSource() { String dataSource = tenantInfoMapperByMySql.getDataSource(); - Assert.assertEquals(dataSource, DataSourceConstant.MYSQL); + assertEquals(DataSourceConstant.MYSQL, dataSource); } -} \ No newline at end of file +} diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/mapper/AbstractMapperTest.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/mapper/AbstractMapperTest.java index 3f88eb05769..899cb01adf1 100644 --- a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/mapper/AbstractMapperTest.java +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/mapper/AbstractMapperTest.java @@ -16,67 +16,85 @@ package com.alibaba.nacos.plugin.datasource.mapper; -import com.alibaba.nacos.plugin.datasource.impl.mysql.TenantInfoMapperByMySql; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; +import com.alibaba.nacos.plugin.datasource.constants.TableConstant; +import com.alibaba.nacos.plugin.datasource.enums.mysql.TrustedMysqlFunctionEnum; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Arrays; -public class AbstractMapperTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class AbstractMapperTest { private AbstractMapper abstractMapper; - @Before - public void setUp() throws Exception { - abstractMapper = new TenantInfoMapperByMySql(); + @BeforeEach + void setUp() throws Exception { + abstractMapper = new AbstractMapper() { + @Override + public String getTableName() { + return TableConstant.TENANT_INFO; + } + + @Override + public String getDataSource() { + return DataSourceConstant.MYSQL; + } + + @Override + public String getFunction(String functionName) { + return TrustedMysqlFunctionEnum.getFunctionByName(functionName); + } + }; } @Test - public void testSelect() { + void testSelect() { String sql = abstractMapper.select(Arrays.asList("id", "name"), Arrays.asList("id")); - Assert.assertEquals(sql, "SELECT id,name FROM tenant_info WHERE id = ?"); + assertEquals("SELECT id,name FROM tenant_info WHERE id = ?", sql); } @Test - public void testInsert() { + void testInsert() { String sql = abstractMapper.insert(Arrays.asList("id", "name")); - Assert.assertEquals(sql, "INSERT INTO tenant_info(id, name) VALUES(?,?)"); + assertEquals("INSERT INTO tenant_info(id, name) VALUES(?,?)", sql); } @Test - public void testUpdate() { + void testUpdate() { String sql = abstractMapper.update(Arrays.asList("id", "name"), Arrays.asList("id")); - Assert.assertEquals(sql, "UPDATE tenant_info SET id = ?,name = ? WHERE id = ?"); + assertEquals("UPDATE tenant_info SET id = ?,name = ? WHERE id = ?", sql); } @Test - public void testDelete() { + void testDelete() { String sql = abstractMapper.delete(Arrays.asList("id")); - Assert.assertEquals(sql, "DELETE FROM tenant_info WHERE id = ? "); + assertEquals("DELETE FROM tenant_info WHERE id = ? ", sql); } @Test - public void testCount() { + void testCount() { String sql = abstractMapper.count(Arrays.asList("id")); - Assert.assertEquals(sql, "SELECT COUNT(*) FROM tenant_info WHERE id = ?"); + assertEquals("SELECT COUNT(*) FROM tenant_info WHERE id = ?", sql); } @Test - public void testGetPrimaryKeyGeneratedKeys() { + void testGetPrimaryKeyGeneratedKeys() { String[] keys = abstractMapper.getPrimaryKeyGeneratedKeys(); - Assert.assertEquals(keys[0], "id"); + assertEquals("id", keys[0]); } @Test - public void testSelectAll() { + void testSelectAll() { String sql = abstractMapper.select(Arrays.asList("id", "name"), null); - Assert.assertEquals(sql, "SELECT id,name FROM tenant_info "); + assertEquals("SELECT id,name FROM tenant_info ", sql); } @Test - public void testCountAll() { + void testCountAll() { String sql = abstractMapper.count(null); - Assert.assertEquals(sql, "SELECT COUNT(*) FROM tenant_info "); + assertEquals("SELECT COUNT(*) FROM tenant_info ", sql); } -} \ No newline at end of file +} diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/mapper/TestMapper.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/mapper/TestMapper.java new file mode 100644 index 00000000000..643d242e4da --- /dev/null +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/mapper/TestMapper.java @@ -0,0 +1,40 @@ +/* + * Copyright 1999-2022 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.plugin.datasource.mapper; + +import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; +import com.alibaba.nacos.plugin.datasource.impl.TestInterface; +import com.alibaba.nacos.plugin.datasource.impl.mysql.ConfigInfoAggrMapperByMySql; + +/** + * Implement interfaces other than Mapper. just for test + * + * @author mikolls + **/ +public class TestMapper extends ConfigInfoAggrMapperByMySql implements TestInterface { + + @Override + public String getTableName() { + return "enable_data_source_log_test"; + } + + @Override + public String getDataSource() { + return DataSourceConstant.MYSQL; + } + +} diff --git a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/proxy/MapperProxyTest.java b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/proxy/MapperProxyTest.java index c848ebc530f..3b0be29fb90 100644 --- a/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/proxy/MapperProxyTest.java +++ b/plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/proxy/MapperProxyTest.java @@ -16,65 +16,72 @@ package com.alibaba.nacos.plugin.datasource.proxy; +import com.alibaba.nacos.plugin.datasource.enums.mysql.TrustedMysqlFunctionEnum; import com.alibaba.nacos.plugin.datasource.mapper.Mapper; -import org.junit.Assert; -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.List; -public class MapperProxyTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class MapperProxyTest { private MapperProxy mapperProxy; - @Before - public void setup() { + @BeforeEach + void setup() { this.mapperProxy = new MapperProxy(); } @Test - public void testCreateProxy() { + void testCreateProxy() { Mapper mapper = new Mapper() { @Override public String select(List columns, List where) { return "select-test"; } - + @Override public String insert(List columns) { return "insert-test"; } - + @Override public String update(List columns, List where) { return "update-test"; } - + @Override public String delete(List params) { return "delete-test"; } - + @Override public String count(List where) { return "count-test"; } - + @Override public String getTableName() { return "test"; } - + @Override public String getDataSource() { return "test"; } - + @Override public String[] getPrimaryKeyGeneratedKeys() { return new String[0]; } + + @Override + public String getFunction(String functionName) { + return TrustedMysqlFunctionEnum.getFunctionByName(functionName); + } }; Mapper proxy = mapperProxy.createProxy(mapper); try { @@ -84,7 +91,7 @@ public String[] getPrimaryKeyGeneratedKeys() { Field mapperField = mapperProxy.getClass().getDeclaredField("mapper"); mapperField.setAccessible(true); Class clazz = mapperField.getDeclaringClass(); - Assert.assertEquals(MapperProxy.class, clazz); + assertEquals(MapperProxy.class, clazz); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } diff --git a/plugin/encryption/src/test/java/com/alibaba/nacos/plugin/encryption/EncryptionPluginManagerTest.java b/plugin/encryption/src/test/java/com/alibaba/nacos/plugin/encryption/EncryptionPluginManagerTest.java index ba0bd35f0f9..1afb0c85baf 100644 --- a/plugin/encryption/src/test/java/com/alibaba/nacos/plugin/encryption/EncryptionPluginManagerTest.java +++ b/plugin/encryption/src/test/java/com/alibaba/nacos/plugin/encryption/EncryptionPluginManagerTest.java @@ -17,26 +17,28 @@ package com.alibaba.nacos.plugin.encryption; import com.alibaba.nacos.plugin.encryption.spi.EncryptionPluginService; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * EncryptionPluginManagerTest. * * @author lixiaoshuang */ -public class EncryptionPluginManagerTest { +class EncryptionPluginManagerTest { @Test - public void testInstance() { + void testInstance() { EncryptionPluginManager instance = EncryptionPluginManager.instance(); - Assert.assertNotNull(instance); + assertNotNull(instance); } @Test - public void testJoin() { + void testJoin() { EncryptionPluginManager.join(new EncryptionPluginService() { @Override public String encrypt(String secretKey, String content) { @@ -57,25 +59,25 @@ public String generateSecretKey() { public String algorithmName() { return "aes"; } - + @Override public String encryptSecretKey(String secretKey) { return secretKey; } - + @Override public String decryptSecretKey(String secretKey) { return secretKey; } }); - Assert.assertNotNull(EncryptionPluginManager.instance().findEncryptionService("aes")); + assertNotNull(EncryptionPluginManager.instance().findEncryptionService("aes")); } @Test - public void testFindEncryptionService() { + void testFindEncryptionService() { EncryptionPluginManager instance = EncryptionPluginManager.instance(); Optional optional = instance.findEncryptionService("aes"); - Assert.assertTrue(optional.isPresent()); + assertTrue(optional.isPresent()); } -} \ No newline at end of file +} diff --git a/plugin/encryption/src/test/java/com/alibaba/nacos/plugin/encryption/handler/EncryptionAesHandlerTest.java b/plugin/encryption/src/test/java/com/alibaba/nacos/plugin/encryption/handler/EncryptionAesHandlerTest.java index 4690a3f706c..45dcaaa111e 100644 --- a/plugin/encryption/src/test/java/com/alibaba/nacos/plugin/encryption/handler/EncryptionAesHandlerTest.java +++ b/plugin/encryption/src/test/java/com/alibaba/nacos/plugin/encryption/handler/EncryptionAesHandlerTest.java @@ -20,19 +20,20 @@ import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.plugin.encryption.EncryptionPluginManager; import com.alibaba.nacos.plugin.encryption.spi.EncryptionPluginService; +import org.apache.commons.codec.binary.Base64; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import java.nio.charset.StandardCharsets; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; 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 org.apache.commons.codec.binary.Base64; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * AES encryption algorithm testing dataId with prefix cipher. @@ -41,12 +42,12 @@ * @Date 2023/12/22 6:07 PM * @Version 1.0 */ -public class EncryptionAesHandlerTest { +class EncryptionAesHandlerTest { private EncryptionPluginService mockEncryptionPluginService; - @Before - public void setUp() { + @BeforeEach + void setUp() { mockEncryptionPluginService = new EncryptionPluginService() { private static final String ALGORITHM = "AES"; @@ -138,18 +139,18 @@ private String aesDecrypt(String content, String key) { } @Test - public void testEncrypt() { + void testEncrypt() { String content = "content"; String contentKey = mockEncryptionPluginService.generateSecretKey(); Pair pair = EncryptionHandler.encryptHandler("cipher-aes-dataId", content); - Assert.assertEquals("should return the encryption secret key if algorithm defined.", mockEncryptionPluginService.encryptSecretKey(contentKey), - pair.getFirst()); - Assert.assertEquals("should return the encryption content if algorithm defined.", mockEncryptionPluginService.encrypt(contentKey, content), - pair.getSecond()); + assertEquals(mockEncryptionPluginService.encryptSecretKey(contentKey), pair.getFirst(), + "should return the encryption secret key if algorithm defined."); + assertEquals(mockEncryptionPluginService.encrypt(contentKey, content), pair.getSecond(), + "should return the encryption content if algorithm defined."); } @Test - public void testDecrypt() { + void testDecrypt() { String content = "content"; String contentKey = mockEncryptionPluginService.generateSecretKey(); String encryptionSecretKey = mockEncryptionPluginService.encryptSecretKey(contentKey); @@ -157,14 +158,14 @@ public void testDecrypt() { Pair pair = EncryptionHandler.decryptHandler("cipher-aes-dataId", encryptionSecretKey, encryptionContent); - Assert.assertEquals("should return the original secret key if algorithm defined.", mockEncryptionPluginService.generateSecretKey(), - pair.getFirst()); - Assert.assertEquals("should return the original content if algorithm defined.", content, pair.getSecond()); + assertEquals(mockEncryptionPluginService.generateSecretKey(), pair.getFirst(), + "should return the original secret key if algorithm defined."); + assertEquals(content, pair.getSecond(), "should return the original content if algorithm defined."); } @Test - public void testEncryptAndDecrypt() { + void testEncryptAndDecrypt() { String dataId = "cipher-aes-dataId"; String content = "content"; String contentKey = mockEncryptionPluginService.generateSecretKey(); @@ -172,64 +173,64 @@ public void testEncryptAndDecrypt() { Pair encryptPair = EncryptionHandler.encryptHandler(dataId, content); String encryptionSecretKey = encryptPair.getFirst(); String encryptionContent = encryptPair.getSecond(); - Assert.assertNotNull(encryptPair); - Assert.assertEquals("should return the encryption secret key if algorithm defined.", mockEncryptionPluginService.encryptSecretKey(contentKey), - encryptionSecretKey); - Assert.assertEquals("should return the encryption content if algorithm defined.", mockEncryptionPluginService.encrypt(contentKey, content), - encryptionContent); + assertNotNull(encryptPair); + assertEquals(mockEncryptionPluginService.encryptSecretKey(contentKey), encryptionSecretKey, + "should return the encryption secret key if algorithm defined."); + assertEquals(mockEncryptionPluginService.encrypt(contentKey, content), encryptionContent, + "should return the encryption content if algorithm defined."); Pair decryptPair = EncryptionHandler.decryptHandler(dataId, encryptionSecretKey, encryptionContent); - Assert.assertNotNull(decryptPair); - Assert.assertEquals("should return the original secret key if algorithm defined.", mockEncryptionPluginService.generateSecretKey(), - decryptPair.getFirst()); - Assert.assertEquals("should return the original content if algorithm defined.", content, decryptPair.getSecond()); + assertNotNull(decryptPair); + assertEquals(mockEncryptionPluginService.generateSecretKey(), decryptPair.getFirst(), + "should return the original secret key if algorithm defined."); + assertEquals(content, decryptPair.getSecond(), "should return the original content if algorithm defined."); } @Test - public void testPrefixNotCipherEncrypt() { + void testPrefixNotCipherEncrypt() { String content = "content"; Pair pair = EncryptionHandler.encryptHandler("test-dataId", content); - Assert.assertNotNull(pair); - Assert.assertEquals(pair.getFirst(), ""); - Assert.assertEquals(pair.getSecond(), content); + assertNotNull(pair); + assertEquals("", pair.getFirst()); + assertEquals(pair.getSecond(), content); } @Test - public void testPrefixNotCipherDecrypt() { + void testPrefixNotCipherDecrypt() { String content = "content"; Pair pair = EncryptionHandler.decryptHandler("test-dataId", "", content); - Assert.assertNotNull(pair); - Assert.assertEquals(pair.getFirst(), ""); - Assert.assertEquals(pair.getSecond(), content); + assertNotNull(pair); + assertEquals("", pair.getFirst()); + assertEquals(pair.getSecond(), content); } @Test - public void testAlgorithmEmpty() { + void testAlgorithmEmpty() { String dataId = "cipher-"; String content = "content"; Pair pair = EncryptionHandler.encryptHandler(dataId, content); - Assert.assertNotNull("should not throw exception when parsing enc algo for dataId '" + dataId + "'", pair); - Assert.assertEquals(pair.getFirst(), ""); - Assert.assertEquals(pair.getSecond(), content); + assertNotNull(pair, "should not throw exception when parsing enc algo for dataId '" + dataId + "'"); + assertEquals("", pair.getFirst()); + assertEquals(pair.getSecond(), content); } @Test - public void testUnknownAlgorithmNameEncrypt() { + void testUnknownAlgorithmNameEncrypt() { String dataId = "cipher-mySM4-application"; String content = "content"; Pair pair = EncryptionHandler.encryptHandler(dataId, content); - Assert.assertNotNull(pair); - Assert.assertEquals(pair.getFirst(), ""); - Assert.assertEquals("should return original content if algorithm is not defined.", content, pair.getSecond()); + assertNotNull(pair); + assertEquals("", pair.getFirst()); + assertEquals(content, pair.getSecond(), "should return original content if algorithm is not defined."); } @Test - public void testUnknownAlgorithmNameDecrypt() { + void testUnknownAlgorithmNameDecrypt() { String dataId = "cipher-mySM4-application"; String content = "content"; Pair pair = EncryptionHandler.decryptHandler(dataId, "", content); - Assert.assertNotNull(pair); - Assert.assertEquals(pair.getFirst(), ""); - Assert.assertEquals("should return original content if algorithm is not defined.", content, pair.getSecond()); + assertNotNull(pair); + assertEquals("", pair.getFirst()); + assertEquals(content, pair.getSecond(), "should return original content if algorithm is not defined."); } } diff --git a/plugin/encryption/src/test/java/com/alibaba/nacos/plugin/encryption/handler/EncryptionHandlerTest.java b/plugin/encryption/src/test/java/com/alibaba/nacos/plugin/encryption/handler/EncryptionHandlerTest.java index 8eca559f377..d0e979049a8 100644 --- a/plugin/encryption/src/test/java/com/alibaba/nacos/plugin/encryption/handler/EncryptionHandlerTest.java +++ b/plugin/encryption/src/test/java/com/alibaba/nacos/plugin/encryption/handler/EncryptionHandlerTest.java @@ -19,21 +19,23 @@ import com.alibaba.nacos.common.utils.Pair; import com.alibaba.nacos.plugin.encryption.EncryptionPluginManager; import com.alibaba.nacos.plugin.encryption.spi.EncryptionPluginService; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * EncryptionHandlerTest. * * @author lixiaoshuang */ -public class EncryptionHandlerTest { +class EncryptionHandlerTest { private EncryptionPluginService mockEncryptionPluginService; - @Before - public void setUp() { + @BeforeEach + void setUp() { mockEncryptionPluginService = new EncryptionPluginService() { @Override public String encrypt(String secretKey, String content) { @@ -69,65 +71,63 @@ public String decryptSecretKey(String secretKey) { } @Test - public void testEncryptHandler() { + void testEncryptHandler() { Pair pair = EncryptionHandler.encryptHandler("test-dataId", "content"); - Assert.assertNotNull(pair); + assertNotNull(pair); } @Test - public void testDecryptHandler() { + void testDecryptHandler() { Pair pair = EncryptionHandler.decryptHandler("test-dataId", "12345678", "content"); - Assert.assertNotNull(pair); + assertNotNull(pair); } @Test - public void testCornerCaseDataIdAlgoParse() { + void testCornerCaseDataIdAlgoParse() { String dataId = "cipher-"; Pair pair = EncryptionHandler.encryptHandler(dataId, "content"); - Assert.assertNotNull("should not throw exception when parsing enc algo for dataId '" + dataId + "'", pair); + assertNotNull(pair, "should not throw exception when parsing enc algo for dataId '" + dataId + "'"); } @Test - public void testUnknownAlgorithmNameEnc() { + void testUnknownAlgorithmNameEnc() { String dataId = "cipher-mySM4-application"; String content = "content"; Pair pair = EncryptionHandler.encryptHandler(dataId, content); - Assert.assertNotNull(pair); - Assert.assertEquals("should return original content if algorithm is not defined.", content, pair.getSecond()); + assertNotNull(pair); + assertEquals(content, pair.getSecond(), "should return original content if algorithm is not defined."); } @Test - public void testUnknownAlgorithmNameDecrypt() { + void testUnknownAlgorithmNameDecrypt() { String dataId = "cipher-mySM4-application"; String content = "content"; Pair pair = EncryptionHandler.decryptHandler(dataId, "", content); - Assert.assertNotNull(pair); - Assert.assertEquals("should return original content if algorithm is not defined.", content, pair.getSecond()); + assertNotNull(pair); + assertEquals(content, pair.getSecond(), "should return original content if algorithm is not defined."); } @Test - public void testEncrypt() { + void testEncrypt() { String dataId = "cipher-mockAlgo-application"; String content = "content"; String sec = mockEncryptionPluginService.generateSecretKey(); Pair pair = EncryptionHandler.encryptHandler(dataId, content); - Assert.assertNotNull(pair); - Assert.assertEquals("should return encrypted content.", - mockEncryptionPluginService.encrypt(sec, content), pair.getSecond()); - Assert.assertEquals("should return encrypted secret key.", - mockEncryptionPluginService.encryptSecretKey(sec), pair.getFirst()); + assertNotNull(pair); + assertEquals(mockEncryptionPluginService.encrypt(sec, content), pair.getSecond(), "should return encrypted content."); + assertEquals(mockEncryptionPluginService.encryptSecretKey(sec), pair.getFirst(), "should return encrypted secret key."); } @Test - public void testDecrypt() { + void testDecrypt() { String dataId = "cipher-mockAlgo-application"; String oContent = "content"; String oSec = mockEncryptionPluginService.generateSecretKey(); String content = mockEncryptionPluginService.encrypt(oSec, oContent); String sec = mockEncryptionPluginService.encryptSecretKey(oSec); Pair pair = EncryptionHandler.decryptHandler(dataId, sec, content); - Assert.assertNotNull(pair); - Assert.assertEquals("should return original content.", oContent, pair.getSecond()); - Assert.assertEquals("should return original secret key.", oSec, pair.getFirst()); + assertNotNull(pair); + assertEquals(oContent, pair.getSecond(), "should return original content."); + assertEquals(oSec, pair.getFirst(), "should return original secret key."); } -} \ No newline at end of file +} diff --git a/plugin/environment/src/test/java/com/alibaba/nacos/plugin/environment/CustomEnvironmentPluginManagerTest.java b/plugin/environment/src/test/java/com/alibaba/nacos/plugin/environment/CustomEnvironmentPluginManagerTest.java index 9398241d579..8c8955f8c45 100644 --- a/plugin/environment/src/test/java/com/alibaba/nacos/plugin/environment/CustomEnvironmentPluginManagerTest.java +++ b/plugin/environment/src/test/java/com/alibaba/nacos/plugin/environment/CustomEnvironmentPluginManagerTest.java @@ -17,28 +17,30 @@ package com.alibaba.nacos.plugin.environment; import com.alibaba.nacos.plugin.environment.spi.CustomEnvironmentPluginService; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; +import static org.junit.jupiter.api.Assertions.assertNotNull; + /** * CustomEnvironment Plugin Test. * * @author : huangtianhui */ -public class CustomEnvironmentPluginManagerTest { +class CustomEnvironmentPluginManagerTest { + @Test - public void testInstance() { + void testInstance() { CustomEnvironmentPluginManager instance = CustomEnvironmentPluginManager.getInstance(); - Assert.assertNotNull(instance); + assertNotNull(instance); } - + @Test - public void testJoin() { + void testJoin() { CustomEnvironmentPluginManager.join(new CustomEnvironmentPluginService() { @Override public Map customValue(Map property) { @@ -46,27 +48,27 @@ public Map customValue(Map property) { property.put("db.password.0", "test" + pwd); return property; } - + @Override public Set propertyKey() { Set propertyKey = new HashSet<>(); propertyKey.add("db.password.0"); return propertyKey; } - + @Override public Integer order() { return 0; } - + @Override public String pluginName() { return "test"; } }); - Assert.assertNotNull(CustomEnvironmentPluginManager.getInstance().getPropertyKeys()); + assertNotNull(CustomEnvironmentPluginManager.getInstance().getPropertyKeys()); Map sourcePropertyMap = new HashMap<>(); sourcePropertyMap.put("db.password.0", "nacos"); - Assert.assertNotNull(CustomEnvironmentPluginManager.getInstance().getCustomValues(sourcePropertyMap)); + assertNotNull(CustomEnvironmentPluginManager.getInstance().getCustomValues(sourcePropertyMap)); } } diff --git a/plugin/trace/src/test/java/com/alibaba/nacos/plugin/trace/NacosTracePluginManagerTest.java b/plugin/trace/src/test/java/com/alibaba/nacos/plugin/trace/NacosTracePluginManagerTest.java index 7df42256859..1c6cafb9d5d 100644 --- a/plugin/trace/src/test/java/com/alibaba/nacos/plugin/trace/NacosTracePluginManagerTest.java +++ b/plugin/trace/src/test/java/com/alibaba/nacos/plugin/trace/NacosTracePluginManagerTest.java @@ -17,21 +17,21 @@ package com.alibaba.nacos.plugin.trace; import com.alibaba.nacos.plugin.trace.spi.NacosTraceSubscriber; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.fail; -public class NacosTracePluginManagerTest { +class NacosTracePluginManagerTest { - @BeforeClass - public static void setUp() { + @BeforeAll + static void setUp() { NacosTracePluginManager.getInstance(); } @Test - public void testGetAllTraceSubscribers() { + void testGetAllTraceSubscribers() { assertFalse(NacosTracePluginManager.getInstance().getAllTraceSubscribers().isEmpty()); assertContainsTestPlugin(); } @@ -42,6 +42,6 @@ private void assertContainsTestPlugin() { return; } } - Assert.fail("No found plugin named 'trace-plugin-mock'"); + fail("No found plugin named 'trace-plugin-mock'"); } } diff --git a/pom.xml b/pom.xml index 55fc7b7d768..8a50e88b560 100644 --- a/pom.xml +++ b/pom.xml @@ -88,7 +88,7 @@ - 2.4.0-SNAPSHOT + 2.4.1 UTF-8 UTF-8 @@ -127,6 +127,7 @@ 1.3.0 + 1.1.0 2.7.18 3.0 2.7 @@ -138,7 +139,7 @@ 8.0.33 10.14.2.0 0.11.2 - 1.57.2 + 1.64.2 2.17.0 3.22.3 ${grpc-java.version} @@ -360,6 +361,7 @@ **/filter-config.json **/disk_cache_test/** **/failover_test/** + lefthook.yml @@ -620,16 +622,6 @@ - - junit - junit - test - - - org.junit.vintage - junit-vintage-engine - test - org.junit.jupiter junit-jupiter @@ -724,6 +716,21 @@ nacos-client ${project.version} + + com.alibaba.nacos + nacos-logback-adapter-12 + ${project.version} + + + com.alibaba.nacos + logback-adapter + ${nacos.logback.adapter.version} + + + com.alibaba.nacos + nacos-log4j2-adapter + ${project.version} + ${project.groupId} nacos-test @@ -982,6 +989,12 @@ grpc-stub ${grpc-java.version} + + io.grpc + grpc-util + ${grpc-java.version} + compile + io.grpc grpc-testing diff --git a/prometheus/pom.xml b/prometheus/pom.xml index f36bc67857a..fad764f2e38 100644 --- a/prometheus/pom.xml +++ b/prometheus/pom.xml @@ -48,6 +48,16 @@ spring-boot-test-autoconfigure test + + org.springframework + spring-test + test + + + org.hamcrest + hamcrest + test + diff --git a/prometheus/src/main/java/com/alibaba/nacos/prometheus/utils/PrometheusUtils.java b/prometheus/src/main/java/com/alibaba/nacos/prometheus/utils/PrometheusUtils.java index 9fd377af57e..8ce8cb07a61 100644 --- a/prometheus/src/main/java/com/alibaba/nacos/prometheus/utils/PrometheusUtils.java +++ b/prometheus/src/main/java/com/alibaba/nacos/prometheus/utils/PrometheusUtils.java @@ -24,6 +24,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.stream.Collectors; import static java.util.stream.Collectors.groupingBy; @@ -36,21 +37,39 @@ public class PrometheusUtils { /** * Assemble arrayNodes for prometheus sd api. - * */ public static void assembleArrayNodes(Set targetSet, ArrayNode arrayNode) { Map> groupingInsMap = targetSet.stream().collect(groupingBy(Instance::getClusterName)); groupingInsMap.forEach((key, value) -> { - ObjectNode jsonNode = JacksonUtils.createEmptyJsonNode(); - ArrayNode targetsNode = JacksonUtils.createEmptyArrayNode(); - ObjectNode labelNode = JacksonUtils.createEmptyJsonNode(); - value.forEach(e -> { - targetsNode.add(e.getIp() + ":" + e.getPort()); - }); - labelNode.put("__meta_clusterName", key); - jsonNode.replace("targets", targetsNode); - jsonNode.replace("labels", labelNode); - arrayNode.add(jsonNode); + for (Instance instance : value) { + ObjectNode jsonNode = assembleInstanceToArrayNode(key, instance); + arrayNode.add(jsonNode); + } }); } + + /** + * assemble instance to json node, and export metadata to label. + * + * @param clusterName the cluster name + * @param instance instance info + */ + private static ObjectNode assembleInstanceToArrayNode(String clusterName, Instance instance) { + + ArrayNode targetsNode = JacksonUtils.createEmptyArrayNode(); + targetsNode.add(instance.getIp() + ":" + instance.getPort()); + ObjectNode labelNode = JacksonUtils.createEmptyJsonNode(); + //mark cluster name + labelNode.put("__meta_clusterName", clusterName); + //export metadata + Map metadata = instance.getMetadata(); + // auto convert label names contain with "." and "-" to "_" + metadata = metadata.entrySet().stream().collect(Collectors.toMap(e -> e.getKey().replace(".", "_").replace("-", "_"), e -> e.getValue())); + + metadata.forEach(labelNode::put); + ObjectNode jsonNode = JacksonUtils.createEmptyJsonNode(); + jsonNode.replace("targets", targetsNode); + jsonNode.replace("labels", labelNode); + return jsonNode; + } } diff --git a/prometheus/src/test/java/com/alibaba/nacos/prometheus/controller/PrometheusControllerTest.java b/prometheus/src/test/java/com/alibaba/nacos/prometheus/controller/PrometheusControllerTest.java index 23dba8fa7f3..d8c9acfd617 100644 --- a/prometheus/src/test/java/com/alibaba/nacos/prometheus/controller/PrometheusControllerTest.java +++ b/prometheus/src/test/java/com/alibaba/nacos/prometheus/controller/PrometheusControllerTest.java @@ -24,14 +24,13 @@ import com.alibaba.nacos.naming.core.v2.ServiceManager; import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.prometheus.api.ApiConstants; -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.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; @@ -39,9 +38,11 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.Map; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; /** @@ -50,9 +51,15 @@ * @author karsonto * @date 2023-02-01 10:56 */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class PrometheusControllerTest { + private final String nameSpace = "A"; + + private final String group = "B"; + + private final String name = "C"; + @InjectMocks private PrometheusController prometheusController; @@ -61,31 +68,31 @@ public class PrometheusControllerTest { private Service service; - private final String nameSpace = "A"; - - private final String group = "B"; - - private final String name = "C"; - private List testInstanceList; private MockMvc mockMvc; - @Before + @BeforeEach public void setUp() throws NoSuchFieldException, IllegalAccessException, NacosException { ServiceManager serviceManager = ServiceManager.getInstance(); service = Service.newService(nameSpace, group, name); serviceManager.getSingleton(service); testInstanceList = new ArrayList<>(); + testInstanceList.add(prepareInstance("A", "127.0.0.1", 8080, Collections.singletonMap("__meta_key", "value"))); + testInstanceList.add(prepareInstance("A", "127.0.0.1", 8081, Collections.singletonMap("__meta_key", "value2"))); + mockMvc = MockMvcBuilders.standaloneSetup(prometheusController).build(); + } + + private Instance prepareInstance(String clusterName, String ip, int port, Map metadata) { Instance instance = new Instance(); instance.setClusterName("A"); instance.setIp("127.0.0.1"); instance.setPort(8080); - testInstanceList.add(instance); - mockMvc = MockMvcBuilders.standaloneSetup(prometheusController).build(); + instance.setMetadata(metadata); + return instance; } - @After + @AfterEach public void tearDown() { ServiceManager serviceManager = ServiceManager.getInstance(); serviceManager.removeSingleton(service); @@ -93,48 +100,41 @@ public void tearDown() { @Test public void testMetric() throws Exception { - when(instanceServiceV2.listAllInstances(nameSpace, NamingUtils.getGroupedName(name, group))).thenReturn( - testInstanceList); + when(instanceServiceV2.listAllInstances(nameSpace, NamingUtils.getGroupedName(name, group))).thenReturn(testInstanceList); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(ApiConstants.PROMETHEUS_CONTROLLER_PATH); MockHttpServletResponse response = mockMvc.perform(builder).andReturn().getResponse(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); assertEquals(testInstanceList.size(), JacksonUtils.toObj(response.getContentAsString()).size()); } @Test public void testMetricNamespace() throws Exception { - when(instanceServiceV2.listAllInstances(nameSpace, NamingUtils.getGroupedName(name, group))).thenReturn( - testInstanceList); - String prometheusNamespacePath = ApiConstants.PROMETHEUS_CONTROLLER_NAMESPACE_PATH.replace("{namespaceId}", - nameSpace); + when(instanceServiceV2.listAllInstances(nameSpace, NamingUtils.getGroupedName(name, group))).thenReturn(testInstanceList); + String prometheusNamespacePath = ApiConstants.PROMETHEUS_CONTROLLER_NAMESPACE_PATH.replace("{namespaceId}", nameSpace); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(prometheusNamespacePath); MockHttpServletResponse response = mockMvc.perform(builder).andReturn().getResponse(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); assertEquals(testInstanceList.size(), JacksonUtils.toObj(response.getContentAsString()).size()); } @Test public void testMetricNamespaceService() throws Exception { - when(instanceServiceV2.listAllInstances(nameSpace, NamingUtils.getGroupedName(name, group))).thenReturn( - testInstanceList); - String prometheusNamespaceServicePath = ApiConstants.PROMETHEUS_CONTROLLER_SERVICE_PATH.replace("{namespaceId}", - nameSpace); + when(instanceServiceV2.listAllInstances(nameSpace, NamingUtils.getGroupedName(name, group))).thenReturn(testInstanceList); + String prometheusNamespaceServicePath = ApiConstants.PROMETHEUS_CONTROLLER_SERVICE_PATH.replace("{namespaceId}", nameSpace); prometheusNamespaceServicePath = prometheusNamespaceServicePath.replace("{service}", service.getName()); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(prometheusNamespaceServicePath); MockHttpServletResponse response = mockMvc.perform(builder).andReturn().getResponse(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); assertEquals(testInstanceList.size(), JacksonUtils.toObj(response.getContentAsString()).size()); } @Test public void testEmptyMetricNamespaceService() throws Exception { - String prometheusNamespaceServicePath = ApiConstants.PROMETHEUS_CONTROLLER_SERVICE_PATH.replace("{namespaceId}", - nameSpace); - prometheusNamespaceServicePath = prometheusNamespaceServicePath.replace("{service}", - "D"); //query non-existed service + String prometheusNamespaceServicePath = ApiConstants.PROMETHEUS_CONTROLLER_SERVICE_PATH.replace("{namespaceId}", nameSpace); + prometheusNamespaceServicePath = prometheusNamespaceServicePath.replace("{service}", "D"); //query non-existed service MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(prometheusNamespaceServicePath); MockHttpServletResponse response = mockMvc.perform(builder).andReturn().getResponse(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); assertEquals(0, JacksonUtils.toObj(response.getContentAsString()).size()); } diff --git a/prometheus/src/test/java/com/alibaba/nacos/prometheus/controller/exception/PrometheusApiExceptionHandlerTest.java b/prometheus/src/test/java/com/alibaba/nacos/prometheus/controller/exception/PrometheusApiExceptionHandlerTest.java index 0b1f8b9ba86..373010264fc 100644 --- a/prometheus/src/test/java/com/alibaba/nacos/prometheus/controller/exception/PrometheusApiExceptionHandlerTest.java +++ b/prometheus/src/test/java/com/alibaba/nacos/prometheus/controller/exception/PrometheusApiExceptionHandlerTest.java @@ -19,56 +19,52 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; import com.alibaba.nacos.prometheus.controller.PrometheusController; -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.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; + import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -@RunWith(SpringRunner.class) @WebMvcTest(PrometheusApiExceptionHandlerTest.class) public class PrometheusApiExceptionHandlerTest { - + private MockMvc mockMvc; - + @Autowired private WebApplicationContext context; - + @MockBean private PrometheusController prometheusController; - - @Before + + @BeforeEach public void before() { mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); } - + @Test public void testNacosRunTimeExceptionHandler() throws Exception { // 设置PrometheusController的行为,使其抛出NacosRuntimeException并被PrometheusApiExceptionHandler捕获处理 - when(prometheusController.metric()) - .thenThrow(new NacosRuntimeException(NacosException.INVALID_PARAM)) - .thenThrow(new NacosRuntimeException(NacosException.SERVER_ERROR)) - .thenThrow(new NacosRuntimeException(503)); - + when(prometheusController.metric()).thenThrow(new NacosRuntimeException(NacosException.INVALID_PARAM)) + .thenThrow(new NacosRuntimeException(NacosException.SERVER_ERROR)).thenThrow(new NacosRuntimeException(503)); + // 执行请求并验证响应码 - ResultActions resultActions = mockMvc.perform(get("/prometheus")); + ResultActions resultActions = mockMvc.perform(get("/prometheus")); resultActions.andExpect(MockMvcResultMatchers.status().is(NacosException.INVALID_PARAM)); - + // 执行请求并验证响应码 - ResultActions resultActions1 = mockMvc.perform(get("/prometheus")); + ResultActions resultActions1 = mockMvc.perform(get("/prometheus")); resultActions1.andExpect(MockMvcResultMatchers.status().is(NacosException.SERVER_ERROR)); - + // 执行请求并验证响应码 - ResultActions resultActions2 = mockMvc.perform(get("/prometheus")); + ResultActions resultActions2 = mockMvc.perform(get("/prometheus")); resultActions2.andExpect(MockMvcResultMatchers.status().is(503)); } -} \ No newline at end of file +} diff --git a/style/NacosCheckStyle_9.xml b/style/NacosCheckStyle_9.xml new file mode 100644 index 00000000000..6c46c983eb7 --- /dev/null +++ b/style/NacosCheckStyle_9.xml @@ -0,0 +1,220 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/style/codeStyle.md b/style/codeStyle.md index 9cf424ff86e..5ecbb8fce02 100644 --- a/style/codeStyle.md +++ b/style/codeStyle.md @@ -53,6 +53,8 @@ Volunteer wanted. 3. Import `style/NacosCheckStyle.xml` to checkstyle plugin. 4. Scan and check your modified code by plugin. +> If you install the latest version of CheckStyle plugin, it may not support the previous version of CheckStyle(9.0), you can modify the `style/NacosCheckStyle.xml` file to `style/NacosCheckStyle_9.xml` instead. + [checkstyle插件idea安装](https://plugins.jetbrains.com/plugin/1065-checkstyle-idea) 1. `Preferences/Settings --> Other Settings --> Checkstyle` 或者 `Preferences/Settings --> Tools --> Checkstyle` @@ -60,6 +62,8 @@ Volunteer wanted. 3. 导入源代码下`style/NacosCheckStyle.xml`文件到checkstyle插件。 4. 用checkstyle插件扫描你修改的代码。 +> 如果安装的CheckStyle的插件较新,已不支持9.0之前的Checkstyle版本,将上述第3步的`style/NacosCheckStyle.xml`文件修改为`style/NacosCheckStyle_9.xml`即可。 + ### eclipse IDE #### p3c diff --git a/sys/pom.xml b/sys/pom.xml index 62f573160c1..ccb4c7a48f7 100644 --- a/sys/pom.xml +++ b/sys/pom.xml @@ -42,26 +42,16 @@ spring-boot-starter - - org.springframework.boot - spring-boot-starter-test - test - - - org.junit.vintage - junit-vintage-engine - - - - org.springframework spring-test + test org.springframework.boot spring-boot-test + test com.alibaba.nacos diff --git a/sys/src/main/java/com/alibaba/nacos/sys/env/EnvUtil.java b/sys/src/main/java/com/alibaba/nacos/sys/env/EnvUtil.java index 84a85825be9..6c87d0a7c5e 100644 --- a/sys/src/main/java/com/alibaba/nacos/sys/env/EnvUtil.java +++ b/sys/src/main/java/com/alibaba/nacos/sys/env/EnvUtil.java @@ -24,8 +24,10 @@ import com.alibaba.nacos.sys.utils.DiskUtils; import com.alibaba.nacos.sys.utils.InetUtils; import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.EnumerablePropertySource; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.MutablePropertySources; +import org.springframework.core.env.PropertySource; import org.springframework.core.io.InputStreamResource; import org.springframework.core.io.Resource; @@ -43,6 +45,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Properties; import java.util.Set; import java.util.HashMap; @@ -169,6 +172,23 @@ public static String getRequiredProperty(String key) throws IllegalStateExceptio public static T getRequiredProperty(String key, Class targetType) throws IllegalStateException { return environment.getRequiredProperty(key, targetType); } + + public static Properties getProperties() { + Properties properties = new Properties(); + for (PropertySource propertySource : environment.getPropertySources()) { + if (propertySource instanceof EnumerablePropertySource) { + EnumerablePropertySource enumerablePropertySource = (EnumerablePropertySource) propertySource; + String[] propertyNames = enumerablePropertySource.getPropertyNames(); + for (String propertyName : propertyNames) { + Object propertyValue = enumerablePropertySource.getProperty(propertyName); + if (propertyValue != null) { + properties.put(propertyName, propertyValue.toString()); + } + } + } + } + return properties; + } public static String resolvePlaceholders(String text) { return environment.resolvePlaceholders(text); @@ -308,7 +328,7 @@ public static float getCpu() { public static float getMem() { return (float) (1 - - OperatingSystemBeanManager.getFreePhysicalMem() / OperatingSystemBeanManager.getTotalPhysicalMem()); + - (double) OperatingSystemBeanManager.getFreePhysicalMem() / (double) OperatingSystemBeanManager.getTotalPhysicalMem()); } public static String getConfPath() { diff --git a/sys/src/main/java/com/alibaba/nacos/sys/module/ModuleStateBuilder.java b/sys/src/main/java/com/alibaba/nacos/sys/module/ModuleStateBuilder.java index d7c14134f66..8c06d18b7a9 100644 --- a/sys/src/main/java/com/alibaba/nacos/sys/module/ModuleStateBuilder.java +++ b/sys/src/main/java/com/alibaba/nacos/sys/module/ModuleStateBuilder.java @@ -38,4 +38,14 @@ public interface ModuleStateBuilder { default boolean isIgnore() { return false; } + + /** + * Whether module is cache, default return true. + * + * @return boolean + */ + default boolean isCacheable() { + return true; + } + } diff --git a/sys/src/main/java/com/alibaba/nacos/sys/module/ModuleStateHolder.java b/sys/src/main/java/com/alibaba/nacos/sys/module/ModuleStateHolder.java index 8a481978639..e8284d6ee61 100644 --- a/sys/src/main/java/com/alibaba/nacos/sys/module/ModuleStateHolder.java +++ b/sys/src/main/java/com/alibaba/nacos/sys/module/ModuleStateHolder.java @@ -21,8 +21,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; @@ -40,6 +42,8 @@ public class ModuleStateHolder { private final Map moduleStates; + private final List moduleStateBuilders = new ArrayList<>(); + private ModuleStateHolder() { this.moduleStates = new HashMap<>(); for (ModuleStateBuilder each : NacosServiceLoader.load(ModuleStateBuilder.class)) { @@ -47,6 +51,7 @@ private ModuleStateHolder() { continue; } try { + moduleStateBuilders.add(each); ModuleState moduleState = each.build(); moduleStates.put(moduleState.getModuleName(), moduleState); } catch (Exception e) { @@ -59,11 +64,28 @@ public static ModuleStateHolder getInstance() { return INSTANCE; } + private void reBuildModuleState() { + for (ModuleStateBuilder each : moduleStateBuilders) { + if (each.isCacheable()) { + continue; + } + try { + ModuleState moduleState = each.build(); + moduleStates.put(moduleState.getModuleName(), moduleState); + } catch (Exception e) { + LOGGER.warn("reBuild ModuleState failed in builder:{}", each.getClass().getCanonicalName(), e); + } + } + + } + public Optional getModuleState(String moduleName) { + reBuildModuleState(); return Optional.ofNullable(moduleStates.get(moduleName)); } public Set getAllModuleStates() { + reBuildModuleState(); return new HashSet<>(moduleStates.values()); } diff --git a/sys/src/main/java/com/alibaba/nacos/sys/utils/InetUtils.java b/sys/src/main/java/com/alibaba/nacos/sys/utils/InetUtils.java index ca4bdba317a..7462a5f041b 100644 --- a/sys/src/main/java/com/alibaba/nacos/sys/utils/InetUtils.java +++ b/sys/src/main/java/com/alibaba/nacos/sys/utils/InetUtils.java @@ -32,6 +32,7 @@ import java.net.Inet6Address; import java.net.InetAddress; import java.net.NetworkInterface; +import java.net.SocketException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Enumeration; @@ -192,12 +193,12 @@ public static InetAddress findFirstNonLoopbackAddress() { for (Enumeration nics = NetworkInterface.getNetworkInterfaces(); nics.hasMoreElements(); ) { NetworkInterface ifc = nics.nextElement(); - if (ifc.isUp()) { + if (isUp(ifc)) { LOG.debug("Testing interface: " + ifc.getDisplayName()); - if (ifc.getIndex() < lowest || result == null) { - lowest = ifc.getIndex(); - } else { + if (ifc.getIndex() >= lowest && result != null) { continue; + } else { + lowest = ifc.getIndex(); } if (!ignoreInterface(ifc.getDisplayName())) { @@ -231,6 +232,20 @@ public static InetAddress findFirstNonLoopbackAddress() { return null; } + /** + * check network intreface isUp, not throw SocketException. + * @param ifc network interface + * @return true or false; + */ + public static boolean isUp(NetworkInterface ifc) { + try { + return ifc.isUp(); + } catch (SocketException e) { + LOG.debug("Network interface can not get isUp, exception: ", e); + } + return false; + } + private static boolean isPreferredAddress(InetAddress address) { if (useOnlySiteLocalInterface) { final boolean siteLocalAddress = address.isSiteLocalAddress(); diff --git a/sys/src/test/java/com/alibaba/nacos/sys/env/EnvModuleStateBuilderTest.java b/sys/src/test/java/com/alibaba/nacos/sys/env/EnvModuleStateBuilderTest.java index 8c0bd3c5856..cd9a43e7a27 100644 --- a/sys/src/test/java/com/alibaba/nacos/sys/env/EnvModuleStateBuilderTest.java +++ b/sys/src/test/java/com/alibaba/nacos/sys/env/EnvModuleStateBuilderTest.java @@ -18,20 +18,20 @@ import com.alibaba.nacos.common.utils.VersionUtils; import com.alibaba.nacos.sys.module.ModuleState; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.mock.env.MockEnvironment; -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; -public class EnvModuleStateBuilderTest { +class EnvModuleStateBuilderTest { private static ConfigurableEnvironment environment; - @BeforeClass - public static void setUp() throws Exception { + @BeforeAll + static void setUp() throws Exception { environment = new MockEnvironment(); EnvUtil.setEnvironment(environment); System.setProperty(Constants.STANDALONE_MODE_PROPERTY_NAME, "true"); @@ -39,11 +39,11 @@ public static void setUp() throws Exception { } @Test - public void testBuild() { + void testBuild() { ModuleState actual = new EnvModuleStateBuilder().build(); assertEquals(Constants.SYS_MODULE, actual.getModuleName()); assertEquals(EnvUtil.STANDALONE_MODE_ALONE, actual.getStates().get(Constants.STARTUP_MODE_STATE)); - assertNull(EnvUtil.FUNCTION_MODE_NAMING, actual.getStates().get(Constants.FUNCTION_MODE_STATE)); + assertNull(actual.getStates().get(Constants.FUNCTION_MODE_STATE), EnvUtil.FUNCTION_MODE_NAMING); assertEquals(VersionUtils.version, actual.getStates().get(Constants.NACOS_VERSION)); } } diff --git a/sys/src/test/java/com/alibaba/nacos/sys/env/EnvUtilTest.java b/sys/src/test/java/com/alibaba/nacos/sys/env/EnvUtilTest.java new file mode 100644 index 00000000000..f9fdd2ef216 --- /dev/null +++ b/sys/src/test/java/com/alibaba/nacos/sys/env/EnvUtilTest.java @@ -0,0 +1,53 @@ +/* + * Copyright 1999-2020 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.sys.env; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; + +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class EnvUtilTest { + + MockedStatic systemBeanManagerMocked; + + @BeforeEach + void before() { + systemBeanManagerMocked = Mockito.mockStatic(OperatingSystemBeanManager.class); + } + + @AfterEach + void after() { + if (!systemBeanManagerMocked.isClosed()) { + systemBeanManagerMocked.close(); + } + } + + @Test + public void testGetMem() { + systemBeanManagerMocked.when(() -> OperatingSystemBeanManager.getFreePhysicalMem()).thenReturn(123L); + systemBeanManagerMocked.when(() -> OperatingSystemBeanManager.getTotalPhysicalMem()).thenReturn(2048L); + assertEquals(EnvUtil.getMem(), 1 - ((double) 123L / (double) 2048L)); + + systemBeanManagerMocked.when(() -> OperatingSystemBeanManager.getFreePhysicalMem()).thenReturn(0L); + assertEquals(EnvUtil.getMem(), 1 - ((double) 0L / (double) 2048L)); + } +} diff --git a/sys/src/test/java/com/alibaba/nacos/sys/env/EnvUtilWithConfigTest.java b/sys/src/test/java/com/alibaba/nacos/sys/env/EnvUtilWithConfigTest.java index cdc91b89807..97e6db6a43f 100644 --- a/sys/src/test/java/com/alibaba/nacos/sys/env/EnvUtilWithConfigTest.java +++ b/sys/src/test/java/com/alibaba/nacos/sys/env/EnvUtilWithConfigTest.java @@ -16,47 +16,44 @@ package com.alibaba.nacos.sys.env; -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.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -@RunWith(SpringRunner.class) @ActiveProfiles("test") @SpringBootTest(classes = EnvUtilWithConfigTest.class) -public class EnvUtilWithConfigTest { +class EnvUtilWithConfigTest { private static final int SETTING_PROCESSORS = 10; @Autowired private Environment environment; - @Before - public void setUp() { + @BeforeEach + void setUp() { EnvUtil.setEnvironment((ConfigurableEnvironment) environment); } @Test - public void testGetAvailableProcessors() { + void testGetAvailableProcessors() { int actual = EnvUtil.getAvailableProcessors(); assertEquals(SETTING_PROCESSORS, actual); } @Test - public void testGetAvailableProcessorsWithMultiple() { + void testGetAvailableProcessorsWithMultiple() { int actual = EnvUtil.getAvailableProcessors(2); assertEquals(SETTING_PROCESSORS * 2, actual); } @Test - public void testGetAvailableProcessorsWithScale() { + void testGetAvailableProcessorsWithScale() { int actual = EnvUtil.getAvailableProcessors(0.5); assertEquals((int) (SETTING_PROCESSORS * 0.5), actual); } diff --git a/sys/src/test/java/com/alibaba/nacos/sys/env/EnvUtilWithoutConfigTest.java b/sys/src/test/java/com/alibaba/nacos/sys/env/EnvUtilWithoutConfigTest.java index b0859fc1499..42f36c4ad05 100644 --- a/sys/src/test/java/com/alibaba/nacos/sys/env/EnvUtilWithoutConfigTest.java +++ b/sys/src/test/java/com/alibaba/nacos/sys/env/EnvUtilWithoutConfigTest.java @@ -17,47 +17,44 @@ package com.alibaba.nacos.sys.env; import com.alibaba.nacos.common.utils.ThreadUtils; -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.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -@RunWith(SpringRunner.class) @ActiveProfiles("empty") @SpringBootTest(classes = EnvUtilWithConfigTest.class) -public class EnvUtilWithoutConfigTest { +class EnvUtilWithoutConfigTest { @Autowired private Environment environment; - @Before - public void setUp() { + @BeforeEach + void setUp() { EnvUtil.setEnvironment((ConfigurableEnvironment) environment); } @Test - public void testGetAvailableProcessors() { + void testGetAvailableProcessors() { int expected = ThreadUtils.getSuitableThreadCount(1); int actual = EnvUtil.getAvailableProcessors(); assertEquals(expected, actual); } @Test - public void testGetAvailableProcessorsWithMultiple() { + void testGetAvailableProcessorsWithMultiple() { int expected = ThreadUtils.getSuitableThreadCount(2); int actual = EnvUtil.getAvailableProcessors(2); assertEquals(expected, actual); } @Test - public void testGetAvailableProcessorsWithScale() { + void testGetAvailableProcessorsWithScale() { int expected = ThreadUtils.getSuitableThreadCount(1); int actual = EnvUtil.getAvailableProcessors(0.5); assertEquals((int) (expected * 0.5), actual); diff --git a/sys/src/test/java/com/alibaba/nacos/sys/module/ModuleStateHolderTest.java b/sys/src/test/java/com/alibaba/nacos/sys/module/ModuleStateHolderTest.java index c7fe2b0c076..eb716ee9442 100644 --- a/sys/src/test/java/com/alibaba/nacos/sys/module/ModuleStateHolderTest.java +++ b/sys/src/test/java/com/alibaba/nacos/sys/module/ModuleStateHolderTest.java @@ -17,66 +17,66 @@ package com.alibaba.nacos.sys.module; import com.alibaba.nacos.sys.env.EnvUtil; -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 org.springframework.core.env.ConfigurableEnvironment; import org.springframework.mock.env.MockEnvironment; import org.springframework.test.util.ReflectionTestUtils; import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -public class ModuleStateHolderTest { +class ModuleStateHolderTest { private Map moduleStateMap; private ConfigurableEnvironment environment; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { environment = new MockEnvironment(); EnvUtil.setEnvironment(environment); - moduleStateMap = (Map) ReflectionTestUtils - .getField(ModuleStateHolder.getInstance(), ModuleStateHolder.class, "moduleStates"); + moduleStateMap = (Map) ReflectionTestUtils.getField(ModuleStateHolder.getInstance(), + ModuleStateHolder.class, "moduleStates"); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { } @Test - public void testGetModuleState() { + void testGetModuleState() { assertNotNull(ModuleStateHolder.getInstance().getModuleState("mock")); } @Test - public void testGetAllModuleStates() { + void testGetAllModuleStates() { assertEquals(2, ModuleStateHolder.getInstance().getAllModuleStates().size()); } @Test - public void testGetStateValueByNameFound() { + void testGetStateValueByNameFound() { assertEquals("test", ModuleStateHolder.getInstance().getStateValueByName("mock", "test")); assertEquals("test", ModuleStateHolder.getInstance().getStateValueByName("mock", "test", "aaa")); } @Test - public void testGetStateValueByNameWithoutModuleState() { + void testGetStateValueByNameWithoutModuleState() { assertEquals("", ModuleStateHolder.getInstance().getStateValueByName("non-exist", "test")); assertEquals("aaa", ModuleStateHolder.getInstance().getStateValueByName("non-exist", "test", "aaa")); } @Test - public void testGetStateValueByNameWithoutStateName() { + void testGetStateValueByNameWithoutStateName() { assertEquals("", ModuleStateHolder.getInstance().getStateValueByName("mock", "non-exist")); assertEquals("aaa", ModuleStateHolder.getInstance().getStateValueByName("mock", "non-exist", "aaa")); } @Test - public void testSearchStateValue() { + void testSearchStateValue() { assertEquals("test", ModuleStateHolder.getInstance().searchStateValue("test", "aaa")); assertEquals("aaa", ModuleStateHolder.getInstance().searchStateValue("non-exist", "aaa")); } diff --git a/sys/src/test/java/com/alibaba/nacos/sys/utils/DiskUtilsTest.java b/sys/src/test/java/com/alibaba/nacos/sys/utils/DiskUtilsTest.java index 882ccf85de3..261049b0993 100644 --- a/sys/src/test/java/com/alibaba/nacos/sys/utils/DiskUtilsTest.java +++ b/sys/src/test/java/com/alibaba/nacos/sys/utils/DiskUtilsTest.java @@ -17,10 +17,9 @@ package com.alibaba.nacos.sys.utils; import com.alibaba.nacos.sys.env.EnvUtil; -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.io.File; import java.io.FileInputStream; @@ -31,45 +30,50 @@ import java.nio.file.Paths; import java.util.UUID; -public class DiskUtilsTest { +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.assertTrue; + +class DiskUtilsTest { private static File testFile; - @BeforeClass - public static void setup() throws IOException { + @BeforeAll + static void setup() throws IOException { testFile = DiskUtils.createTmpFile("nacostmp", ".ut"); } - @AfterClass - public static void tearDown() throws IOException { + @AfterAll + static void tearDown() throws IOException { testFile.deleteOnExit(); } @Test - public void testTouch() throws IOException { + void testTouch() throws IOException { File file = Paths.get(EnvUtil.getNacosTmpDir(), "touch.ut").toFile(); - Assert.assertFalse(file.exists()); + assertFalse(file.exists()); DiskUtils.touch(file); - Assert.assertTrue(file.exists()); + assertTrue(file.exists()); file.deleteOnExit(); } @Test - public void testTouchWithFileName() throws IOException { + void testTouchWithFileName() throws IOException { File file = Paths.get(EnvUtil.getNacosTmpDir(), UUID.randomUUID().toString()).toFile(); - Assert.assertFalse(file.exists()); + assertFalse(file.exists()); DiskUtils.touch(file.getParent(), file.getName()); - Assert.assertTrue(file.exists()); + assertTrue(file.exists()); file.deleteOnExit(); } @Test - public void testCreateTmpFile() throws IOException { + void testCreateTmpFile() throws IOException { File tmpFile = null; try { tmpFile = DiskUtils.createTmpFile("nacos1", ".ut"); - Assert.assertTrue(tmpFile.getName().startsWith("nacos1")); - Assert.assertTrue(tmpFile.getName().endsWith(".ut")); + assertTrue(tmpFile.getName().startsWith("nacos1")); + assertTrue(tmpFile.getName().endsWith(".ut")); } finally { if (tmpFile != null) { tmpFile.deleteOnExit(); @@ -78,13 +82,13 @@ public void testCreateTmpFile() throws IOException { } @Test - public void testCreateTmpFileWithPath() throws IOException { + void testCreateTmpFileWithPath() throws IOException { File tmpFile = null; try { tmpFile = DiskUtils.createTmpFile(EnvUtil.getNacosTmpDir(), "nacos1", ".ut"); - Assert.assertEquals(EnvUtil.getNacosTmpDir(), tmpFile.getParent()); - Assert.assertTrue(tmpFile.getName().startsWith("nacos1")); - Assert.assertTrue(tmpFile.getName().endsWith(".ut")); + assertEquals(EnvUtil.getNacosTmpDir(), tmpFile.getParent()); + assertTrue(tmpFile.getName().startsWith("nacos1")); + assertTrue(tmpFile.getName().endsWith(".ut")); } finally { if (tmpFile != null) { tmpFile.deleteOnExit(); @@ -93,94 +97,94 @@ public void testCreateTmpFileWithPath() throws IOException { } @Test - public void testReadFile() { - Assert.assertNotNull(DiskUtils.readFile(testFile)); + void testReadFile() { + assertNotNull(DiskUtils.readFile(testFile)); } @Test - public void testReadFileWithInputStream() throws FileNotFoundException { - Assert.assertNotNull(DiskUtils.readFile(new FileInputStream(testFile))); + void testReadFileWithInputStream() throws FileNotFoundException { + assertNotNull(DiskUtils.readFile(new FileInputStream(testFile))); } @Test - public void testReadFileWithPath() { - Assert.assertNotNull(DiskUtils.readFile(testFile.getParent(), testFile.getName())); + void testReadFileWithPath() { + assertNotNull(DiskUtils.readFile(testFile.getParent(), testFile.getName())); } @Test - public void testReadFileBytes() { - Assert.assertNotNull(DiskUtils.readFileBytes(testFile)); + void testReadFileBytes() { + assertNotNull(DiskUtils.readFileBytes(testFile)); } @Test - public void testReadFileBytesWithPath() { - Assert.assertNotNull(DiskUtils.readFileBytes(testFile.getParent(), testFile.getName())); + void testReadFileBytesWithPath() { + assertNotNull(DiskUtils.readFileBytes(testFile.getParent(), testFile.getName())); } @Test - public void writeFile() { - Assert.assertTrue(DiskUtils.writeFile(testFile, "unit test".getBytes(StandardCharsets.UTF_8), false)); - Assert.assertEquals("unit test", DiskUtils.readFile(testFile)); + void writeFile() { + assertTrue(DiskUtils.writeFile(testFile, "unit test".getBytes(StandardCharsets.UTF_8), false)); + assertEquals("unit test", DiskUtils.readFile(testFile)); } @Test - public void deleteQuietly() throws IOException { + void deleteQuietly() throws IOException { File tmpFile = DiskUtils.createTmpFile(UUID.randomUUID().toString(), ".ut"); DiskUtils.deleteQuietly(tmpFile); - Assert.assertFalse(tmpFile.exists()); + assertFalse(tmpFile.exists()); } @Test - public void testDeleteQuietlyWithPath() throws IOException { + void testDeleteQuietlyWithPath() throws IOException { String dir = EnvUtil.getNacosTmpDir() + "/" + "diskutils"; DiskUtils.forceMkdir(dir); DiskUtils.createTmpFile(dir, "nacos", ".ut"); Path path = Paths.get(dir); DiskUtils.deleteQuietly(path); - Assert.assertFalse(path.toFile().exists()); + assertFalse(path.toFile().exists()); } @Test - public void testDeleteFile() throws IOException { + void testDeleteFile() throws IOException { File tmpFile = DiskUtils.createTmpFile(UUID.randomUUID().toString(), ".ut"); - Assert.assertTrue(DiskUtils.deleteFile(tmpFile.getParent(), tmpFile.getName())); - Assert.assertFalse(DiskUtils.deleteFile(tmpFile.getParent(), tmpFile.getName())); + assertTrue(DiskUtils.deleteFile(tmpFile.getParent(), tmpFile.getName())); + assertFalse(DiskUtils.deleteFile(tmpFile.getParent(), tmpFile.getName())); } @Test - public void deleteDirectory() throws IOException { + void deleteDirectory() throws IOException { Path diskutils = Paths.get(EnvUtil.getNacosTmpDir(), "diskutils"); File file = diskutils.toFile(); if (!file.exists()) { file.mkdir(); } - Assert.assertTrue(file.exists()); + assertTrue(file.exists()); DiskUtils.deleteDirectory(diskutils.toString()); - Assert.assertFalse(file.exists()); + assertFalse(file.exists()); } @Test - public void testForceMkdir() throws IOException { + void testForceMkdir() throws IOException { File dir = Paths.get(EnvUtil.getNacosTmpDir(), UUID.randomUUID().toString(), UUID.randomUUID().toString()) .toFile(); DiskUtils.forceMkdir(dir); - Assert.assertTrue(dir.exists()); + assertTrue(dir.exists()); dir.deleteOnExit(); } @Test - public void testForceMkdirWithPath() throws IOException { + void testForceMkdirWithPath() throws IOException { Path path = Paths.get(EnvUtil.getNacosTmpDir(), UUID.randomUUID().toString(), UUID.randomUUID().toString()); DiskUtils.forceMkdir(path.toString()); File file = path.toFile(); - Assert.assertTrue(file.exists()); + assertTrue(file.exists()); file.deleteOnExit(); } @Test - public void deleteDirThenMkdir() throws IOException { + void deleteDirThenMkdir() throws IOException { Path path = Paths.get(EnvUtil.getNacosTmpDir(), UUID.randomUUID().toString()); DiskUtils.forceMkdir(path.toString()); @@ -190,15 +194,15 @@ public void deleteDirThenMkdir() throws IOException { DiskUtils.deleteDirThenMkdir(path.toString()); File file = path.toFile(); - Assert.assertTrue(file.exists()); - Assert.assertTrue(file.isDirectory()); - Assert.assertTrue(file.list() == null || file.list().length == 0); + assertTrue(file.exists()); + assertTrue(file.isDirectory()); + assertTrue(file.list() == null || file.list().length == 0); file.deleteOnExit(); } @Test - public void testCopyDirectory() throws IOException { + void testCopyDirectory() throws IOException { Path srcPath = Paths.get(EnvUtil.getNacosTmpDir(), UUID.randomUUID().toString()); DiskUtils.forceMkdir(srcPath.toString()); File nacos = DiskUtils.createTmpFile(srcPath.toString(), "nacos", ".ut"); @@ -207,36 +211,36 @@ public void testCopyDirectory() throws IOException { DiskUtils.copyDirectory(srcPath.toFile(), destPath.toFile()); File file = Paths.get(destPath.toString(), nacos.getName()).toFile(); - Assert.assertTrue(file.exists()); + assertTrue(file.exists()); DiskUtils.deleteDirectory(srcPath.toString()); DiskUtils.deleteDirectory(destPath.toString()); } @Test - public void testCopyFile() throws IOException { + void testCopyFile() throws IOException { File nacos = DiskUtils.createTmpFile("nacos", ".ut"); DiskUtils.copyFile(testFile, nacos); - Assert.assertEquals(DiskUtils.readFile(testFile), DiskUtils.readFile(nacos)); + assertEquals(DiskUtils.readFile(testFile), DiskUtils.readFile(nacos)); nacos.deleteOnExit(); } @Test - public void openFile() { + void openFile() { File file = DiskUtils.openFile(testFile.getParent(), testFile.getName()); - Assert.assertNotNull(file); - Assert.assertEquals(testFile.getPath(), file.getPath()); - Assert.assertEquals(testFile.getName(), file.getName()); + assertNotNull(file); + assertEquals(testFile.getPath(), file.getPath()); + assertEquals(testFile.getName(), file.getName()); } @Test - public void testOpenFileWithPath() { + void testOpenFileWithPath() { File file = DiskUtils.openFile(testFile.getParent(), testFile.getName(), false); - Assert.assertNotNull(file); - Assert.assertEquals(testFile.getPath(), file.getPath()); - Assert.assertEquals(testFile.getName(), file.getName()); + assertNotNull(file); + assertEquals(testFile.getPath(), file.getPath()); + assertEquals(testFile.getName(), file.getName()); } } diff --git a/sys/src/test/java/com/alibaba/nacos/sys/utils/InetUtilsTest.java b/sys/src/test/java/com/alibaba/nacos/sys/utils/InetUtilsTest.java index db1ec145d6c..e20ec3045e4 100644 --- a/sys/src/test/java/com/alibaba/nacos/sys/utils/InetUtilsTest.java +++ b/sys/src/test/java/com/alibaba/nacos/sys/utils/InetUtilsTest.java @@ -19,53 +19,73 @@ import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.sys.env.Constants; import com.alibaba.nacos.sys.env.EnvUtil; -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.springframework.mock.env.MockEnvironment; import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; import java.util.concurrent.TimeUnit; import static com.alibaba.nacos.sys.env.Constants.NACOS_SERVER_IP; +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.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; -public class InetUtilsTest { +class InetUtilsTest { - @Before - public void setUp() { + @BeforeEach + void setUp() { EnvUtil.setEnvironment(new MockEnvironment()); System.setProperty(NACOS_SERVER_IP, "1.1.1.1"); System.setProperty(Constants.AUTO_REFRESH_TIME, "100"); } @Test - public void testRefreshIp() throws InterruptedException { - Assert.assertEquals("1.1.1.1", InetUtils.getSelfIP()); + void testRefreshIp() throws InterruptedException { + assertEquals("1.1.1.1", InetUtils.getSelfIP()); System.setProperty(NACOS_SERVER_IP, "1.1.1.2"); TimeUnit.MILLISECONDS.sleep(300L); - - Assert.assertTrue(StringUtils.equalsIgnoreCase(InetUtils.getSelfIP(), "1.1.1.2")); + + assertTrue(StringUtils.equalsIgnoreCase(InetUtils.getSelfIP(), "1.1.1.2")); } - @After - public void tearDown() { + @AfterEach + void tearDown() { System.clearProperty(NACOS_SERVER_IP); System.clearProperty(Constants.AUTO_REFRESH_TIME); } @Test - public void getSelfIP() { - Assert.assertNotNull(InetUtils.getSelfIP()); + void getSelfIP() { + assertNotNull(InetUtils.getSelfIP()); } @Test - public void findFirstNonLoopbackAddress() { + void findFirstNonLoopbackAddress() { InetAddress address = InetUtils.findFirstNonLoopbackAddress(); - Assert.assertNotNull(address); - Assert.assertFalse(address.isLoopbackAddress()); + assertNotNull(address); + assertFalse(address.isLoopbackAddress()); + } + + @Test + void testisUp() throws SocketException { + NetworkInterface nic = mock(NetworkInterface.class); + when(nic.isUp()).thenReturn(true); + assertTrue(InetUtils.isUp(nic)); + + when(nic.isUp()).thenReturn(false); + assertFalse(InetUtils.isUp(nic)); + + when(nic.isUp()).thenThrow(new SocketException()); + assertFalse(InetUtils.isUp(nic)); } } diff --git a/sys/src/test/java/com/alibaba/nacos/sys/utils/MethodUtilTest.java b/sys/src/test/java/com/alibaba/nacos/sys/utils/MethodUtilTest.java index 52cbcbb2127..c851fefeec5 100644 --- a/sys/src/test/java/com/alibaba/nacos/sys/utils/MethodUtilTest.java +++ b/sys/src/test/java/com/alibaba/nacos/sys/utils/MethodUtilTest.java @@ -16,12 +16,14 @@ package com.alibaba.nacos.sys.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.lang.reflect.Method; -public class MethodUtilTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +class MethodUtilTest { private static final Method DOUBLE_METHOD; @@ -37,18 +39,18 @@ public class MethodUtilTest { } @Test - public void invokeAndReturnDouble() { + void invokeAndReturnDouble() { InternalMethod internalMethod = new InternalMethod(); - Assert.assertNotEquals(Double.NaN, MethodUtil.invokeAndReturnDouble(DOUBLE_METHOD, internalMethod), 0.000001d); + assertNotEquals(Double.NaN, MethodUtil.invokeAndReturnDouble(DOUBLE_METHOD, internalMethod), 0.000001d); - Assert.assertEquals(Double.NaN, MethodUtil.invokeAndReturnDouble(LONG_METHOD, internalMethod), 0.000001d); + assertEquals(Double.NaN, MethodUtil.invokeAndReturnDouble(LONG_METHOD, internalMethod), 0.000001d); } @Test - public void invokeAndReturnLong() { + void invokeAndReturnLong() { InternalMethod internalMethod = new InternalMethod(); - Assert.assertEquals(100L, MethodUtil.invokeAndReturnLong(LONG_METHOD, internalMethod)); - Assert.assertNotEquals(100L, MethodUtil.invokeAndReturnLong(DOUBLE_METHOD, internalMethod)); + assertEquals(100L, MethodUtil.invokeAndReturnLong(LONG_METHOD, internalMethod)); + assertNotEquals(100L, MethodUtil.invokeAndReturnLong(DOUBLE_METHOD, internalMethod)); } public static class InternalMethod { diff --git a/sys/src/test/java/com/alibaba/nacos/sys/utils/PropertiesUtilTest.java b/sys/src/test/java/com/alibaba/nacos/sys/utils/PropertiesUtilTest.java index 895e67b9d5e..659dee75ccf 100644 --- a/sys/src/test/java/com/alibaba/nacos/sys/utils/PropertiesUtilTest.java +++ b/sys/src/test/java/com/alibaba/nacos/sys/utils/PropertiesUtilTest.java @@ -16,30 +16,27 @@ package com.alibaba.nacos.sys.utils; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; import java.util.Map; import java.util.Properties; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -@RunWith(SpringRunner.class) @ActiveProfiles("prefix") @SpringBootTest(classes = PropertiesUtilTest.class) -public class PropertiesUtilTest { +class PropertiesUtilTest { @Autowired private ConfigurableEnvironment environment; @Test @SuppressWarnings("unchecked") - public void testGetPropertiesWithPrefixForMap() { + void testGetPropertiesWithPrefixForMap() { Map actual = PropertiesUtil.getPropertiesWithPrefixForMap(environment, "nacos.prefix"); assertEquals(3, actual.size()); for (Map.Entry entry : actual.entrySet()) { @@ -62,13 +59,13 @@ public void testGetPropertiesWithPrefixForMap() { } @Test - public void testGetPropertiesWithPrefix() { + void testGetPropertiesWithPrefix() { Properties actual = PropertiesUtil.getPropertiesWithPrefix(environment, "nacos.prefix"); assertEquals(3, actual.size()); } @Test - public void testHandleSpringBinder() { + void testHandleSpringBinder() { Map properties = PropertiesUtil.handleSpringBinder(environment, "nacos.prefix", Map.class); assertEquals(3, properties.size()); } diff --git a/sys/src/test/resources/logback-test.xml b/sys/src/test/resources/logback-test.xml new file mode 100644 index 00000000000..e726ab228a6 --- /dev/null +++ b/sys/src/test/resources/logback-test.xml @@ -0,0 +1,19 @@ + + + + + \ No newline at end of file diff --git a/test/config-test/src/test/java/com/alibaba/nacos/test/base/BaseClusterTest.java b/test/config-test/src/test/java/com/alibaba/nacos/test/base/BaseClusterTest.java index f52bc00e9e3..c6f88e13a73 100644 --- a/test/config-test/src/test/java/com/alibaba/nacos/test/base/BaseClusterTest.java +++ b/test/config-test/src/test/java/com/alibaba/nacos/test/base/BaseClusterTest.java @@ -24,16 +24,16 @@ import com.alibaba.nacos.common.notify.Event; import com.alibaba.nacos.common.notify.NotifyCenter; import com.alibaba.nacos.common.notify.listener.Subscriber; -import com.alibaba.nacos.persistence.model.event.RaftDbErrorEvent; -import com.alibaba.nacos.core.persistence.DistributedDatabaseOperateImpl; import com.alibaba.nacos.consistency.ProtocolMetaData; import com.alibaba.nacos.consistency.cp.CPProtocol; import com.alibaba.nacos.consistency.cp.MetadataKey; +import com.alibaba.nacos.core.persistence.DistributedDatabaseOperateImpl; +import com.alibaba.nacos.persistence.model.event.RaftDbErrorEvent; import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.utils.DiskUtils; import com.alibaba.nacos.sys.utils.InetUtils; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; @@ -57,9 +57,14 @@ public class BaseClusterTest extends HttpClient4Test { + protected static final String CONFIG_INFO_ID = "config-info-id"; + + protected static final AtomicBoolean[] FINISHED = new AtomicBoolean[] {new AtomicBoolean(false), + new AtomicBoolean(false), new AtomicBoolean(false)}; + private static final Logger LOGGER = LoggerFactory.getLogger(BaseClusterTest.class); - protected static final String CONFIG_INFO_ID = "config-info-id"; + protected static final NacosRestTemplate NACOS_REST_TEMPLATE = HttpClientBeanHolder.getNacosRestTemplate(LOGGER); protected static ConfigService iconfig7; @@ -67,11 +72,6 @@ public class BaseClusterTest extends HttpClient4Test { protected static ConfigService iconfig9; - protected static final NacosRestTemplate NACOS_REST_TEMPLATE = HttpClientBeanHolder.getNacosRestTemplate(LOGGER); - - protected static final AtomicBoolean[] FINISHED = new AtomicBoolean[] {new AtomicBoolean(false), - new AtomicBoolean(false), new AtomicBoolean(false)}; - protected static Map applications = new HashMap<>(); protected static String clusterInfo; @@ -79,6 +79,7 @@ public class BaseClusterTest extends HttpClient4Test { static { System.getProperties().setProperty("nacos.core.auth.enabled", "false"); System.getProperties().setProperty("embeddedStorage", "true"); + System.getProperties().setProperty("nacos.config.derby.ops.enabled", "true"); String ip = InetUtils.getSelfIP(); clusterInfo = "nacos.member.list=" + ip + ":8847," + ip + ":8848," + ip + ":8849"; @@ -95,8 +96,8 @@ public Class subscribeType() { }); } - @BeforeClass - public static void before() throws Exception { + @BeforeAll + static void before() throws Exception { CountDownLatch latch = new CountDownLatch(3); @@ -144,8 +145,8 @@ public static void before() throws Exception { TimeUnit.SECONDS.sleep(20L); } - @AfterClass - public static void after() throws Exception { + @AfterAll + static void after() throws Exception { CountDownLatch latch = new CountDownLatch(applications.size()); for (ConfigurableApplicationContext context : applications.values()) { new Thread(() -> { diff --git a/test/config-test/src/test/java/com/alibaba/nacos/test/base/HttpClient4Test.java b/test/config-test/src/test/java/com/alibaba/nacos/test/base/HttpClient4Test.java index b92c495d6d7..90c81c25f38 100644 --- a/test/config-test/src/test/java/com/alibaba/nacos/test/base/HttpClient4Test.java +++ b/test/config-test/src/test/java/com/alibaba/nacos/test/base/HttpClient4Test.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.test.base; import org.springframework.beans.factory.annotation.Autowired; @@ -27,41 +28,40 @@ import java.net.URL; /** - * Http client for test module + * Http client for test module. * * @author nkorange * @since 1.2.0 */ public class HttpClient4Test { - + protected URL base; - + @Autowired protected TestRestTemplate restTemplate; - + protected ResponseEntity request(String path, MultiValueMap params, Class clazz) { - + HttpHeaders headers = new HttpHeaders(); - + HttpEntity entity = new HttpEntity(headers); - + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.base.toString() + path) - .queryParams(params); - - return this.restTemplate.exchange( - builder.toUriString(), HttpMethod.GET, entity, clazz); + .queryParams(params); + + return this.restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, clazz); } - - protected ResponseEntity request(String path, MultiValueMap params, Class clazz, HttpMethod httpMethod) { - + + protected ResponseEntity request(String path, MultiValueMap params, Class clazz, + HttpMethod httpMethod) { + HttpHeaders headers = new HttpHeaders(); - + HttpEntity entity = new HttpEntity(headers); - + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.base.toString() + path) - .queryParams(params); - - return this.restTemplate.exchange( - builder.toUriString(), httpMethod, entity, clazz); + .queryParams(params); + + return this.restTemplate.exchange(builder.toUriString(), httpMethod, entity, clazz); } } diff --git a/test/config-test/src/test/java/com/alibaba/nacos/test/base/Params.java b/test/config-test/src/test/java/com/alibaba/nacos/test/base/Params.java index aee7d0e750c..8c3a3adc99e 100644 --- a/test/config-test/src/test/java/com/alibaba/nacos/test/base/Params.java +++ b/test/config-test/src/test/java/com/alibaba/nacos/test/base/Params.java @@ -13,30 +13,55 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.test.base; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; /** - * @author nkorange + * Helper class for building HTTP request parameters using Spring's MultiValueMap. Provides methods to construct and + * append parameters. */ public class Params { - + private MultiValueMap paramMap; - + + /** + * Private constructor to enforce usage of static factory method `newParams()`. + */ + private Params() { + this.paramMap = new LinkedMultiValueMap<>(); + } + + /** + * Static factory method to create a new instance of Params. + * + * @return A new Params instance. + */ public static Params newParams() { - Params params = new Params(); - params.paramMap = new LinkedMultiValueMap(); - return params; + return new Params(); } - + + /** + * Appends a parameter with the specified name and value to the parameter map. + * + * @param name The parameter name. + * @param value The parameter value. + * @return This Params instance for method chaining. + */ public Params appendParam(String name, String value) { this.paramMap.add(name, value); return this; } - + + /** + * Retrieves the constructed parameter map. + * + * @return The MultiValueMap containing the appended parameters. + */ public MultiValueMap done() { return paramMap; } } + diff --git a/test/config-test/src/test/java/com/alibaba/nacos/test/config/AbstractConfigAPI_CITCase.java b/test/config-test/src/test/java/com/alibaba/nacos/test/config/AbstractConfigAPIConfigITCase.java similarity index 60% rename from test/config-test/src/test/java/com/alibaba/nacos/test/config/AbstractConfigAPI_CITCase.java rename to test/config-test/src/test/java/com/alibaba/nacos/test/config/AbstractConfigAPIConfigITCase.java index f95114ea23d..239b595afdf 100644 --- a/test/config-test/src/test/java/com/alibaba/nacos/test/config/AbstractConfigAPI_CITCase.java +++ b/test/config-test/src/test/java/com/alibaba/nacos/test/config/AbstractConfigAPIConfigITCase.java @@ -32,29 +32,40 @@ import com.alibaba.nacos.common.utils.ThreadUtils; 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 javax.crypto.KeyGenerator; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.server.LocalServerPort; +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; import java.net.HttpURLConnection; +import java.nio.charset.StandardCharsets; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -public abstract class AbstractConfigAPI_CITCase { +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +abstract class AbstractConfigAPIConfigITCase { public static final long TIME_OUT = 5000; @@ -62,13 +73,13 @@ public abstract class AbstractConfigAPI_CITCase { private static final String SPECIAL_CHARACTERS = "!@#$%^&*()_+-=_|/'?."; - private static String dataId = "yanlin"; + private static ConfigService iconfig = null; - private static String group = "yanlin"; + private static HttpAgent agent = null; - static ConfigService iconfig = null; + private static String dataId = "yanlin"; - static HttpAgent agent = null; + private static String group = "yanlin"; @Value("${server.servlet.context-path}") private String contextPath; @@ -78,7 +89,7 @@ public abstract class AbstractConfigAPI_CITCase { private EncryptionPluginService mockEncryptionPluginService; - @Before + @BeforeEach public void initEncryptionPluginService() { mockEncryptionPluginService = new EncryptionPluginService() { @@ -170,7 +181,7 @@ private String aesDecrypt(String content, String key) { EncryptionPluginManager.join(mockEncryptionPluginService); } - @Before + @BeforeEach public void setUp() throws Exception { Properties properties = new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1" + ":" + port); @@ -182,7 +193,7 @@ public void setUp() throws Exception { agent.start(); } - @After + @AfterEach public void cleanup() throws Exception { HttpRestResult result = null; try { @@ -191,288 +202,319 @@ public void cleanup() throws Exception { params.put("group", group); params.put("beta", "true"); result = agent.httpDelete(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT); - Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); - Assert.assertTrue(JacksonUtils.toObj(result.getData()).get("data").booleanValue()); - Assert.assertTrue(JacksonUtils.toObj(result.getData()).get("data").booleanValue()); + assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); + assertTrue(JacksonUtils.toObj(result.getData()).get("data").booleanValue()); + assertTrue(JacksonUtils.toObj(result.getData()).get("data").booleanValue()); } catch (Exception e) { e.printStackTrace(); - Assert.fail(); + fail(); } } /** - * @TCDescription : nacos_正常获取数据 - * @TestStep : - * @ExpectResult : + * Retrieve data successfully. + * + * @throws Exception if an error occurs during the test. */ - @Test(timeout = 3 * TIME_OUT) - public void nacos_getconfig_1() throws Exception { + @Test + @Timeout(value = 3 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void getConfig() throws Exception { final String content = "test"; boolean result = iconfig.publishConfig(dataId, group, content); Thread.sleep(TIME_OUT); - Assert.assertTrue(result); + assertTrue(result); String value = iconfig.getConfig(dataId, group, TIME_OUT); - Assert.assertEquals(content, value); + assertEquals(content, value); result = iconfig.removeConfig(dataId, group); Thread.sleep(TIME_OUT); - Assert.assertTrue(result); + assertTrue(result); value = iconfig.getConfig(dataId, group, TIME_OUT); System.out.println(value); - Assert.assertNull(value); + assertNull(value); } /** - * @TCDescription : nacos_正常推送&获取加密数据 - * @TestStep : - * @ExpectResult : + * Publish and retrieve encrypted data successfully. + * + * @throws Exception if an error occurs during the test. */ - @Test(timeout = 3 * TIME_OUT) - public void nacosPublishAndGetConfig() throws Exception { + @Test + @Timeout(value = 3 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void publishAndGetConfig() throws Exception { String dataId = "cipher-aes-dataId"; final String content = "test"; boolean result = iconfig.publishConfig(dataId, group, content); Thread.sleep(TIME_OUT); - Assert.assertTrue(result); + assertTrue(result); String value = iconfig.getConfig(dataId, group, TIME_OUT); - Assert.assertEquals(content, value); + assertEquals(content, value); result = iconfig.removeConfig(dataId, group); Thread.sleep(TIME_OUT); - Assert.assertTrue(result); + assertTrue(result); value = iconfig.getConfig(dataId, group, TIME_OUT); - Assert.assertNull(value); + assertNull(value); } /** - * @throws Exception - * @TCDescription : nacos_服务端无配置时,获取配置 + * Test retrieving configuration when server has no config. + * + * @throws Exception if an error occurs during the test. */ - @Test(timeout = 5 * TIME_OUT) - public void nacos_getconfig_2() throws Exception { + @Test + @Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testGetConfigWhenServerHasNoConfig() throws Exception { String content = iconfig.getConfig(dataId, "nacos", TIME_OUT); - Assert.assertNull(content); + assertNull(content); } /** - * @throws Exception - * @TCDescription : nacos_获取配置时dataId为null + * Test fetching config when dataId is null. + * + * @throws Exception if an error occurs during the test. */ - @Test(timeout = 5 * TIME_OUT) - public void nacos_getconfig_3() throws Exception { + @Test + @Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testGetConfigWithNullDataId() throws Exception { try { String content = iconfig.getConfig(null, group, TIME_OUT); } catch (Exception e) { - Assert.assertTrue(true); + assertTrue(true); return; } - Assert.fail(); + fail(); } /** - * @throws Exception - * @TCDescription : nacos_获取配置时group为null + * Test fetching config when group is null. + * + * @throws Exception if an error occurs during the test. */ - @Test(timeout = 5 * TIME_OUT) - public void nacos_getconfig_4() throws Exception { + @Test + @Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testGetConfigWithNullGroup() throws Exception { final String dataId = "nacos_getconfig_4"; final String content = "test"; boolean result = iconfig.publishConfig(dataId, null, content); - Assert.assertTrue(result); + assertTrue(result); Thread.sleep(TIME_OUT); String value = iconfig.getConfig(dataId, null, TIME_OUT); - Assert.assertEquals(content, value); + assertEquals(content, value); result = iconfig.removeConfig(dataId, null); Thread.sleep(TIME_OUT); - Assert.assertTrue(result); + assertTrue(result); } /** - * @throws Exception - * @TCDescription : nacos_服务端无该配置项时,正常创建配置 + * Test publishing config to Nacos when the server does not have the config. + * + * @throws Exception if an error occurs during the test. */ - @Test(timeout = 5 * TIME_OUT) - public void nacos_publishConfig_1() throws Exception { + @Test + @Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testPublishConfigWhenServerDoesNotExist() throws Exception { final String content = "publishConfigTest"; boolean result = iconfig.publishConfig(dataId, group, content); Thread.sleep(TIME_OUT); - Assert.assertTrue(result); + assertTrue(result); result = iconfig.removeConfig(dataId, group); - Assert.assertTrue(result); + assertTrue(result); } /** - * @throws Exception - * @TCDescription : nacos_服务端有该配置项时,正常修改配置 + * Test updating config in Nacos when the server already has the config. + * + * @throws Exception if an error occurs during the test. */ - @Test(timeout = 5 * TIME_OUT) - public void nacos_publishConfig_2() throws Exception { + @Test + @Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testUpdateConfigWhenServerHasExistingConfig() throws Exception { final String content = "publishConfigTest"; boolean result = iconfig.publishConfig(dataId, group, content); Thread.sleep(TIME_OUT); - Assert.assertTrue(result); + assertTrue(result); final String content1 = "test.abc"; result = iconfig.publishConfig(dataId, group, content1); Thread.sleep(TIME_OUT); String value = iconfig.getConfig(dataId, group, TIME_OUT); - Assert.assertEquals(content1, value); + assertEquals(content1, value); } /** - * @throws Exception - * @TCDescription : nacos_发布配置时包含特殊字符 + * Test publishing config to Nacos with special characters. + * + * @throws Exception if an error occurs during the test. */ - @Test(timeout = 5 * TIME_OUT) - public void nacos_publishConfig_3() throws Exception { + @Test + @Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testPublishConfigWithSpecialCharacters() throws Exception { String content = "test" + SPECIAL_CHARACTERS; boolean result = iconfig.publishConfig(dataId, group, content); Thread.sleep(TIME_OUT); - Assert.assertTrue(result); + assertTrue(result); String value = iconfig.getConfig(dataId, group, TIME_OUT); - Assert.assertEquals(content, value); + assertEquals(content, value); } /** - * @throws Exception - * @TCDescription : nacos_发布配置时dataId为null + * Test publishing config to Nacos when dataId is null. + * + * @throws Exception if an error occurs during the test. */ - @Test(timeout = 5 * TIME_OUT) - public void nacos_publishConfig_4() throws Exception { + @Test + @Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testPublishConfigWithNullDataId() throws Exception { try { String content = "test"; boolean result = iconfig.publishConfig(null, group, content); Thread.sleep(TIME_OUT); - Assert.assertTrue(result); + assertTrue(result); } catch (Exception e) { - Assert.assertTrue(true); + assertTrue(true); return; } - Assert.fail(); + fail(); } /** - * @throws Exception - * @TCDescription : nacos_发布配置时group为null + * Test publishing config to Nacos when group is null. + * + * @throws Exception if an error occurs during the test. */ - @Test(timeout = 5 * TIME_OUT) - public void nacos_publishConfig_5() throws Exception { + @Test + @Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testPublishConfigWithNullGroup() throws Exception { final String dataId = "nacos_publishConfig_5"; String content = "test"; boolean result = iconfig.publishConfig(dataId, null, content); Thread.sleep(TIME_OUT); - Assert.assertTrue(result); + assertTrue(result); String value = iconfig.getConfig(dataId, null, TIME_OUT); - Assert.assertEquals(content, value); + assertEquals(content, value); } /** - * @throws Exception - * @TCDescription : nacos_发布配置时配置内容为null + * Test publishing config to Nacos when content is null. + * + * @throws Exception if an error occurs during the test. */ - @Test(timeout = 5 * TIME_OUT) - public void nacos_publishConfig_6() throws Exception { + @Test + @Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testPublishConfigWithNullContent() throws Exception { String content = null; try { boolean result = iconfig.publishConfig(dataId, group, content); Thread.sleep(TIME_OUT); } catch (Exception e) { - Assert.assertTrue(true); + assertTrue(true); return; } - Assert.fail(); + fail(); } /** - * @throws Exception - * @TCDescription : nacos_发布配置时配置内容包含中文字符 + * Test publishing configuration to Nacos with content containing Chinese characters. + * + * @throws Exception if an error occurs during the test. */ - @Test(timeout = 5 * TIME_OUT) - public void nacos_publishConfig_7() throws Exception { + @Test + @Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testPublishConfigWithChineseCharacters() throws Exception { String content = "阿里abc"; boolean result = iconfig.publishConfig(dataId, group, content); Thread.sleep(TIME_OUT); - Assert.assertTrue(result); + assertTrue(result); String value = iconfig.getConfig(dataId, group, TIME_OUT); - Assert.assertEquals(content, value); + assertEquals(content, value); } /** - * @throws Exception - * @TCDescription : nacos_服务端有该配置项时,正常删除配置 + * Test removing config from Nacos when the server has the config. + * + * @throws Exception if an error occurs during the test. */ @Test - public void nacos_removeConfig_1() throws Exception { + public void testRemoveConfigWhenServerHasConfig() throws Exception { String content = "test"; boolean result = iconfig.publishConfig(dataId, group, content); - Assert.assertTrue(result); + assertTrue(result); Thread.sleep(TIME_OUT); result = iconfig.removeConfig(dataId, group); - Assert.assertTrue(result); + assertTrue(result); Thread.sleep(TIME_OUT); String value = iconfig.getConfig(dataId, group, TIME_OUT); - Assert.assertNull(value); + assertNull(value); } /** - * @throws Exception - * @TCDescription : nacos_服务端无该配置项时,配置删除失败 + * Test removing config from Nacos when the server does not have the config. + * + * @throws Exception if an error occurs during the test. */ - @Test(timeout = 5 * TIME_OUT) - public void nacos_removeConfig_2() throws Exception { + @Test + @Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testRemoveConfigWhenServerDoesNotHaveConfig() throws Exception { group += "removeConfig2"; boolean result = iconfig.removeConfig(dataId, group); - Assert.assertTrue(result); + assertTrue(result); } /** - * @throws Exception - * @TCDescription : nacos_删除配置时dataId为null + * Test removing configuration from Nacos when dataId is null. + * + * @throws Exception if an error occurs during the test. */ - @Test(timeout = 5 * TIME_OUT) - public void nacos_removeConfig_3() throws Exception { + @Test + @Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testRemoveConfigWithNullDataId() throws Exception { try { boolean result = iconfig.removeConfig(null, group); - Assert.assertTrue(result); + assertTrue(result); } catch (Exception e) { - Assert.assertTrue(true); + assertTrue(true); return; } - Assert.fail(); + fail(); } /** - * @throws Exception - * @TCDescription : nacos_删除配置时group为null + * Test removing configuration from Nacos when group is null. + * + * @throws Exception if an error occurs during the test. */ - @Test(timeout = 5 * TIME_OUT) - public void nacos_removeConfig_4() throws Exception { + @Test + @Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testRemoveConfigWithNullGroup() throws Exception { boolean result = iconfig.removeConfig(dataId, null); - Assert.assertTrue(result); + assertTrue(result); } /** - * @throws Exception - * @TCDescription : nacos_添加对dataId的监听,在服务端修改配置后,获取监听后的修改的配置 + * Test adding listener for dataId in Nacos, retrieving modified configuration after server-side modification. + * + * @throws Exception if an error occurs during the test. */ - @Test(timeout = 5 * TIME_OUT) - public void nacos_addListener_1() throws Exception { + @Test + @Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testAddListenerAndRetrieveModifiedConfig() throws Exception { final AtomicInteger count = new AtomicInteger(0); final String content = "test-abc"; boolean result = iconfig.publishConfig(dataId, group, content); - Assert.assertTrue(result); + assertTrue(result); Listener ml = new Listener() { @Override public void receiveConfigInfo(String configInfo) { System.out.println("receive23:" + configInfo); count.incrementAndGet(); - Assert.assertEquals(content, configInfo); + assertEquals(content, configInfo); } @Override @@ -484,39 +526,42 @@ public Executor getExecutor() { while (count.get() == 0) { Thread.sleep(2000); } - Assert.assertTrue(count.get() >= 1); + assertTrue(count.get() >= 1); iconfig.removeListener(dataId, group, ml); } /** - * @TCDescription : nacos_设置监听器为null,抛出异常信息 - * @TestStep : - * @ExpectResult : + * Verify that setting a listener to null throws an IllegalArgumentException. + * * @author xiaochun.xxc * @since 3.6.8 */ - @Test(timeout = TIME_OUT, expected = IllegalArgumentException.class) - public void nacos_addListener_2() throws Exception { - iconfig.addListener(dataId, group, null); + @Test + @Timeout(value = TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testAddNullListenerThrowsException() throws Exception { + assertThrows(IllegalArgumentException.class, () -> { + iconfig.addListener(dataId, group, null); + }); } /** - * @TCDescription : nacos_添加对dataId的监听,修改服务端配置,正常推送并只推送一次 - * @TestStep : TODO Test steps - * @ExpectResult : TODO expect results + * Verify adding a listener for dataId, modifying the server configuration, and ensuring the listener is triggered + * exactly once. + * * @author xiaochun.xxc * @since 3.6.8 */ - @Test(timeout = Constants.CONFIG_LONG_POLL_TIMEOUT << 2) - public void nacos_addListener_3() throws InterruptedException, NacosException { + @Test + @Timeout(value = Constants.CONFIG_LONG_POLL_TIMEOUT << 2, unit = TimeUnit.MILLISECONDS) + public void testAddListenerAndModifyConfig() throws InterruptedException, NacosException { final AtomicInteger count = new AtomicInteger(0); final String dataId = "nacos_addListener_3"; final String group = "nacos_addListener_3"; final String content = "test-abc-" + System.currentTimeMillis(); final String newContent = "nacos_addListener_3-" + System.currentTimeMillis(); boolean result = iconfig.publishConfig(dataId, group, content); - Assert.assertTrue(result); + assertTrue(result); // Maximum assurance level notification has been performed ThreadUtils.sleep(5000); @@ -525,29 +570,29 @@ public void nacos_addListener_3() throws InterruptedException, NacosException { @Override public void receiveConfigInfo(String configInfo) { count.incrementAndGet(); - Assert.assertEquals(newContent, configInfo); + assertEquals(newContent, configInfo); } }; String receive = iconfig.getConfigAndSignListener(dataId, group, 5000L, ml); - Assert.assertEquals(content, receive); + assertEquals(content, receive); result = iconfig.publishConfig(dataId, group, newContent); - Assert.assertTrue(result); + assertTrue(result); // Get enough sleep to ensure that the monitor is triggered only once // during the two long training sessions ThreadUtils.sleep(Constants.CONFIG_LONG_POLL_TIMEOUT << 1); - Assert.assertEquals(1, count.get()); + assertEquals(1, count.get()); iconfig.removeListener(dataId, group, ml); } /** - * @TCDescription : nacos_服务端无配置时,添加对dataId的监听 - * @TestStep : TODO Test steps - * @ExpectResult : TODO expect results + * Verify that setting a null listener in Nacos throws an IllegalArgumentException. + * * @author xiaochun.xxc * @since 3.6.8 */ - @Test(timeout = 5 * TIME_OUT) - public void nacos_addListener_4() throws Exception { + @Test + @Timeout(value = TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testAddNullListener() throws Exception { final AtomicInteger count = new AtomicInteger(0); iconfig.removeConfig(dataId, group); @@ -563,31 +608,32 @@ public void receiveConfigInfo(String configInfo) { Thread.sleep(TIME_OUT); String content = "test-abc"; boolean result = iconfig.publishConfig(dataId, group, content); - Assert.assertTrue(result); + assertTrue(result); while (count.get() == 0) { Thread.sleep(3000); } - Assert.assertEquals(1, count.get()); + assertEquals(1, count.get()); iconfig.removeListener(dataId, group, ml); } /** - * @TCDescription : nacos_在主动拉取配置后并注册Listener,在更新配置后才触发Listener监听事件(使用特定接口) - * @TestStep : TODO Test steps - * @ExpectResult : TODO expect results + * Subscribe to dataId in Nacos, update server-side configuration, and verify that the listener receives the update + * exactly once. + * * @author chuntaojun * @since 3.6.8 */ @Test - public void nacos_addListener_5() throws InterruptedException, NacosException { + @Timeout(value = Constants.CONFIG_LONG_POLL_TIMEOUT << 2, unit = TimeUnit.MILLISECONDS) + public void testAddListenerAndUpdateConfig() throws InterruptedException, NacosException { final AtomicInteger count = new AtomicInteger(0); final String dataId = "nacos_addListener_5"; final String group = "nacos_addListener_5"; final String content = "test-abc"; final String newContent = "new-test-def"; boolean result = iconfig.publishConfig(dataId, group, content); - Assert.assertTrue(result); + assertTrue(result); Thread.sleep(2000); @@ -595,7 +641,7 @@ public void nacos_addListener_5() throws InterruptedException, NacosException { @Override public void receiveConfigInfo(String configInfo) { count.incrementAndGet(); - Assert.assertEquals(newContent, configInfo); + assertEquals(newContent, configInfo); } }; @@ -603,24 +649,24 @@ public void receiveConfigInfo(String configInfo) { System.out.println(receiveContent); result = iconfig.publishConfig(dataId, group, newContent); - Assert.assertTrue(result); + assertTrue(result); - Assert.assertEquals(content, receiveContent); + assertEquals(content, receiveContent); Thread.sleep(2000); - Assert.assertEquals(1, count.get()); + assertEquals(1, count.get()); iconfig.removeListener(dataId, group, ml); } /** - * @TCDescription : nacos_在主动拉取配置后并注册Listener,在更新配置后才触发Listener监听事件(进行配置参数设置) - * @TestStep : TODO Test steps - * @ExpectResult : TODO expect results + * Verify that the listener is triggered only after the configuration is updated. + * * @author chuntaojun * @since 3.6.8 */ @Test - public void nacos_addListener_6() throws InterruptedException, NacosException { + @Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testListenerTriggeredAfterConfigUpdate() throws Exception { Properties properties = new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1" + ":" + port); @@ -634,7 +680,7 @@ public void nacos_addListener_6() throws InterruptedException, NacosException { final String content = "test-abc"; final String newContent = "new-test-def"; boolean result = iconfig.publishConfig(dataId, group, content); - Assert.assertTrue(result); + assertTrue(result); Thread.sleep(2000); @@ -643,7 +689,7 @@ public void nacos_addListener_6() throws InterruptedException, NacosException { public void receiveConfigInfo(String configInfo) { count.incrementAndGet(); System.out.println("Listener receive : [" + configInfo + "]"); - Assert.assertEquals(newContent, configInfo); + assertEquals(newContent, configInfo); } }; @@ -654,31 +700,31 @@ public void receiveConfigInfo(String configInfo) { System.out.println(receiveContent); result = iconfig.publishConfig(dataId, group, newContent); - Assert.assertTrue(result); + assertTrue(result); Thread.sleep(2000); receiveContent = iconfig.getConfig(dataId, group, 1000); - Assert.assertEquals(newContent, receiveContent); + assertEquals(newContent, receiveContent); - Assert.assertEquals(1, count.get()); + assertEquals(1, count.get()); iconfig.removeListener(dataId, group, ml); } /** - * @TCDescription : nacos_正常移除监听器 - * @TestStep : TODO Test steps - * @ExpectResult : TODO expect results + * Verify normal removal of listener in Nacos. + * * @author xiaochun.xxc * @since 3.6.8 */ - @Test(timeout = 5 * TIME_OUT) - public void nacos_removeListener_1() throws Exception { + @Test + @Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testRemoveListener() throws Exception { iconfig.addListener(dataId, group, new AbstractListener() { @Override public void receiveConfigInfo(String configInfo) { - Assert.fail(); + fail(); } }); Thread.sleep(TIME_OUT); @@ -690,41 +736,39 @@ public void receiveConfigInfo(String configInfo) { } }); } catch (Exception e) { - + // ignore } } /** - * @TCDescription : nacos_移除无该项dataId的监听器 - * @TestStep : TODO Test steps - * @ExpectResult : TODO expect results + * Verify removing listener for dataId that does not exist in Nacos. + * * @author xiaochun.xxc * @since 3.6.8 */ - @Test(timeout = TIME_OUT) - public void nacos_removeListener_2() { + @Test + @Timeout(value = TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testRemoveListenerForNonexistentDataId() { group += "test.nacos"; - try { + Assertions.assertDoesNotThrow(() -> { iconfig.removeListener(dataId, group, new AbstractListener() { @Override public void receiveConfigInfo(String configInfo) { } }); - } catch (Exception e) { - Assert.fail(); - } + }); } /** - * @TCDescription : nacos_存在多个监听器时,删除最后一个监听器 - * @TestStep : TODO Test steps - * @ExpectResult : TODO expect results + * Verify removal of the last listener when multiple listeners exist in Nacos. + * * @author xiaochun.xxc * @since 3.6.8 */ - @Test(timeout = 5 * TIME_OUT) - public void nacos_removeListener_3() throws Exception { + @Test + @Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testRemoveLastListener() throws Exception { final String contentRemove = "test-abc-two"; final AtomicInteger count = new AtomicInteger(0); @@ -739,7 +783,7 @@ public void receiveConfigInfo(String configInfo) { public void receiveConfigInfo(String configInfo) { //System.out.println("ml1 remove listener receive:" + configInfo); count.incrementAndGet(); - Assert.assertEquals(contentRemove, configInfo); + assertEquals(contentRemove, configInfo); } }; iconfig.addListener(dataId, group, ml); @@ -750,97 +794,91 @@ public void receiveConfigInfo(String configInfo) { boolean result = iconfig.publishConfig(dataId, group, contentRemove); Thread.sleep(TIME_OUT); - Assert.assertTrue(result); + assertTrue(result); while (count.get() == 0) { Thread.sleep(3000); } - Assert.assertNotEquals(0, count.get()); + assertNotEquals(0, count.get()); } /** - * @TCDescription : nacos_监听器为null时 - * @TestStep : TODO Test steps - * @ExpectResult : TODO expect results + * Verify exception thrown when listener is null during removal in Nacos. + * * @author xiaochun.xxc * @since 3.6.8 */ - @Test(timeout = TIME_OUT, expected = IllegalArgumentException.class) - public void nacos_removeListener_4() { - iconfig.removeListener(dataId, group, null); + @Test + @Timeout(value = TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testRemoveListenerNull() { + assertThrows(IllegalArgumentException.class, () -> { + iconfig.removeListener(dataId, group, null); + }); } /** - * @TCDescription : nacos_openAPI_配置具体信息 - * @TestStep : - * @ExpectResult : + * Verify detailed configuration retrieval using Nacos Open API. + * * @author xiaochun.xxc * @since 3.6.8 */ - @Test(timeout = 3 * TIME_OUT) - public void nacos_openAPI_detailConfig_1() { - HttpRestResult result = null; - - try { + @Test + @Timeout(value = 3 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testOpenApiDetailConfig() { + Assertions.assertDoesNotThrow(() -> { final String content = "test"; boolean ret = iconfig.publishConfig(dataId, group, content); Thread.sleep(TIME_OUT); - Assert.assertTrue(ret); + assertTrue(ret); Map params = new HashMap<>(); params.put("dataId", dataId); params.put("group", group); params.put("show", "all"); - result = agent.httpGet(CONFIG_CONTROLLER_PATH, null, params, agent.getEncode(), TIME_OUT); - Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); + HttpRestResult result = agent.httpGet(CONFIG_CONTROLLER_PATH, null, params, agent.getEncode(), + TIME_OUT); + assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); - Assert.assertEquals(content, JacksonUtils.toObj(result.getData()).get("content").textValue()); - } catch (Exception e) { - Assert.fail(); - } + assertEquals(content, JacksonUtils.toObj(result.getData()).get("content").textValue()); + }); } /** - * @TCDescription : nacos_openAPI_catalog信息 - * @TestStep : - * @ExpectResult : + * Verify catalog information retrieval using Nacos Open API. + * * @author xiaochun.xxc * @since 3.6.8 */ - @Test(timeout = 3 * TIME_OUT) - public void nacos_openAPI_catalog() { - HttpRestResult result = null; - - try { + @Test + @Timeout(value = 3 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testOpenApiCatalog() { + Assertions.assertDoesNotThrow(() -> { final String content = "test"; boolean ret = iconfig.publishConfig(dataId, group, content); Thread.sleep(TIME_OUT); - Assert.assertTrue(ret); + assertTrue(ret); Map params = new HashMap<>(); params.put("dataId", dataId); params.put("group", group); - result = agent.httpGet(CONFIG_CONTROLLER_PATH + "/catalog", null, params, agent.getEncode(), TIME_OUT); - Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); + HttpRestResult result = agent.httpGet(CONFIG_CONTROLLER_PATH + "/catalog", null, params, + agent.getEncode(), TIME_OUT); + assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); System.out.println(result.getData()); - Assert.assertFalse(JacksonUtils.toObj(result.getData()).get("data").isNull()); + assertFalse(JacksonUtils.toObj(result.getData()).get("data").isNull()); - } catch (Exception e) { - Assert.fail(); - } + }); } /** - * @TCDescription : nacos_openAPI_queryBeta信息 - * @TestStep : - * @ExpectResult : + * Verify beta configuration query using Nacos Open API. + * * @author xiaochun.xxc * @since 3.6.8 */ - @Test(timeout = 3 * TIME_OUT) - public void nacos_openAPI_queryBeta_1() { - HttpRestResult result = null; - - try { + @Test + @Timeout(value = 3 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testOpenApiQueryBeta() { + Assertions.assertDoesNotThrow(() -> { final String content = "test-beta"; Map headers = new HashMap<>(); headers.put("betaIps", "127.0.0.1"); @@ -848,34 +886,32 @@ public void nacos_openAPI_queryBeta_1() { params.put("dataId", dataId); params.put("group", group); params.put("content", content); - result = agent.httpPost(CONFIG_CONTROLLER_PATH + "/", headers, params, agent.getEncode(), TIME_OUT); - Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); - Assert.assertEquals("true", result.getData()); + HttpRestResult result = agent.httpPost(CONFIG_CONTROLLER_PATH + "/", headers, params, + agent.getEncode(), TIME_OUT); + assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); + assertEquals("true", result.getData()); params.clear(); params.put("dataId", dataId); params.put("group", group); params.put("beta", "true"); result = agent.httpGet(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT); - Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); - Assert.assertEquals(content, JacksonUtils.toObj(result.getData()).get("data").get("content").textValue()); + assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); + assertEquals(content, JacksonUtils.toObj(result.getData()).get("data").get("content").textValue()); // delete data result = agent.httpDelete(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT); - Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); - } catch (Exception e) { - - Assert.fail(); - } + assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); + }); } /** - * @TCDescription : nacos_openAPI_queryBeta删除信息 - * @TestStep : 1. 发布配置 2. 删除Beta配置信息 - * @ExpectResult : + * Verify beta configuration deletion using Nacos Open API. + * * @author xiaochun.xxc * @since 3.6.8 */ - @Test(timeout = 3 * TIME_OUT) - public void nacos_openAPI_queryBeta_delete() { + @Test + @Timeout(value = 3 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testOpenApiQueryBetaDelete() { HttpRestResult result = null; try { @@ -887,8 +923,8 @@ public void nacos_openAPI_queryBeta_delete() { params.put("group", group); params.put("content", content); result = agent.httpPost(CONFIG_CONTROLLER_PATH + "/", headers, params, agent.getEncode(), TIME_OUT); - Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); - Assert.assertEquals("true", result.getData()); + assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); + assertEquals("true", result.getData()); params.clear(); params.put("dataId", dataId); @@ -896,96 +932,90 @@ public void nacos_openAPI_queryBeta_delete() { params.put("beta", "true"); result = agent.httpDelete(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT); - Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); - Assert.assertTrue(JacksonUtils.toObj(result.getData()).get("data").booleanValue()); + assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); + assertTrue(JacksonUtils.toObj(result.getData()).get("data").booleanValue()); } catch (Exception e) { e.printStackTrace(); - Assert.fail(); + fail(); } } /** - * @TCDescription : nacos_openAPI_模糊查询配置信息 - * @TestStep : 1. 发布配置 2. 模糊查询 - * @ExpectResult : 获取查询到配置 + * Verify fuzzy search of configuration information using Nacos Open API. + * * @author xiaochun.xxc * @since 3.6.8 */ - @Test(timeout = 5 * TIME_OUT) - public void nacos_openAPI_fuzzySearchConfig() { - HttpRestResult result = null; - - try { + @Test + @Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testOpenApiFuzzySearchConfig() { + Assertions.assertDoesNotThrow(() -> { final String content = "test123"; boolean ret = iconfig.publishConfig(dataId, group, content); Thread.sleep(TIME_OUT); - Assert.assertTrue(ret); + assertTrue(ret); Map params = new HashMap<>(); params.put("dataId", dataId); params.put("group", group); params.put("pageNo", "1"); params.put("pageSize", "10"); params.put("search", "blur"); - result = agent.httpGet(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT); - Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); + HttpRestResult result = agent.httpGet(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), + TIME_OUT); + assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); - Assert.assertTrue(JacksonUtils.toObj(result.getData()).get("totalCount").intValue() >= 1); - Assert.assertTrue(JacksonUtils.toObj(result.getData()).get("pageItems").get(0).get("content").textValue() + assertTrue(JacksonUtils.toObj(result.getData()).get("totalCount").intValue() >= 1); + assertTrue(JacksonUtils.toObj(result.getData()).get("pageItems").get(0).get("content").textValue() .startsWith(content)); - } catch (Exception e) { - Assert.fail(); - } + }); } /** - * @TCDescription : nacos_openAPI_模糊查询配置信息 - * @TestStep : 1. 发布配置 2. 查询配置信息 - * @ExpectResult : 获取查询到配置 + * Verify fuzzy search of configuration information using Nacos Open API. + * * @author xiaochun.xxc * @since 3.6.8 */ - @Test(timeout = 5 * TIME_OUT) - public void nacos_openAPI_fuzzySearchConfig_1() { - HttpRestResult result = null; + @Test + @Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testOpenApiFuzzySearchConfig1() { - try { + Assertions.assertDoesNotThrow(() -> { final String content = "test123"; boolean ret = iconfig.publishConfig(dataId, group, content); Thread.sleep(TIME_OUT); - Assert.assertTrue(ret); + assertTrue(ret); Map params = new HashMap<>(); params.put("dataId", dataId + "*"); params.put("group", group + "*"); params.put("pageNo", "1"); params.put("pageSize", "10"); params.put("search", "blur"); - result = agent.httpGet(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT); + HttpRestResult result = agent.httpGet(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), + TIME_OUT); - Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); - Assert.assertTrue(JacksonUtils.toObj(result.getData()).get("totalCount").intValue() >= 1); - Assert.assertEquals(content, + assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); + assertTrue(JacksonUtils.toObj(result.getData()).get("totalCount").intValue() >= 1); + assertEquals(content, JacksonUtils.toObj(result.getData()).get("pageItems").get(0).get("content").textValue()); - } catch (Exception e) { - Assert.fail(); - } + }); } /** - * @TCDescription : nacos_openAPI_查询配置信息 - * @TestStep : 1. 发布配置 2. 查询配置信息 - * @ExpectResult : 获取查询到配置 + * Verify accurate search of configuration information using Nacos Open API. + * * @author xiaochun.xxc * @since 3.6.8 */ - @Test(timeout = 5 * TIME_OUT) - public void nacos_openAPI_searchConfig() { - HttpRestResult result = null; + @Test + @Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testOpenApiSearchConfig() { - try { + Assertions.assertDoesNotThrow(() -> { final String content = "test123"; boolean ret = iconfig.publishConfig(dataId, group, content); - Assert.assertTrue(ret); + assertTrue(ret); Thread.sleep(TIME_OUT); Map params = new HashMap<>(); params.put("dataId", dataId); @@ -993,33 +1023,31 @@ public void nacos_openAPI_searchConfig() { params.put("pageNo", "1"); params.put("pageSize", "10"); params.put("search", "accurate"); - result = agent.httpGet(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT); + HttpRestResult result = agent.httpGet(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), + TIME_OUT); - Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); - Assert.assertEquals(1, JacksonUtils.toObj(result.getData()).get("totalCount").intValue()); - Assert.assertEquals(content, + assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); + assertEquals(1, JacksonUtils.toObj(result.getData()).get("totalCount").intValue()); + assertEquals(content, JacksonUtils.toObj(result.getData()).get("pageItems").get(0).get("content").textValue()); - } catch (Exception e) { - Assert.fail(); - } + }); } /** - * @TCDescription : nacos_openAPI_查询配置信息,包含中文,utf-8 - * @TestStep : 1. 发布配置 2. 查询配置信息 - * @ExpectResult : 获取查询到配置 + * Verify search of configuration information including Chinese characters using Nacos Open API. + * * @author xiaochun.xxc * @since 3.6.8 */ - @Test(timeout = 5 * TIME_OUT) - public void nacos_openAPI_searchConfig_2() { - HttpRestResult result = null; + @Test + @Timeout(value = 5 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + public void testOpenApiSearchConfigChinese() { - try { + Assertions.assertDoesNotThrow(() -> { final String content = "test测试"; boolean ret = iconfig.publishConfig(dataId, group, content); - Assert.assertTrue(ret); + assertTrue(ret); Thread.sleep(TIME_OUT); Map params = new HashMap<>(); @@ -1028,15 +1056,13 @@ public void nacos_openAPI_searchConfig_2() { params.put("pageNo", "1"); params.put("pageSize", "10"); params.put("search", "accurate"); - result = agent.httpGet(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT); - Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); - Assert.assertEquals(1, JacksonUtils.toObj(result.getData()).get("totalCount").intValue()); - Assert.assertEquals(content, + HttpRestResult result = agent.httpGet(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), + TIME_OUT); + assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); + assertEquals(1, JacksonUtils.toObj(result.getData()).get("totalCount").intValue()); + assertEquals(content, JacksonUtils.toObj(result.getData()).get("pageItems").get(0).get("content").textValue()); - } catch (Exception e) { - Assert.fail(); - } + }); } - } diff --git a/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigAPI_CITCase.java b/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigAPIConfigITCase.java similarity index 62% rename from test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigAPI_CITCase.java rename to test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigAPIConfigITCase.java index 70b1e6f7ac0..1cb1290d35a 100644 --- a/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigAPI_CITCase.java +++ b/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigAPIConfigITCase.java @@ -18,29 +18,31 @@ import com.alibaba.nacos.Nacos; import com.alibaba.nacos.test.base.ConfigCleanUtils; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - +import org.springframework.test.context.junit.jupiter.SpringExtension; /** + * Integration tests for Config API Config. + * * @author xiaochun.xxc */ -@RunWith(SpringRunner.class) +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +@ExtendWith(SpringExtension.class) @SpringBootTest(classes = Nacos.class, properties = { "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class ConfigAPI_CITCase extends AbstractConfigAPI_CITCase { +class ConfigAPIConfigITCase extends AbstractConfigAPIConfigITCase { - @BeforeClass - public static void beforeClass() { - ConfigCleanUtils.changeToNewTestNacosHome(ConfigAPI_CITCase.class.getSimpleName()); + @BeforeAll + static void beforeClass() { + ConfigCleanUtils.changeToNewTestNacosHome(ConfigAPIConfigITCase.class.getSimpleName()); } - @BeforeClass - @AfterClass - public static void cleanClientCache() throws Exception { + @BeforeAll + @AfterAll + static void cleanClientCache() throws Exception { ConfigCleanUtils.cleanClientCache(); } } diff --git a/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigAPI_V2_CITCase.java b/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigAPIV2ConfigITCase.java similarity index 68% rename from test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigAPI_V2_CITCase.java rename to test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigAPIV2ConfigITCase.java index 704d136a546..f7242de7d10 100644 --- a/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigAPI_V2_CITCase.java +++ b/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigAPIV2ConfigITCase.java @@ -19,38 +19,41 @@ import com.alibaba.nacos.Nacos; import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.config.server.constant.Constants; -import com.alibaba.nacos.sys.utils.DiskUtils; import com.alibaba.nacos.test.base.ConfigCleanUtils; import com.alibaba.nacos.test.base.HttpClient4Test; import com.alibaba.nacos.test.base.Params; import com.fasterxml.jackson.databind.JsonNode; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import java.net.URL; import java.util.Random; -import static com.alibaba.nacos.test.config.ConfigAPI_V2_CITCase.CONTEXT_PATH; +import static com.alibaba.nacos.test.config.ConfigAPIV2ConfigITCase.CONTEXT_PATH; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** + * Integration tests for Config API V2. + * * @author karsonto */ -@RunWith(SpringRunner.class) +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +@ExtendWith(SpringExtension.class) @SpringBootTest(classes = Nacos.class, properties = { "server.servlet.context-path=" + CONTEXT_PATH}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -@FixMethodOrder(MethodSorters.JVM) -public class ConfigAPI_V2_CITCase extends HttpClient4Test { +@TestMethodOrder(MethodName.class) +public class ConfigAPIV2ConfigITCase extends HttpClient4Test { public static final long TIME_OUT = 5000; @@ -60,39 +63,52 @@ public class ConfigAPI_V2_CITCase extends HttpClient4Test { private static final String CONTENT = randomContent(); - private final String DATA_ID = "nacos.example"; + private static final String DATA_ID = "nacos.example"; - private final String GROUP = "DEFAULT_GROUP"; + private static final String GROUP = "DEFAULT_GROUP"; - private final String NAME_SPACE_ID = "public"; + private static final String NAME_SPACE_ID = "public"; @LocalServerPort private int port; - @BeforeClass - public static void beforeClass() { - ConfigCleanUtils.changeToNewTestNacosHome(ConfigAPI_V2_CITCase.class.getSimpleName()); + @BeforeAll + static void beforeClass() { + ConfigCleanUtils.changeToNewTestNacosHome(ConfigAPIV2ConfigITCase.class.getSimpleName()); } - - @AfterClass - @BeforeClass - public static void cleanClientCache() throws Exception { + @AfterAll + @BeforeAll + static void cleanClientCache() throws Exception { ConfigCleanUtils.cleanClientCache(); } - @Before - public void setUp() throws Exception { + /** + * Generates random content for testing purposes. + */ + public static String randomContent() { + StringBuilder sb = new StringBuilder(); + Random rand = new Random(); + int temp = rand.nextInt(10) + 1; + sb.append("contentTest"); + for (int i = 0; i < temp; i++) { + sb.append(i); + } + return sb.toString(); + } + + @BeforeEach + void setUp() throws Exception { String url = String.format("http://127.0.0.1:%d/", port); this.base = new URL(url); } @Test - public void test() throws Exception { + void test() throws Exception { publishConfig(); Thread.sleep(TIME_OUT); String config = getConfig(true); - Assert.assertEquals(config, CONTENT); + assertEquals(CONTENT, config); Thread.sleep(TIME_OUT); deleteConfig(); Thread.sleep(TIME_OUT); @@ -102,19 +118,22 @@ public void test() throws Exception { } catch (Exception e) { thrown = true; } - Assert.assertTrue(thrown); + assertTrue(thrown); } - + /** + * Publishes a configuration. + * + * @throws Exception if an error occurs during the test. + */ public void publishConfig() throws Exception { ResponseEntity response = request(CONFIG_V2_CONTROLLER_PATH, Params.newParams().appendParam("dataId", DATA_ID).appendParam("group", GROUP) .appendParam("namespaceId", NAME_SPACE_ID).appendParam("content", CONTENT).done(), String.class, HttpMethod.POST); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); JsonNode json = JacksonUtils.toObj(response.getBody()); - Assert.assertEquals(true, json.get("data").asBoolean()); - + assertTrue(json.get("data").asBoolean()); } public String getConfig(boolean ignoreStatusCode) throws Exception { @@ -126,31 +145,23 @@ public String getConfig(boolean ignoreStatusCode) throws Exception { throw new RuntimeException("Fail to get config"); } } else { - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); } JsonNode json = JacksonUtils.toObj(response.getBody()); return json.get("data").asText(); } + /** + * Deletes a configuration. + * + * @throws Exception if an error occurs during the test. + */ public void deleteConfig() throws Exception { ResponseEntity response = request(CONFIG_V2_CONTROLLER_PATH, Params.newParams().appendParam("dataId", DATA_ID).appendParam("group", GROUP) .appendParam("namespaceId", NAME_SPACE_ID).done(), String.class, HttpMethod.DELETE); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); JsonNode json = JacksonUtils.toObj(response.getBody()); - Assert.assertEquals(true, json.get("data").asBoolean()); - - } - - - public static String randomContent() { - StringBuilder sb = new StringBuilder(); - Random rand = new Random(); - int temp = rand.nextInt(10) + 1; - sb.append("contentTest"); - for (int i = 0; i < temp; i++) { - sb.append(i); - } - return sb.toString(); + assertTrue(json.get("data").asBoolean()); } } diff --git a/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigAPI_With_RootContextPath_CITCase.java b/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigAPIWithRootContextPathConfigITCase.java similarity index 68% rename from test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigAPI_With_RootContextPath_CITCase.java rename to test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigAPIWithRootContextPathConfigITCase.java index da6da5253b7..cd906b71fe2 100644 --- a/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigAPI_With_RootContextPath_CITCase.java +++ b/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigAPIWithRootContextPathConfigITCase.java @@ -19,35 +19,35 @@ import com.alibaba.nacos.Nacos; import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.test.base.ConfigCleanUtils; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import java.io.IOException; - /** * Test context path is '/'. * * @see #4171 */ -@RunWith(SpringRunner.class) +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +@ExtendWith(SpringExtension.class) @SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/", "server.port=7001"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class ConfigAPI_With_RootContextPath_CITCase extends AbstractConfigAPI_CITCase { +class ConfigAPIWithRootContextPathConfigITCase extends AbstractConfigAPIConfigITCase { - @BeforeClass - public static void beforeClass() throws IOException { - ConfigCleanUtils.changeToNewTestNacosHome(ConfigAPI_With_RootContextPath_CITCase.class.getSimpleName()); + @BeforeAll + static void beforeClass() throws IOException { + ConfigCleanUtils.changeToNewTestNacosHome(ConfigAPIWithRootContextPathConfigITCase.class.getSimpleName()); ConfigCleanUtils.cleanClientCache(); EnvUtil.setPort(7001); } - @AfterClass - public static void cleanClientCache() throws Exception { + @AfterAll + static void cleanClientCache() throws Exception { ConfigCleanUtils.cleanClientCache(); EnvUtil.setPort(8848); } diff --git a/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigBetaConfigITCase.java b/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigBetaConfigITCase.java new file mode 100644 index 00000000000..8a478541d96 --- /dev/null +++ b/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigBetaConfigITCase.java @@ -0,0 +1,315 @@ +/* + * Copyright 1999-2018 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.test.config; + +import com.alibaba.nacos.Nacos; +import com.alibaba.nacos.api.exception.NacosException; +import com.alibaba.nacos.common.utils.JacksonUtils; +import com.alibaba.nacos.common.utils.ThreadUtils; +import com.alibaba.nacos.test.base.ConfigCleanUtils; +import com.alibaba.nacos.test.base.Params; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.util.MultiValueMap; +import org.springframework.web.util.UriComponentsBuilder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Integration tests for Config API Beta functionality. + * + * @author xiaochun.xxc + * @date 2019-07-03 + **/ +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +@ExtendWith(SpringExtension.class) +@SpringBootTest(classes = Nacos.class, properties = { + "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +class ConfigBetaConfigITCase { + + static final String CONFIG_CONTROLLER_PATH = "/nacos/v1/cs"; + + String dataId = "com.dungu.test"; + + String group = "default"; + + String tenant = "dungu"; + + String content = "test"; + + String appName = "nacos"; + + @LocalServerPort + private int port; + + private String url; + + @Autowired + private TestRestTemplate restTemplate; + + @BeforeAll + @AfterAll + static void cleanClientCache() throws Exception { + ConfigCleanUtils.cleanClientCache(); + ConfigCleanUtils.changeToNewTestNacosHome(ConfigBetaConfigITCase.class.getSimpleName()); + } + + @BeforeEach + void init() throws NacosException { + url = String.format("http://localhost:%d", port); + } + + /** + * Tests publishing a Beta configuration with all required parameters. + * + * @throws Exception if an error occurs during the publishing process + */ + @Test + void publishBetaConfig() throws Exception { + HttpHeaders headers = new HttpHeaders(); + headers.add("betaIps", "127.0.0.1,127.0.0.2"); + + ResponseEntity response = request(CONFIG_CONTROLLER_PATH + "/configs", headers, + Params.newParams().appendParam("dataId", dataId).appendParam("group", group) + .appendParam("tenant", tenant).appendParam("content", content).appendParam("config_tags", "") + .appendParam("appName", appName).done(), String.class, HttpMethod.POST); + System.out.println("publishBetaConfig : " + response); + assertTrue(response.getStatusCode().is2xxSuccessful()); + assertEquals("true", response.getBody()); + } + + /** + * Tests publishing a Beta configuration without the required content parameter. + * + * @throws Exception if an error occurs during the publishing process + */ + @Test + void publishBetaConfigNoContent() throws Exception { + HttpHeaders headers = new HttpHeaders(); + headers.add("betaIps", "127.0.0.1,127.0.0.2"); + + ResponseEntity response = request(CONFIG_CONTROLLER_PATH + "/configs", headers, + Params.newParams().appendParam("dataId", dataId).appendParam("group", group) + .appendParam("tenant", tenant).appendParam("config_tags", "").appendParam("appName", appName) + .done(), String.class, HttpMethod.POST); + System.out.println("publishBetaConfig_no_content : " + response); + assertFalse(response.getStatusCode().is2xxSuccessful()); + } + + /** + * Tests publishing and retrieving a Beta configuration without beta IPs, expecting failure. + * + * @throws Exception if an error occurs during the publishing process + */ + @Test + void publishBetaConfigNoBetaIpsBeta() throws Exception { + HttpHeaders headers = new HttpHeaders(); //不存在betaIps + + ResponseEntity response = request(CONFIG_CONTROLLER_PATH + "/configs", headers, + Params.newParams().appendParam("dataId", dataId).appendParam("group", group) + .appendParam("tenant", tenant).appendParam("content", content).appendParam("config_tags", "") + .appendParam("appName", appName).done(), String.class, HttpMethod.POST); + System.out.println("publishBetaConfig_noBetaIps_beta post : " + response); + assertTrue(response.getStatusCode().is2xxSuccessful()); + assertEquals("true", response.getBody()); + + ResponseEntity response1 = request(CONFIG_CONTROLLER_PATH + "/configs?beta=true", + Params.newParams().appendParam("dataId", dataId).appendParam("group", group) + .appendParam("tenant", tenant).done(), String.class, HttpMethod.GET); + System.out.println("publishBetaConfig_noBetaIps_beta get : " + response); + assertTrue(response1.getStatusCode().is2xxSuccessful()); + assertTrue(JacksonUtils.toObj(response1.getBody()).get("data").isNull()); + } + + /** + * Tests publishing and retrieving a Beta configuration without beta IPs. + * + * @throws Exception if an error occurs during the process + */ + @Test + void publishBetaConfigNoBetaIps() throws Exception { + + HttpHeaders headers = new HttpHeaders(); //不存在betaIps + + final String dataId = "publishBetaConfig_noBetaIps"; + final String groupId = "publishBetaConfig_noBetaIps"; + final String content = "publishBetaConfig_noBetaIps"; + + ResponseEntity response = request(CONFIG_CONTROLLER_PATH + "/configs", headers, + Params.newParams().appendParam("dataId", dataId).appendParam("group", groupId) + .appendParam("tenant", tenant).appendParam("content", content).appendParam("config_tags", "") + .appendParam("appName", appName).done(), String.class, HttpMethod.POST); + System.out.println("publishBetaConfig_noBetaIps post : " + response); + assertTrue(response.getStatusCode().is2xxSuccessful()); + assertEquals("true", response.getBody()); + + ThreadUtils.sleep(10_000L); + + response = request(CONFIG_CONTROLLER_PATH + "/configs?beta=false", + Params.newParams().appendParam("dataId", dataId).appendParam("group", groupId) + .appendParam("tenant", tenant).done(), String.class, HttpMethod.GET); + System.out.println("publishBetaConfig_noBetaIps get : " + response); + assertTrue(response.getStatusCode().is2xxSuccessful()); + assertEquals(content, response.getBody()); + } + + /** + * Tests retrieving a Beta configuration. + * + * @throws Exception if an error occurs during the process + */ + @Test + void getBetaConfig() throws Exception { + HttpHeaders headers = new HttpHeaders(); + headers.add("betaIps", "127.0.0.1,127.0.0.2"); + + ResponseEntity response = request(CONFIG_CONTROLLER_PATH + "/configs", headers, + Params.newParams().appendParam("dataId", dataId).appendParam("group", group) + .appendParam("tenant", tenant).appendParam("content", content).appendParam("config_tags", "") + .appendParam("appName", appName).done(), String.class, HttpMethod.POST); + System.out.println("getBetaConfig post : " + response); + assertTrue(response.getStatusCode().is2xxSuccessful()); + assertEquals("true", response.getBody()); + + response = request(CONFIG_CONTROLLER_PATH + "/configs?beta=true", + Params.newParams().appendParam("dataId", dataId).appendParam("group", group) + .appendParam("tenant", tenant).done(), String.class, HttpMethod.GET); + System.out.println("getBetaConfig get : " + response); + assertTrue(response.getStatusCode().is2xxSuccessful()); + assertEquals("com.dungu.test", JacksonUtils.toObj(response.getBody()).get("data").get("dataId").asText()); + } + + /** + * Delete Beta configuration successfully. + * + * @throws Exception if an error occurs during the process + */ + @Test + void deleteBetaConfig() throws Exception { + + HttpHeaders headers = new HttpHeaders(); + headers.add("betaIps", "127.0.0.1,127.0.0.2"); + + ResponseEntity response = request(CONFIG_CONTROLLER_PATH + "/configs", headers, + Params.newParams().appendParam("dataId", dataId).appendParam("group", group) + .appendParam("tenant", tenant).appendParam("content", content).appendParam("config_tags", "") + .appendParam("appName", appName).done(), String.class, HttpMethod.POST); + System.out.println("deleteBetaConfig post : " + response); + assertTrue(response.getStatusCode().is2xxSuccessful()); + assertEquals("true", response.getBody()); + + response = request(CONFIG_CONTROLLER_PATH + "/configs?beta=true", + Params.newParams().appendParam("dataId", dataId).appendParam("group", group) + .appendParam("tenant", tenant).done(), String.class, HttpMethod.GET); + System.out.println("deleteBetaConfig get : " + response); + assertTrue(response.getStatusCode().is2xxSuccessful()); + assertEquals("com.dungu.test", JacksonUtils.toObj(response.getBody()).get("data").get("dataId").asText()); + + response = request(CONFIG_CONTROLLER_PATH + "/configs?beta=true", + Params.newParams().appendParam("dataId", dataId).appendParam("group", group) + .appendParam("tenant", tenant).done(), String.class, HttpMethod.DELETE); + System.out.println("deleteBetaConfig delete : " + response); + assertTrue(response.getStatusCode().is2xxSuccessful()); + assertEquals("true", JacksonUtils.toObj(response.getBody()).get("data").asText()); + + response = request(CONFIG_CONTROLLER_PATH + "/configs?beta=true", + Params.newParams().appendParam("dataId", dataId).appendParam("group", group) + .appendParam("tenant", tenant).done(), String.class, HttpMethod.GET); + System.out.println("deleteBetaConfig after delete then get : " + response); + assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(JacksonUtils.toObj(response.getBody()).get("data").isNull()); + } + + + /** + * Delete Beta configuration with beta=false. + * + * @throws Exception if an error occurs during the process + */ + @Test + void deleteBetaConfigDeleteBetaFalse() throws Exception { + + HttpHeaders headers = new HttpHeaders(); + headers.add("betaIps", "127.0.0.1,127.0.0.2"); + + ResponseEntity response = request(CONFIG_CONTROLLER_PATH + "/configs", headers, + Params.newParams().appendParam("dataId", dataId).appendParam("group", group) + .appendParam("tenant", tenant).appendParam("content", content).appendParam("config_tags", "") + .appendParam("appName", appName).done(), String.class, HttpMethod.POST); + System.out.println("deleteBetaConfig_delete_beta_false post : " + response); + assertTrue(response.getStatusCode().is2xxSuccessful()); + assertEquals("true", response.getBody()); + + response = request(CONFIG_CONTROLLER_PATH + "/configs?beta=true", + Params.newParams().appendParam("dataId", dataId).appendParam("group", group) + .appendParam("tenant", tenant).done(), String.class, HttpMethod.GET); + System.out.println("deleteBetaConfig_delete_beta_false get : " + response); + assertTrue(response.getStatusCode().is2xxSuccessful()); + assertEquals("com.dungu.test", JacksonUtils.toObj(response.getBody()).get("data").get("dataId").asText()); + + response = request(CONFIG_CONTROLLER_PATH + "/configs?beta=false", + Params.newParams().appendParam("dataId", dataId).appendParam("group", group) + .appendParam("tenant", tenant).done(), String.class, HttpMethod.DELETE); + System.out.println("deleteBetaConfig_delete_beta_false delete : " + response); + assertTrue(response.getStatusCode().is2xxSuccessful()); + assertEquals("true", response.getBody()); + + response = request(CONFIG_CONTROLLER_PATH + "/configs?beta=true", + Params.newParams().appendParam("dataId", dataId).appendParam("group", group) + .appendParam("tenant", tenant).done(), String.class, HttpMethod.GET); + System.out.println("deleteBetaConfig_delete_beta_false after delete then get : " + response); + assertTrue(response.getStatusCode().is2xxSuccessful()); + assertEquals("com.dungu.test", JacksonUtils.toObj(response.getBody()).get("data").get("dataId").asText()); + } + + ResponseEntity request(String path, MultiValueMap params, Class clazz, + HttpMethod httpMethod) { + + HttpHeaders headers = new HttpHeaders(); + + HttpEntity entity = new HttpEntity(headers); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.url.toString() + path).queryParams(params); + + return this.restTemplate.exchange(builder.toUriString(), httpMethod, entity, clazz); + } + + ResponseEntity request(String path, HttpHeaders headers, MultiValueMap params, + Class clazz, HttpMethod httpMethod) { + + HttpEntity entity = new HttpEntity(headers); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.url.toString() + path).queryParams(params); + + return this.restTemplate.exchange(builder.toUriString(), httpMethod, entity, clazz); + } + +} diff --git a/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigBeta_CITCase.java b/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigBeta_CITCase.java deleted file mode 100644 index a92b38c847f..00000000000 --- a/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigBeta_CITCase.java +++ /dev/null @@ -1,400 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.test.config; - -import com.alibaba.nacos.Nacos; -import com.alibaba.nacos.api.exception.NacosException; -import com.alibaba.nacos.common.utils.JacksonUtils; -import com.alibaba.nacos.common.utils.ThreadUtils; -import com.alibaba.nacos.test.base.ConfigCleanUtils; -import com.alibaba.nacos.test.base.Params; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.util.MultiValueMap; -import org.springframework.web.util.UriComponentsBuilder; - -/** - * @author xiaochun.xxc - * @date 2019-07-03 - **/ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"}, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class ConfigBeta_CITCase { - - @LocalServerPort - private int port; - - private String url; - - @Autowired - private TestRestTemplate restTemplate; - - static final String CONFIG_CONTROLLER_PATH = "/nacos/v1/cs"; - - String dataId = "com.dungu.test"; - String group = "default"; - String tenant = "dungu"; - String content = "test"; - String appName = "nacos"; - - @BeforeClass - @AfterClass - public static void cleanClientCache() throws Exception { - ConfigCleanUtils.cleanClientCache(); - ConfigCleanUtils.changeToNewTestNacosHome(ConfigBeta_CITCase.class.getSimpleName()); - } - - @Before - public void init() throws NacosException { - url = String.format("http://localhost:%d", port); - } - - /** - * @TCDescription : 正常发布Beta配置 - * @TestStep : - * @ExpectResult : - */ - @Test - public void publishBetaConfig() throws Exception { - HttpHeaders headers = new HttpHeaders(); - headers.add("betaIps", "127.0.0.1,127.0.0.2"); - - ResponseEntity response = request(CONFIG_CONTROLLER_PATH + "/configs", headers, - Params.newParams() - .appendParam("dataId", dataId) - .appendParam("group", group) - .appendParam("tenant", tenant) - .appendParam("content", content) - .appendParam("config_tags", "") - .appendParam("appName", appName) - .done(), - String.class, - HttpMethod.POST); - System.out.println("publishBetaConfig : " + response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - Assert.assertEquals("true", response.getBody()); - } - - /** - * @TCDescription : 必选content未设置的发布Beta配置 - * @TestStep : - * @ExpectResult : - */ - @Test - public void publishBetaConfig_no_content() throws Exception { - HttpHeaders headers = new HttpHeaders(); - headers.add("betaIps", "127.0.0.1,127.0.0.2"); - - ResponseEntity response = request(CONFIG_CONTROLLER_PATH + "/configs", headers, - Params.newParams() - .appendParam("dataId", dataId) - .appendParam("group", group) - .appendParam("tenant", tenant) - .appendParam("config_tags", "") - .appendParam("appName", appName) - .done(), - String.class, - HttpMethod.POST); - System.out.println("publishBetaConfig_no_content : " + response); - Assert.assertFalse(response.getStatusCode().is2xxSuccessful()); - } - - /** - * @TCDescription : 可选参数betaIps不存在时,发布Beta配置应该不成功。 - * @TestStep : - * @ExpectResult : - */ - @Test - public void publishBetaConfig_noBetaIps_beta() throws Exception { - HttpHeaders headers = new HttpHeaders(); //不存在betaIps - - ResponseEntity response = request(CONFIG_CONTROLLER_PATH + "/configs", headers, - Params.newParams() - .appendParam("dataId", dataId) - .appendParam("group", group) - .appendParam("tenant", tenant) - .appendParam("content", content) - .appendParam("config_tags", "") - .appendParam("appName", appName) - .done(), - String.class, - HttpMethod.POST); - System.out.println("publishBetaConfig_noBetaIps_beta post : " + response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - Assert.assertEquals("true", response.getBody()); - - ResponseEntity response1 = request(CONFIG_CONTROLLER_PATH + "/configs?beta=true", - Params.newParams() - .appendParam("dataId", dataId) - .appendParam("group", group) - .appendParam("tenant", tenant) - .done(), - String.class, - HttpMethod.GET); - System.out.println("publishBetaConfig_noBetaIps_beta get : " + response); - Assert.assertTrue(response1.getStatusCode().is2xxSuccessful()); - Assert.assertTrue(JacksonUtils.toObj(response1.getBody()).get("data").isNull()); - } - - /** - * @TCDescription : 可选参数betaIps不存在时,发布Beta配置应该不成功。 - * @TestStep : - * @ExpectResult : - */ - @Test - public void publishBetaConfig_noBetaIps() throws Exception { - - HttpHeaders headers = new HttpHeaders(); //不存在betaIps - - final String dataId = "publishBetaConfig_noBetaIps"; - final String groupId = "publishBetaConfig_noBetaIps"; - final String content = "publishBetaConfig_noBetaIps"; - - ResponseEntity response = request(CONFIG_CONTROLLER_PATH + "/configs", headers, - Params.newParams() - .appendParam("dataId", dataId) - .appendParam("group", groupId) - .appendParam("tenant", tenant) - .appendParam("content", content) - .appendParam("config_tags", "") - .appendParam("appName", appName) - .done(), - String.class, - HttpMethod.POST); - System.out.println("publishBetaConfig_noBetaIps post : " + response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - Assert.assertEquals("true", response.getBody()); - - ThreadUtils.sleep(10_000L); - - response = request(CONFIG_CONTROLLER_PATH + "/configs?beta=false", - Params.newParams() - .appendParam("dataId", dataId) - .appendParam("group", groupId) - .appendParam("tenant", tenant) - .done(), - String.class, - HttpMethod.GET); - System.out.println("publishBetaConfig_noBetaIps get : " + response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - Assert.assertEquals(content, response.getBody()); - } - - /** - * @TCDescription : 正常获取Beta配置 - * @TestStep : - * @ExpectResult : - */ - @Test - public void getBetaConfig() throws Exception { - HttpHeaders headers = new HttpHeaders(); - headers.add("betaIps", "127.0.0.1,127.0.0.2"); - - ResponseEntity response = request(CONFIG_CONTROLLER_PATH + "/configs", headers, - Params.newParams() - .appendParam("dataId", dataId) - .appendParam("group", group) - .appendParam("tenant", tenant) - .appendParam("content", content) - .appendParam("config_tags", "") - .appendParam("appName", appName) - .done(), - String.class, - HttpMethod.POST); - System.out.println("getBetaConfig post : " + response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - Assert.assertEquals("true", response.getBody()); - - response = request(CONFIG_CONTROLLER_PATH + "/configs?beta=true", - Params.newParams() - .appendParam("dataId", dataId) - .appendParam("group", group) - .appendParam("tenant", tenant) - .done(), - String.class, - HttpMethod.GET); - System.out.println("getBetaConfig get : " + response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - Assert.assertEquals("com.dungu.test", JacksonUtils.toObj(response.getBody()).get("data").get("dataId").asText()); - } - - /** - * @TCDescription : 正常删除Beta配置 - * @TestStep : - * @ExpectResult : - */ - @Test - public void deleteBetaConfig() throws Exception { - - HttpHeaders headers = new HttpHeaders(); - headers.add("betaIps", "127.0.0.1,127.0.0.2"); - - ResponseEntity response = request(CONFIG_CONTROLLER_PATH + "/configs", headers, - Params.newParams() - .appendParam("dataId", dataId) - .appendParam("group", group) - .appendParam("tenant", tenant) - .appendParam("content", content) - .appendParam("config_tags", "") - .appendParam("appName", appName) - .done(), - String.class, - HttpMethod.POST); - System.out.println("deleteBetaConfig post : " + response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - Assert.assertEquals("true", response.getBody()); - - response = request(CONFIG_CONTROLLER_PATH + "/configs?beta=true", - Params.newParams() - .appendParam("dataId", dataId) - .appendParam("group", group) - .appendParam("tenant", tenant) - .done(), - String.class, - HttpMethod.GET); - System.out.println("deleteBetaConfig get : " + response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - Assert.assertEquals("com.dungu.test", JacksonUtils.toObj(response.getBody()).get("data").get("dataId").asText()); - - response = request(CONFIG_CONTROLLER_PATH + "/configs?beta=true", - Params.newParams() - .appendParam("dataId", dataId) - .appendParam("group", group) - .appendParam("tenant", tenant) - .done(), - String.class, - HttpMethod.DELETE); - System.out.println("deleteBetaConfig delete : " + response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - Assert.assertEquals("true", JacksonUtils.toObj(response.getBody()).get("data").asText()); - - response = request(CONFIG_CONTROLLER_PATH + "/configs?beta=true", - Params.newParams() - .appendParam("dataId", dataId) - .appendParam("group", group) - .appendParam("tenant", tenant) - .done(), - String.class, - HttpMethod.GET); - System.out.println("deleteBetaConfig after delete then get : " + response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - Assert.assertTrue(JacksonUtils.toObj(response.getBody()).get("data").isNull()); - } - - - /** - * @TCDescription : beta=false时,删除Beta配置 - * @TestStep : - * @ExpectResult : - */ - @Test - public void deleteBetaConfig_delete_beta_false() throws Exception { - - HttpHeaders headers = new HttpHeaders(); - headers.add("betaIps", "127.0.0.1,127.0.0.2"); - - ResponseEntity response = request(CONFIG_CONTROLLER_PATH + "/configs", headers, - Params.newParams() - .appendParam("dataId", dataId) - .appendParam("group", group) - .appendParam("tenant", tenant) - .appendParam("content", content) - .appendParam("config_tags", "") - .appendParam("appName", appName) - .done(), - String.class, - HttpMethod.POST); - System.out.println("deleteBetaConfig_delete_beta_false post : " + response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - Assert.assertEquals("true", response.getBody()); - - response = request(CONFIG_CONTROLLER_PATH + "/configs?beta=true", - Params.newParams() - .appendParam("dataId", dataId) - .appendParam("group", group) - .appendParam("tenant", tenant) - .done(), - String.class, - HttpMethod.GET); - System.out.println("deleteBetaConfig_delete_beta_false get : " + response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - Assert.assertEquals("com.dungu.test", JacksonUtils.toObj(response.getBody()).get("data").get("dataId").asText()); - - response = request(CONFIG_CONTROLLER_PATH + "/configs?beta=false", - Params.newParams() - .appendParam("dataId", dataId) - .appendParam("group", group) - .appendParam("tenant", tenant) - .done(), - String.class, - HttpMethod.DELETE); - System.out.println("deleteBetaConfig_delete_beta_false delete : " + response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - Assert.assertEquals("true", response.getBody()); - - response = request(CONFIG_CONTROLLER_PATH + "/configs?beta=true", - Params.newParams() - .appendParam("dataId", dataId) - .appendParam("group", group) - .appendParam("tenant", tenant) - .done(), - String.class, - HttpMethod.GET); - System.out.println("deleteBetaConfig_delete_beta_false after delete then get : " + response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - Assert.assertEquals("com.dungu.test", JacksonUtils.toObj(response.getBody()).get("data").get("dataId").asText()); - } - - ResponseEntity request(String path, MultiValueMap params, Class clazz, HttpMethod httpMethod) { - - HttpHeaders headers = new HttpHeaders(); - - HttpEntity entity = new HttpEntity(headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.url.toString() + path) - .queryParams(params); - - return this.restTemplate.exchange( - builder.toUriString(), httpMethod, entity, clazz); - } - - ResponseEntity request(String path, HttpHeaders headers, MultiValueMap params, Class clazz, HttpMethod httpMethod) { - - HttpEntity entity = new HttpEntity(headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.url.toString() + path) - .queryParams(params); - - return this.restTemplate.exchange( - builder.toUriString(), httpMethod, entity, clazz); - } - -} diff --git a/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigDerbyImport_CITCase.java b/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigDerbyImportConfigITCase.java similarity index 89% rename from test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigDerbyImport_CITCase.java rename to test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigDerbyImportConfigITCase.java index 52f69363dcb..9d34eefeeca 100644 --- a/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigDerbyImport_CITCase.java +++ b/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigDerbyImportConfigITCase.java @@ -26,93 +26,97 @@ import com.alibaba.nacos.persistence.repository.embedded.operate.DatabaseOperate; import com.alibaba.nacos.sys.utils.DiskUtils; import com.alibaba.nacos.test.base.ConfigCleanUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import java.io.File; import java.util.List; import java.util.concurrent.CompletableFuture; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Data import integration tests. * * @author liaochuntao */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"}, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class ConfigDerbyImport_CITCase { +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +@ExtendWith(SpringExtension.class) +@SpringBootTest(classes = Nacos.class, properties = { + "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +class ConfigDerbyImportConfigITCase { + + private static final String SQL_SCRIPT_CONTEXT = + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (1,'boot-test','ALIBABA','dept:123123123\\ngroup:123123123','2ca50d002a7dabf81497f666a7967e15','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL);\n" + + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (2,'people','DEFAULT_GROUP','people.enable=true','d92cbf8d02080017a805b7efc4481b6c','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL);\n" + + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (3,'apple','DEFAULT_GROUP','apple:\\n list:\\n - 1\\n - 2\\n - 3\\n - 4\\n listMap:\\n key-1:\\n - 1\\n - 2\\n - 3\\n - 4\\n key-2:\\n - aa\\n - dd\\n - ee\\n - rr','4eb5a2258ba6ecddd9631ec10cf36342','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL);\n" + + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (4,'nacos.log','LOG_DEVELOP','logging.level.com.alibaba.boot.nacos.sample=error','96c1909608cad11034802b336b0c5490','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,'text',NULL);\n" + + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (5,'nacos.log','DEFAULT_GROUP','logging.level.com.alibaba.cloud.examples=error','43ed366ef7542af8bf37fb6dbe39e46d','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,'text',NULL);\n" + + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (6,'test','DEFAULT_GROUP','dept: Aliware\\ngroup: Alibaba','2f60cf534f6eb67c6c95c8e0acbcff0a','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL);\n" + + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (7,'common.properties','DEFAULT_GROUP','user.age=12\\nuser.name=liaochuntao','b68ec4349bb2a824d622c423ce3cbcce','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,'properties',NULL);\n" + + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (8,'nacos_cloud_test','DEFAULT_GROUP','user.remark=this is nacos-springboot-adaper testing-89lll\\nuser.age=20','826245312682523bca25308a96ec491c','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL);\n" + + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (9,'extension1.properties','DEFAULT_GROUP','user.age=28','4585b001cc1c4ff4ac94d8dbccdb888f','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,'properties',NULL);\n" + + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (10,'first-property-source-data-id','DEFAULT_GROUP','user.name = Mercy Ma','e36dc37603eabe6dbd08ddab5ae728e3','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL);\n" + + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (11,'before-os-env-property-source-data-id','DEFAULT_GROUP','PATH = /home/my-path','44dae1248f3b8bbc72698e2de4441cc3','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL);\n" + + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (12,'after-system-properties-property-source-data-id','DEFAULT_GROUP','user.name = mercyblitz','f6a3287654d0c79ec47dc3359ea419fa','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL);\n" + + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (13,'example','DEFAULT_GROUP','useLocalCache=true','25a822367cd73c79acc56da3c73fa07e','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL);\n" + + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (14,'people','DEVELOP','people.enable=true','d92cbf8d02080017a805b7efc4481b6c','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL);\n" + + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (15,'test_nacos_1_2_0','DEFAULT_GROUP','this.is.test=liaochuntao\\n\\nkey=value\\n\\nredis.url=127.0.0.1:3306','2482e3802f8fc5fd34545bbbbd121719','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL);\n" + + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (17,'develop_test','DEFAULT_GROUP','develop_test=develop_testdevelop_testdevelop_testdevelop_test','cc4ffd21bdd54362b84d629fd243e050','2020-04-13 13:51:48','2020-04-13 13:51:48',NULL,'127.0.0.1','','188c49ac-d06f-4abe-9d05-7bb87185ac34',NULL,NULL,NULL,'properties',NULL);\n" + + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (33,'application.properties','DEFAULT_GROUP','name=liaochuntao is man','17581188a1cdc684721dde500c693c07','2020-04-30 10:45:21','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,'properties',NULL);\n" + + "\n"; @Autowired private ApplicationContext context; - @BeforeClass - public static void beforeClass() { - ConfigCleanUtils.changeToNewTestNacosHome(ConfigDerbyImport_CITCase.class.getSimpleName()); + @BeforeAll + static void beforeClass() { + ConfigCleanUtils.changeToNewTestNacosHome(ConfigDerbyImportConfigITCase.class.getSimpleName()); } - @Before - public void setUp() { + @BeforeEach + void setUp() { DynamicDataSource.getInstance().getDataSource().getJdbcTemplate().execute("TRUNCATE TABLE config_info"); } - @Test() - public void testDerbyImport() throws Throwable { + @Test + void testDerbyImport() throws Throwable { DatabaseOperate operate = context.getBean(DatabaseOperate.class); File file = DiskUtils.createTmpFile("derby_import" + System.currentTimeMillis(), ".tmp"); DiskUtils.writeFile(file, ByteUtils.toBytes(SQL_SCRIPT_CONTEXT), false); try { - List ids = operate.queryMany("SELECT id FROM config_info", new Object[]{}, Integer.class); + List ids = operate.queryMany("SELECT id FROM config_info", new Object[] {}, Integer.class); for (Integer each : ids) { System.out.println("current id in table config_info contain: " + each); } CompletableFuture> future = operate.dataImport(file); RestResult result = future.join(); System.out.println(result); - Assert.assertTrue(result.ok()); - + assertTrue(result.ok()); + final String queryDataId = "people"; final String queryGroup = "DEFAULT_GROUP"; final String expectContent = "people.enable=true"; - + ConfigInfoPersistService persistService = context.getBean(ConfigInfoPersistService.class); ConfigInfo configInfo = persistService.findConfigInfo(queryDataId, queryGroup, ""); System.out.println(configInfo); - Assert.assertNotNull(configInfo); - Assert.assertEquals(queryDataId, configInfo.getDataId()); - Assert.assertEquals(queryGroup, configInfo.getGroup()); - Assert.assertEquals("", configInfo.getTenant()); - Assert.assertEquals(expectContent, configInfo.getContent()); + assertNotNull(configInfo); + assertEquals(queryDataId, configInfo.getDataId()); + assertEquals(queryGroup, configInfo.getGroup()); + assertEquals("", configInfo.getTenant()); + assertEquals(expectContent, configInfo.getContent()); } finally { DiskUtils.deleteQuietly(file); } } - private static String SQL_SCRIPT_CONTEXT = - "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (1,'boot-test','ALIBABA','dept:123123123\\ngroup:123123123','2ca50d002a7dabf81497f666a7967e15','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL);\n" - + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (2,'people','DEFAULT_GROUP','people.enable=true','d92cbf8d02080017a805b7efc4481b6c','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL);\n" - + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (3,'apple','DEFAULT_GROUP','apple:\\n list:\\n - 1\\n - 2\\n - 3\\n - 4\\n listMap:\\n key-1:\\n - 1\\n - 2\\n - 3\\n - 4\\n key-2:\\n - aa\\n - dd\\n - ee\\n - rr','4eb5a2258ba6ecddd9631ec10cf36342','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL);\n" - + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (4,'nacos.log','LOG_DEVELOP','logging.level.com.alibaba.boot.nacos.sample=error','96c1909608cad11034802b336b0c5490','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,'text',NULL);\n" - + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (5,'nacos.log','DEFAULT_GROUP','logging.level.com.alibaba.cloud.examples=error','43ed366ef7542af8bf37fb6dbe39e46d','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,'text',NULL);\n" - + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (6,'test','DEFAULT_GROUP','dept: Aliware\\ngroup: Alibaba','2f60cf534f6eb67c6c95c8e0acbcff0a','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL);\n" - + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (7,'common.properties','DEFAULT_GROUP','user.age=12\\nuser.name=liaochuntao','b68ec4349bb2a824d622c423ce3cbcce','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,'properties',NULL);\n" - + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (8,'nacos_cloud_test','DEFAULT_GROUP','user.remark=this is nacos-springboot-adaper testing-89lll\\nuser.age=20','826245312682523bca25308a96ec491c','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL);\n" - + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (9,'extension1.properties','DEFAULT_GROUP','user.age=28','4585b001cc1c4ff4ac94d8dbccdb888f','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,'properties',NULL);\n" - + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (10,'first-property-source-data-id','DEFAULT_GROUP','user.name = Mercy Ma','e36dc37603eabe6dbd08ddab5ae728e3','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL);\n" - + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (11,'before-os-env-property-source-data-id','DEFAULT_GROUP','PATH = /home/my-path','44dae1248f3b8bbc72698e2de4441cc3','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL);\n" - + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (12,'after-system-properties-property-source-data-id','DEFAULT_GROUP','user.name = mercyblitz','f6a3287654d0c79ec47dc3359ea419fa','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL);\n" - + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (13,'example','DEFAULT_GROUP','useLocalCache=true','25a822367cd73c79acc56da3c73fa07e','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL);\n" - + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (14,'people','DEVELOP','people.enable=true','d92cbf8d02080017a805b7efc4481b6c','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL);\n" - + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (15,'test_nacos_1_2_0','DEFAULT_GROUP','this.is.test=liaochuntao\\n\\nkey=value\\n\\nredis.url=127.0.0.1:3306','2482e3802f8fc5fd34545bbbbd121719','2020-04-13 13:44:43','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,NULL,NULL);\n" - + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (17,'develop_test','DEFAULT_GROUP','develop_test=develop_testdevelop_testdevelop_testdevelop_test','cc4ffd21bdd54362b84d629fd243e050','2020-04-13 13:51:48','2020-04-13 13:51:48',NULL,'127.0.0.1','','188c49ac-d06f-4abe-9d05-7bb87185ac34',NULL,NULL,NULL,'properties',NULL);\n" - + "INSERT INTO `config_info` (`id`, `data_id`, `group_id`, `content`, `md5`, `gmt_create`, `gmt_modified`, `src_user`, `src_ip`, `app_name`, `tenant_id`, `c_desc`, `c_use`, `effect`, `type`, `c_schema`) VALUES (33,'application.properties','DEFAULT_GROUP','name=liaochuntao is man','17581188a1cdc684721dde500c693c07','2020-04-30 10:45:21','2020-04-30 10:45:21',NULL,'127.0.0.1','','',NULL,NULL,NULL,'properties',NULL);\n" - + "\n"; - } diff --git a/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigDerbyRaft_DITCase.java b/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigDerbyRaftConfigITCase.java similarity index 71% rename from test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigDerbyRaft_DITCase.java rename to test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigDerbyRaftConfigITCase.java index 70666729b4e..25f76bc5eee 100644 --- a/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigDerbyRaft_DITCase.java +++ b/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigDerbyRaftConfigITCase.java @@ -36,12 +36,10 @@ import com.alibaba.nacos.sys.utils.InetUtils; import com.alibaba.nacos.test.base.BaseClusterTest; import com.alibaba.nacos.test.base.ConfigCleanUtils; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.springframework.context.ConfigurableApplicationContext; import java.util.HashMap; @@ -52,30 +50,39 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +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; + /** + * Integration tests for Derby Raft configuration in the cluster environment. + * * @author liaochuntao */ -@SuppressWarnings("all") -@Ignore -@FixMethodOrder(value = MethodSorters.NAME_ASCENDING) -public class ConfigDerbyRaft_DITCase extends BaseClusterTest { +// todo the suffix is _DITCase, the case will be skipped by default +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +@TestMethodOrder(MethodName.class) +class ConfigDerbyRaftConfigITCase extends BaseClusterTest { - @BeforeClass - public static void beforeClass() { - ConfigCleanUtils.changeToNewTestNacosHome(ConfigDerbyRaft_DITCase.class.getSimpleName()); + @BeforeAll + static void beforeClass() { + ConfigCleanUtils.changeToNewTestNacosHome(ConfigDerbyRaftConfigITCase.class.getSimpleName()); } @Test - public void test_a_publish_config() throws Exception { + void testPublishConfigRaftCluster() throws Exception { boolean result = iconfig7.publishConfig("raft_test", "cluster_test_1", "this.is.raft_cluster=lessspring_7"); - Assert.assertTrue(result); + assertTrue(result); ThreadUtils.sleep(5000); ConfigurableApplicationContext context7 = applications.get("8847"); ConfigurableApplicationContext context8 = applications.get("8848"); ConfigurableApplicationContext context9 = applications.get("8849"); - + ConfigInfoPersistService operate7 = context7.getBean(EmbeddedConfigInfoPersistServiceImpl.class); ConfigInfoPersistService operate8 = context8.getBean(EmbeddedConfigInfoPersistServiceImpl.class); ConfigInfoPersistService operate9 = context9.getBean(EmbeddedConfigInfoPersistServiceImpl.class); @@ -84,24 +91,24 @@ public void test_a_publish_config() throws Exception { String s8 = operate8.findConfigInfo("raft_test", "cluster_test_1", "").getContent(); String s9 = operate9.findConfigInfo("raft_test", "cluster_test_1", "").getContent(); - Assert.assertArrayEquals("The three nodes must have consistent data", new String[] {s7, s8, s9}, + assertArrayEquals(new String[] {s7, s8, s9}, new String[] {"this.is.raft_cluster=lessspring_7", "this.is.raft_cluster=lessspring_7", - "this.is.raft_cluster=lessspring_7"}); + "this.is.raft_cluster=lessspring_7"}, "The three nodes must have consistent data"); } @Test - public void test_b_publish_config() throws Exception { + void testPublishConfigCluster() throws Exception { ThreadUtils.sleep(5000); boolean result = iconfig8.publishConfig("raft_test", "cluster_test_2", "this.is.raft_cluster=lessspring_8"); - Assert.assertTrue(result); + assertTrue(result); ThreadUtils.sleep(5000); ConfigurableApplicationContext context7 = applications.get("8847"); ConfigurableApplicationContext context8 = applications.get("8848"); ConfigurableApplicationContext context9 = applications.get("8849"); - + ConfigInfoPersistService operate7 = context7.getBean(EmbeddedConfigInfoPersistServiceImpl.class); ConfigInfoPersistService operate8 = context8.getBean(EmbeddedConfigInfoPersistServiceImpl.class); ConfigInfoPersistService operate9 = context9.getBean(EmbeddedConfigInfoPersistServiceImpl.class); @@ -110,23 +117,23 @@ public void test_b_publish_config() throws Exception { String s8 = operate8.findConfigInfo("raft_test", "cluster_test_2", "").getContent(); String s9 = operate9.findConfigInfo("raft_test", "cluster_test_2", "").getContent(); - Assert.assertArrayEquals("The three nodes must have consistent data", new String[] {s7, s8, s9}, + assertArrayEquals(new String[] {s7, s8, s9}, new String[] {"this.is.raft_cluster=lessspring_8", "this.is.raft_cluster=lessspring_8", - "this.is.raft_cluster=lessspring_8"}); + "this.is.raft_cluster=lessspring_8"}, "The three nodes must have consistent data"); } @Test - public void test_c_publish_config() throws Exception { + void testPublishConfigRaftClusterNew() throws Exception { ThreadUtils.sleep(5000); boolean result = iconfig9.publishConfig("raft_test", "cluster_test_2", "this.is.raft_cluster=lessspring_9"); - Assert.assertTrue(result); + assertTrue(result); ThreadUtils.sleep(5000); ConfigurableApplicationContext context7 = applications.get("8847"); ConfigurableApplicationContext context8 = applications.get("8848"); ConfigurableApplicationContext context9 = applications.get("8849"); - + ConfigInfoPersistService operate7 = context7.getBean(EmbeddedConfigInfoPersistServiceImpl.class); ConfigInfoPersistService operate8 = context8.getBean(EmbeddedConfigInfoPersistServiceImpl.class); ConfigInfoPersistService operate9 = context9.getBean(EmbeddedConfigInfoPersistServiceImpl.class); @@ -135,23 +142,23 @@ public void test_c_publish_config() throws Exception { String s8 = operate8.findConfigInfo("raft_test", "cluster_test_2", "").getContent(); String s9 = operate9.findConfigInfo("raft_test", "cluster_test_2", "").getContent(); - Assert.assertArrayEquals("The three nodes must have consistent data", new String[] {s7, s8, s9}, + assertArrayEquals(new String[] {s7, s8, s9}, new String[] {"this.is.raft_cluster=lessspring_9", "this.is.raft_cluster=lessspring_9", - "this.is.raft_cluster=lessspring_9"}); + "this.is.raft_cluster=lessspring_9"}, "The three nodes must have consistent data"); } @Test - public void test_d_modify_config() throws Exception { - boolean result = iconfig7 - .publishConfig("raft_test", "cluster_test_1", "this.is.raft_cluster=lessspring_7_it_is_for_modify"); - Assert.assertTrue(result); + void testModifyConfigRaftCluster() throws Exception { + boolean result = iconfig7.publishConfig("raft_test", "cluster_test_1", + "this.is.raft_cluster=lessspring_7_it_is_for_modify"); + assertTrue(result); ThreadUtils.sleep(5000); ConfigurableApplicationContext context7 = applications.get("8847"); ConfigurableApplicationContext context8 = applications.get("8848"); ConfigurableApplicationContext context9 = applications.get("8849"); - + ConfigInfoPersistService operate7 = context7.getBean(EmbeddedConfigInfoPersistServiceImpl.class); ConfigInfoPersistService operate8 = context8.getBean(EmbeddedConfigInfoPersistServiceImpl.class); ConfigInfoPersistService operate9 = context9.getBean(EmbeddedConfigInfoPersistServiceImpl.class); @@ -160,75 +167,74 @@ public void test_d_modify_config() throws Exception { String s8 = operate8.findConfigInfo("raft_test", "cluster_test_1", "").getContent(); String s9 = operate9.findConfigInfo("raft_test", "cluster_test_1", "").getContent(); - Assert.assertArrayEquals("The three nodes must have consistent data", new String[] {s7, s8, s9}, - new String[] {"this.is.raft_cluster=lessspring_7_it_is_for_modify", - "this.is.raft_cluster=lessspring_7_it_is_for_modify", - "this.is.raft_cluster=lessspring_7_it_is_for_modify"}); + assertArrayEquals(new String[] {s7, s8, s9}, new String[] {"this.is.raft_cluster=lessspring_7_it_is_for_modify", + "this.is.raft_cluster=lessspring_7_it_is_for_modify", + "this.is.raft_cluster=lessspring_7_it_is_for_modify"}, "The three nodes must have consistent data"); } @Test - public void test_l_client_operation() throws Exception { + void testClientOperationConfig() throws Exception { final String dataId = "test_l_client_operation"; final String groupId = "test_l_client_operation"; String content = "test_l_client_operation" + System.currentTimeMillis(); // publish by 8847 boolean result = iconfig7.publishConfig(dataId, groupId, content); - Assert.assertTrue(result); + assertTrue(result); ThreadUtils.sleep(5000); - String v1_7 = iconfig7.getConfig(dataId, groupId, 5000L); - String v1_8 = iconfig8.getConfig(dataId, groupId, 5000L); - String v1_9 = iconfig9.getConfig(dataId, groupId, 5000L); + String v1Config7 = iconfig7.getConfig(dataId, groupId, 5000L); + String v1Config8 = iconfig8.getConfig(dataId, groupId, 5000L); + String v1Config9 = iconfig9.getConfig(dataId, groupId, 5000L); - Assert.assertEquals(content, v1_7); - Assert.assertEquals(content, v1_8); - Assert.assertEquals(content, v1_9); + assertEquals(content, v1Config7); + assertEquals(content, v1Config8); + assertEquals(content, v1Config9); // publish by 8848 content = "test_l_client_operation" + System.currentTimeMillis(); result = iconfig8.publishConfig(dataId, groupId, content); - Assert.assertTrue(result); + assertTrue(result); ThreadUtils.sleep(5000); - String v2_7 = iconfig7.getConfig(dataId, groupId, 5000L); - String v2_8 = iconfig8.getConfig(dataId, groupId, 5000L); - String v2_9 = iconfig9.getConfig(dataId, groupId, 5000L); + String v2Config7 = iconfig7.getConfig(dataId, groupId, 5000L); + String v2Config8 = iconfig8.getConfig(dataId, groupId, 5000L); + String v2Config9 = iconfig9.getConfig(dataId, groupId, 5000L); - Assert.assertEquals(content, v2_7); - Assert.assertEquals(content, v2_8); - Assert.assertEquals(content, v2_9); + assertEquals(content, v2Config7); + assertEquals(content, v2Config8); + assertEquals(content, v2Config9); // publish by 8849 content = "test_l_client_operation" + System.currentTimeMillis(); result = iconfig9.publishConfig(dataId, groupId, content); - Assert.assertTrue(result); + assertTrue(result); ThreadUtils.sleep(5000); - String v3_7 = iconfig7.getConfig(dataId, groupId, 5000L); - String v3_8 = iconfig8.getConfig(dataId, groupId, 5000L); - String v3_9 = iconfig9.getConfig(dataId, groupId, 5000L); + String v3Config7 = iconfig7.getConfig(dataId, groupId, 5000L); + String v3Config8 = iconfig8.getConfig(dataId, groupId, 5000L); + String v3Config9 = iconfig9.getConfig(dataId, groupId, 5000L); - Assert.assertEquals(content, v3_7); - Assert.assertEquals(content, v3_8); - Assert.assertEquals(content, v3_9); + assertEquals(content, v3Config7); + assertEquals(content, v3Config8); + assertEquals(content, v3Config9); // delete by 8849 result = iconfig9.removeConfig(dataId, groupId); - Assert.assertTrue(result); + assertTrue(result); ThreadUtils.sleep(5000); - String v4_7 = iconfig7.getConfig(dataId, groupId, 5000L); - String v4_8 = iconfig8.getConfig(dataId, groupId, 5000L); - String v4_9 = iconfig9.getConfig(dataId, groupId, 5000L); + String v4Config7 = iconfig7.getConfig(dataId, groupId, 5000L); + String v4Config8 = iconfig8.getConfig(dataId, groupId, 5000L); + String v4Config9 = iconfig9.getConfig(dataId, groupId, 5000L); - Assert.assertNull(v4_7); - Assert.assertNull(v4_8); - Assert.assertNull(v4_9); + assertNull(v4Config7); + assertNull(v4Config8); + assertNull(v4Config9); } @Test - public void test_k_config_listener() throws Exception { + void testConfigListener() throws Exception { String dataId = "test_h_config_listener"; String group = "test_h_config_listener"; String content = "test_h_config_listener"; @@ -248,51 +254,52 @@ public void receiveConfigInfo(String configInfo) { ThreadUtils.sleep(10_000L); latch[0].await(10_000L, TimeUnit.MILLISECONDS); - Assert.assertEquals(content, r.get()); - Assert.assertEquals(content, iconfig7.getConfig(dataId, group, 2_000L)); + assertEquals(content, r.get()); + assertEquals(content, iconfig7.getConfig(dataId, group, 2_000L)); content = content + System.currentTimeMillis(); iconfig7.publishConfig(dataId, group, content); ThreadUtils.sleep(10_000L); latch[1].await(10_000L, TimeUnit.MILLISECONDS); - Assert.assertEquals(content, r.get()); - Assert.assertEquals(content, iconfig7.getConfig(dataId, group, 2_000L)); + assertEquals(content, r.get()); + assertEquals(content, iconfig7.getConfig(dataId, group, 2_000L)); } @Test - public void test_e_derby_ops() throws Exception { + void testDerbyOperations() throws Exception { String url = "http://127.0.0.1:8848/nacos/v1/cs/ops/derby"; Query query = Query.newInstance().addParam("sql", "select * from users"); - RestResult>> result = NACOS_REST_TEMPLATE - .get(url, Header.EMPTY, query, new GenericType>>>() { + RestResult>> result = NACOS_REST_TEMPLATE.get(url, Header.EMPTY, query, + new GenericType>>>() { }.getType()); System.out.println(result.getData()); - Assert.assertTrue(result.ok()); + assertTrue(result.ok()); List> list = result.getData(); - Assert.assertEquals(1, list.size()); - Assert.assertEquals("nacos", list.get(0).get("USERNAME")); + assertEquals(1, list.size()); + assertEquals("nacos", list.get(0).get("USERNAME")); } @Test - public void test_g_derby_ops_no_select() throws Exception { + void testDerbyOperationsNoSelect() throws Exception { String url = "http://127.0.0.1:8848/nacos/v1/cs/ops/derby"; Query query = Query.newInstance().addParam("sql", "update users set username='nacos'"); - RestResult result = NACOS_REST_TEMPLATE.get(url, Header.EMPTY, query, new GenericType>() { - }.getType()); + RestResult result = NACOS_REST_TEMPLATE.get(url, Header.EMPTY, query, + new GenericType>() { + }.getType()); System.out.println(result); - Assert.assertFalse(result.ok()); - Assert.assertEquals("Only query statements are allowed to be executed", result.getMessage()); + assertFalse(result.ok()); + assertEquals("Only query statements are allowed to be executed", result.getMessage()); } @Test - public void test_h_derby_has_error() throws Exception { + void testDerbyWithErrorHandling() throws Exception { ThreadUtils.sleep(5000); - boolean result = iconfig7 - .publishConfig("raft_test_raft_error", "cluster_test_1", "this.is.raft_cluster=lessspring_7"); - Assert.assertTrue(result); + boolean result = iconfig7.publishConfig("raft_test_raft_error", "cluster_test_1", + "this.is.raft_cluster=lessspring_7"); + assertTrue(result); NotifyCenter.registerToPublisher(RaftDbErrorRecoverEvent.class, 8); @@ -312,7 +319,7 @@ public Class subscribeType() { latch1.await(10_000L, TimeUnit.MILLISECONDS); result = iconfig7.publishConfig("raft_test_raft_error", "cluster_test_1", "this.is.raft_cluster=lessspring_7"); - Assert.assertFalse(result); + assertFalse(result); CountDownLatch latch2 = new CountDownLatch(1); NotifyCenter.registerSubscriber(new Subscriber() { @@ -331,11 +338,11 @@ public Class subscribeType() { latch2.await(10_000L, TimeUnit.MILLISECONDS); result = iconfig7.publishConfig("raft_test_raft_error", "cluster_test_1", "this.is.raft_cluster=lessspring_7"); - Assert.assertTrue(result); + assertTrue(result); } @Test - public void test_f_id_generator_leader_transfer() throws Exception { + void testIdGeneratorLeaderTransfer() throws Exception { ConfigurableApplicationContext context7 = applications.get("8847"); ConfigurableApplicationContext context8 = applications.get("8848"); ConfigurableApplicationContext context9 = applications.get("8849"); @@ -349,7 +356,6 @@ public void test_f_id_generator_leader_transfer() throws Exception { final String configGroup = PersistenceConstant.CONFIG_MODEL_RAFT_GROUP; long preId = -1L; - long currentId = -1L; if (protocol7.isLeader(configGroup)) { preId = manager7.nextId(CONFIG_INFO_ID); @@ -367,13 +373,13 @@ public void test_f_id_generator_leader_transfer() throws Exception { transfer.put(JRaftConstants.TRANSFER_LEADER, InetUtils.getSelfIP() + ":9847"); RestResult result = protocol7.execute(transfer); System.out.println(result); - Assert.assertTrue(result.ok()); + assertTrue(result.ok()); TimeUnit.SECONDS.sleep(2); - Assert.assertTrue(protocol7.isLeader(configGroup)); - currentId = manager7.nextId(CONFIG_INFO_ID); - Assert.assertNotEquals(preId, currentId); + assertTrue(protocol7.isLeader(configGroup)); + long currentId = manager7.nextId(CONFIG_INFO_ID); + assertNotEquals(preId, currentId); preId = currentId; // transfer leader to ip:8808 @@ -382,13 +388,13 @@ public void test_f_id_generator_leader_transfer() throws Exception { transfer.put(JRaftConstants.TRANSFER_LEADER, InetUtils.getSelfIP() + ":9848"); result = protocol8.execute(transfer); System.out.println(result); - Assert.assertTrue(result.ok()); + assertTrue(result.ok()); TimeUnit.SECONDS.sleep(2); - Assert.assertTrue(protocol8.isLeader(configGroup)); + assertTrue(protocol8.isLeader(configGroup)); currentId = manager8.nextId(CONFIG_INFO_ID); - Assert.assertNotEquals(preId, currentId); + assertNotEquals(preId, currentId); preId = currentId; // transfer leader to ip:8809 @@ -397,14 +403,13 @@ public void test_f_id_generator_leader_transfer() throws Exception { transfer.put(JRaftConstants.TRANSFER_LEADER, InetUtils.getSelfIP() + ":9849"); result = protocol9.execute(transfer); System.out.println(result); - Assert.assertTrue(result.ok()); + assertTrue(result.ok()); TimeUnit.SECONDS.sleep(2); - Assert.assertTrue(protocol9.isLeader(configGroup)); + assertTrue(protocol9.isLeader(configGroup)); currentId = manager9.nextId(CONFIG_INFO_ID); - Assert.assertNotEquals(preId, currentId); - + assertNotEquals(preId, currentId); } } diff --git a/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigExportAndImportAPI_CITCase.java b/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigExportAndImportAPIConfigITCase.java similarity index 82% rename from test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigExportAndImportAPI_CITCase.java rename to test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigExportAndImportAPIConfigITCase.java index 6db145e91fd..3142c5232c8 100644 --- a/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigExportAndImportAPI_CITCase.java +++ b/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigExportAndImportAPIConfigITCase.java @@ -48,16 +48,17 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import java.io.IOException; import java.lang.reflect.Type; @@ -67,6 +68,11 @@ import java.util.List; import java.util.Map; import java.util.Properties; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; /** * CITCase for ConfigExportAndImportAPI. @@ -74,11 +80,11 @@ * @author klw * @date 2019/5/23 15:26 */ -@RunWith(SpringRunner.class) +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +@ExtendWith(SpringExtension.class) @SpringBootTest(classes = Nacos.class, properties = { "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -@SuppressWarnings({"checkstyle:TypeName", "checkstyle:AbbreviationAsWordInName"}) -public class ConfigExportAndImportAPI_CITCase { +class ConfigExportAndImportAPIConfigITCase { private static final long TIME_OUT = 2000; @@ -93,15 +99,15 @@ public class ConfigExportAndImportAPI_CITCase { private NacosRestTemplate nacosRestTemplate; - @BeforeClass - @AfterClass - public static void cleanClientCache() throws Exception { + @BeforeAll + @AfterAll + static void cleanClientCache() throws Exception { ConfigCleanUtils.cleanClientCache(); - ConfigCleanUtils.changeToNewTestNacosHome(ConfigExportAndImportAPI_CITCase.class.getSimpleName()); + ConfigCleanUtils.changeToNewTestNacosHome(ConfigExportAndImportAPIConfigITCase.class.getSimpleName()); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { nacosRestTemplate = ConfigHttpClientManager.getInstance().getNacosRestTemplate(); // register a handler to process byte[] result nacosRestTemplate.registerResponseHandler(byte[].class.getName(), new AbstractResponseHandler() { @@ -126,88 +132,86 @@ public HttpRestResult convertResult(HttpClientResponse response, Type re prarm.put("content", "test: test"); prarm.put("desc", "testNoAppname1"); prarm.put("type", "yaml"); - Assert.assertEquals("true", httpPost(serverAddr + CONFIG_CONTROLLER_PATH, prarm)); + assertEquals("true", httpPost(serverAddr + CONFIG_CONTROLLER_PATH, prarm)); prarm.put("dataId", "testNoAppname2.txt"); prarm.put("group", "TEST1_GROUP"); prarm.put("content", "test: test"); prarm.put("desc", "testNoAppname2"); prarm.put("type", "text"); - Assert.assertEquals("true", httpPost(serverAddr + CONFIG_CONTROLLER_PATH, prarm)); + assertEquals("true", httpPost(serverAddr + CONFIG_CONTROLLER_PATH, prarm)); prarm.put("dataId", "testHasAppname1.properties"); prarm.put("group", "EXPORT_IMPORT_TEST_GROUP"); prarm.put("content", "test.test1.value=test"); prarm.put("desc", "testHasAppname1"); prarm.put("type", "properties"); prarm.put("appName", "testApp1"); - Assert.assertEquals("true", httpPost(serverAddr + CONFIG_CONTROLLER_PATH, prarm)); + assertEquals("true", httpPost(serverAddr + CONFIG_CONTROLLER_PATH, prarm)); } - @After - public void cleanup() throws Exception { - HttpRestResult result; - try { + @AfterEach + void cleanup() throws Exception { + Assertions.assertDoesNotThrow(() -> { Map params = new HashMap<>(); params.put("dataId", "testNoAppname1.yml"); params.put("group", "EXPORT_IMPORT_TEST_GROUP"); params.put("beta", "false"); - result = agent.httpDelete(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT); - Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); + HttpRestResult result = agent.httpDelete(CONFIG_CONTROLLER_PATH + "/", null, params, + agent.getEncode(), TIME_OUT); + assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); params.put("dataId", "testNoAppname2.txt"); params.put("group", "TEST1_GROUP"); params.put("beta", "false"); result = agent.httpDelete(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT); - Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); + assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); params.put("dataId", "testHasAppname1.properties"); params.put("group", "EXPORT_IMPORT_TEST_GROUP"); params.put("beta", "false"); result = agent.httpDelete(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT); - Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); + assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); params.put("dataId", "test1.yml"); params.put("group", "TEST_IMPORT"); params.put("beta", "false"); result = agent.httpDelete(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT); - Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); + assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); params.put("dataId", "test2.txt"); params.put("group", "TEST_IMPORT"); params.put("beta", "false"); result = agent.httpDelete(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT); - Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); + assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); params.put("dataId", "test3.properties"); params.put("group", "TEST_IMPORT"); params.put("beta", "false"); result = agent.httpDelete(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT); - Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); + assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); params.put("dataId", "test1"); params.put("group", "TEST_IMPORT2"); params.put("beta", "false"); result = agent.httpDelete(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT); - Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); + assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); params.put("dataId", "test3"); params.put("group", "TEST_IMPORT2"); params.put("beta", "false"); result = agent.httpDelete(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT); - Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); + assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); params.put("dataId", "test4"); params.put("group", "TEST_IMPORT2"); params.put("beta", "false"); result = agent.httpDelete(CONFIG_CONTROLLER_PATH + "/", null, params, agent.getEncode(), TIME_OUT); - Assert.assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); - } catch (Exception e) { - Assert.fail(); - } + assertEquals(HttpURLConnection.HTTP_OK, result.getCode()); + }); agent.shutdown(); } - @Test() - public void testExportByIds() { + @Test + void testExportByIds() { String getDataUrl = "?search=accurate&dataId=&group=&appName=&config_tags=&pageNo=1&pageSize=10&tenant=&namespaceId="; String queryResult = httpGetString(serverAddr + CONFIG_CONTROLLER_PATH + getDataUrl, null); JsonNode resultObj = JacksonUtils.toObj(queryResult); @@ -221,76 +225,79 @@ public void testExportByIds() { byte[] zipData = httpGetBytes(serverAddr + CONFIG_CONTROLLER_PATH + exportByIdsUrl, null); ZipUtils.UnZipResult unZiped = ZipUtils.unzip(zipData); List zipItemList = unZiped.getZipItemList(); - Assert.assertEquals(2, zipItemList.size()); + assertEquals(2, zipItemList.size()); String config1Name = config1.get("group").textValue() + "/" + config1.get("dataId").textValue(); String config2Name = config2.get("group").textValue() + "/" + config2.get("dataId").textValue(); for (ZipUtils.ZipItem zipItem : zipItemList) { if (!(config1Name.equals(zipItem.getItemName()) || config2Name.equals(zipItem.getItemName()))) { - Assert.fail(); + fail(); } } } - @Test(timeout = 3 * TIME_OUT) - public void testExportByGroup() { + @Test + @Timeout(value = 3 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + void testExportByGroup() { String getDataUrl = "?search=accurate&dataId=&group=EXPORT_IMPORT_TEST_GROUP&appName=&config_tags=&pageNo=1&pageSize=10&tenant=&namespaceId="; String queryResult = httpGetString(serverAddr + CONFIG_CONTROLLER_PATH + getDataUrl, null); JsonNode resultObj = JacksonUtils.toObj(queryResult); JsonNode resultConfigs = resultObj.get("pageItems"); - Assert.assertEquals(2, resultConfigs.size()); + assertEquals(2, resultConfigs.size()); JsonNode config1 = resultConfigs.get(0); JsonNode config2 = resultConfigs.get(1); String exportByIdsUrl = "?export=true&tenant=&group=EXPORT_IMPORT_TEST_GROUP&appName=&ids="; byte[] zipData = httpGetBytes(serverAddr + CONFIG_CONTROLLER_PATH + exportByIdsUrl, null); ZipUtils.UnZipResult unZiped = ZipUtils.unzip(zipData); List zipItemList = unZiped.getZipItemList(); - Assert.assertEquals(2, zipItemList.size()); + assertEquals(2, zipItemList.size()); String config1Name = config1.get("group").textValue() + "/" + config1.get("dataId").textValue(); String config2Name = config2.get("group").textValue() + "/" + config2.get("dataId").textValue(); for (ZipUtils.ZipItem zipItem : zipItemList) { if (!(config1Name.equals(zipItem.getItemName()) || config2Name.equals(zipItem.getItemName()))) { - Assert.fail(); + fail(); } } // verification metadata Map metaData = processMetaData(unZiped.getMetaDataItem()); String metaDataName = packageMetaName("EXPORT_IMPORT_TEST_GROUP", "testHasAppname1.properties"); String appName = metaData.get(metaDataName); - Assert.assertNotNull(appName); - Assert.assertEquals("testApp1", appName); + assertNotNull(appName); + assertEquals("testApp1", appName); } - @Test(timeout = 3 * TIME_OUT) - public void testExportByGroupAndApp() { + @Test + @Timeout(value = 3 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + void testExportByGroupAndApp() { String getDataUrl = "?search=accurate&dataId=&group=EXPORT_IMPORT_TEST_GROUP&appName=testApp1&config_tags=" + "&pageNo=1&pageSize=10&tenant=&namespaceId="; String queryResult = httpGetString(serverAddr + CONFIG_CONTROLLER_PATH + getDataUrl, null); JsonNode resultObj = JacksonUtils.toObj(queryResult); JsonNode resultConfigs = resultObj.get("pageItems"); - Assert.assertEquals(1, resultConfigs.size()); + assertEquals(1, resultConfigs.size()); JsonNode config1 = resultConfigs.get(0); String exportByIdsUrl = "?export=true&tenant=&group=EXPORT_IMPORT_TEST_GROUP&appName=testApp1&ids="; byte[] zipData = httpGetBytes(serverAddr + CONFIG_CONTROLLER_PATH + exportByIdsUrl, null); ZipUtils.UnZipResult unZiped = ZipUtils.unzip(zipData); List zipItemList = unZiped.getZipItemList(); - Assert.assertEquals(1, zipItemList.size()); + assertEquals(1, zipItemList.size()); String config1Name = config1.get("group").textValue() + "/" + config1.get("dataId").textValue(); for (ZipUtils.ZipItem zipItem : zipItemList) { if (!config1Name.equals(zipItem.getItemName())) { - Assert.fail(); + fail(); } } // verification metadata Map metaData = processMetaData(unZiped.getMetaDataItem()); String metaDataName = packageMetaName("EXPORT_IMPORT_TEST_GROUP", "testHasAppname1.properties"); String appName = metaData.get(metaDataName); - Assert.assertNotNull(appName); - Assert.assertEquals("testApp1", appName); + assertNotNull(appName); + assertEquals("testApp1", appName); } - @Test(timeout = 3 * TIME_OUT) - public void testExportAll() { + @Test + @Timeout(value = 3 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + void testExportAll() { String exportByIdsUrl = "?export=true&tenant=&group=&appName=&ids="; byte[] zipData = httpGetBytes(serverAddr + CONFIG_CONTROLLER_PATH + exportByIdsUrl, null); ZipUtils.UnZipResult unZiped = ZipUtils.unzip(zipData); @@ -305,17 +312,18 @@ public void testExportAll() { successCount++; } } - Assert.assertEquals(3, successCount); + assertEquals(3, successCount); // verification metadata Map metaData = processMetaData(unZiped.getMetaDataItem()); String metaDataName = packageMetaName("EXPORT_IMPORT_TEST_GROUP", "testHasAppname1.properties"); String appName = metaData.get(metaDataName); - Assert.assertNotNull(appName); - Assert.assertEquals("testApp1", appName); + assertNotNull(appName); + assertEquals("testApp1", appName); } - @Test(timeout = 3 * TIME_OUT) - public void testImport() { + @Test + @Timeout(value = 3 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + void testImport() { List zipItemList = new ArrayList<>(3); zipItemList.add(new ZipUtils.ZipItem("TEST_IMPORT/test1.yml", "test: test1")); zipItemList.add(new ZipUtils.ZipItem("TEST_IMPORT/test2.txt", "test: test1")); @@ -335,32 +343,32 @@ public void testImport() { // test unrecognizedData JsonNode importResObj = JacksonUtils.toObj(importResult); int unrecognizedCount = importResObj.get("data").get("unrecognizedCount").intValue(); - Assert.assertEquals(1, unrecognizedCount); + assertEquals(1, unrecognizedCount); JsonNode unrecognizedData = importResObj.get("data").get("unrecognizedData").get(0); - Assert.assertEquals("TEST_IMPORT/SUB_GROUP/test5.properties", unrecognizedData.get("itemName").textValue()); + assertEquals("TEST_IMPORT/SUB_GROUP/test5.properties", unrecognizedData.get("itemName").textValue()); String getDataUrl = "?search=accurate&dataId=&group=TEST_IMPORT&appName=&config_tags=&pageNo=1&pageSize=10&tenant=&namespaceId="; String queryResult = httpGetString(serverAddr + CONFIG_CONTROLLER_PATH + getDataUrl, null); JsonNode resultObj = JacksonUtils.toObj(queryResult); JsonNode resultConfigs = resultObj.get("pageItems"); - Assert.assertEquals(3, resultConfigs.size()); + assertEquals(3, resultConfigs.size()); for (int i = 0; i < resultConfigs.size(); i++) { JsonNode config = resultConfigs.get(i); if (!"TEST_IMPORT".equals(config.get("group").textValue())) { - Assert.fail(); + fail(); } switch (config.get("dataId").textValue()) { case "test1.yml": - Assert.assertEquals(config.get("appName").textValue(), "testApp1"); + assertEquals("testApp1", config.get("appName").textValue()); break; case "test2.txt": - Assert.assertEquals(config.get("appName").textValue(), "testApp2"); + assertEquals("testApp2", config.get("appName").textValue()); break; case "test3.properties": - Assert.assertEquals(config.get("appName").textValue(), "testApp3"); + assertEquals("testApp3", config.get("appName").textValue()); break; default: - Assert.fail(); + fail(); } } @@ -368,9 +376,9 @@ public void testImport() { queryResult = httpGetString(serverAddr + CONFIG_CONTROLLER_PATH + getDataUrl, null); resultObj = JacksonUtils.toObj(queryResult); resultConfigs = resultObj.get("pageItems"); - Assert.assertEquals(1, resultConfigs.size()); + assertEquals(1, resultConfigs.size()); JsonNode jsonNode = resultConfigs.get(0); - Assert.assertEquals(jsonNode.get("appName").textValue(), "testApp4"); + assertEquals("testApp4", jsonNode.get("appName").textValue()); } private Map processMetaData(ZipUtils.ZipItem metaDataZipItem) { @@ -380,7 +388,7 @@ private Map processMetaData(ZipUtils.ZipItem metaDataZipItem) { String[] metaDataArr = metaDataStr.split("\r\n"); for (String metaDataItem : metaDataArr) { String[] metaDataItemArr = metaDataItem.split("="); - Assert.assertEquals(2, metaDataItemArr.length); + assertEquals(2, metaDataItemArr.length); metaDataMap.put(metaDataItemArr[0], metaDataItemArr[1]); } } @@ -397,7 +405,7 @@ private String packageMetaName(String group, String dataId) { } @Test - public void testExportV2() { + void testExportV2() { String dataId = "testNoAppname2.txt"; String getDataUrl = "?search=accurate&group=TEST1_GROUP&pageNo=1&pageSize=10&tenant=&namespaceId=&dataId=" + dataId; @@ -410,28 +418,28 @@ public void testExportV2() { byte[] zipData = httpGetBytes(serverAddr + CONFIG_CONTROLLER_PATH + exportByIdsUrl, null); ZipUtils.UnZipResult unZiped = ZipUtils.unzip(zipData); List zipItemList = unZiped.getZipItemList(); - Assert.assertEquals(1, zipItemList.size()); + assertEquals(1, zipItemList.size()); String config1Name = config1.get("group").textValue() + "/" + config1.get("dataId").textValue(); for (ZipUtils.ZipItem zipItem : zipItemList) { if (!(config1Name.equals(zipItem.getItemName()))) { - Assert.fail(); + fail(); } } - Assert.assertEquals(dataId, config1.get("dataId").asText()); + assertEquals(dataId, config1.get("dataId").asText()); String group = config1.get("group").asText(); String queryConfigDetailResult = httpGetString( serverAddr + CONFIG_CONTROLLER_PATH + "?show=all&dataId=" + dataId + "&group=" + group, null); JsonNode configDetailResult = JacksonUtils.toObj(queryConfigDetailResult); - Assert.assertNotNull(configDetailResult); + assertNotNull(configDetailResult); // verification metadata ZipUtils.ZipItem metaDataItem = unZiped.getMetaDataItem(); - Assert.assertNotNull(metaDataItem); + assertNotNull(metaDataItem); String metaDataItemItemData = metaDataItem.getItemData(); ConfigMetadata configMetadata = YamlParserUtil.loadObject(metaDataItemItemData, ConfigMetadata.class); - Assert.assertNotNull(configMetadata); - Assert.assertEquals(configMetadata.getMetadata().size(), 1); + assertNotNull(configMetadata); + assertEquals(1, configMetadata.getMetadata().size()); ConfigMetadata.ConfigExportItem config1Metadata = new ConfigMetadata.ConfigExportItem(); config1Metadata.setDataId(dataId); @@ -443,11 +451,11 @@ public void testExportV2() { configDetailResult.get("desc") == null ? null : configDetailResult.get("desc").asText()); ConfigMetadata.ConfigExportItem configExportItem1 = configMetadata.getMetadata().get(0); - Assert.assertEquals(configExportItem1, config1Metadata); + assertEquals(configExportItem1, config1Metadata); } @Test - public void testImportV2() { + void testImportV2() { List zipItemList = new ArrayList<>(3); zipItemList.add(new ZipUtils.ZipItem("TEST_IMPORT2/test1", "test: test1")); String metaDataStr = "metadata:\n" + "- appName: testAppName\n" + " dataId: test1\n" + " desc: testDesc\n" @@ -461,22 +469,22 @@ public void testImportV2() { "testImport.zip", ZipUtils.zip(zipItemList)); JsonNode importResObj = JacksonUtils.toObj(importResult); - Assert.assertEquals(importResObj.get("data").get("succCount").asInt(), 1); + assertEquals(1, importResObj.get("data").get("succCount").asInt()); String queryConfigDetailResult = httpGetString( serverAddr + CONFIG_CONTROLLER_PATH + "?show=all&dataId=test1&group=TEST_IMPORT2", null); JsonNode configDetailResult = JacksonUtils.toObj(queryConfigDetailResult); - Assert.assertNotNull(configDetailResult); + assertNotNull(configDetailResult); - Assert.assertEquals(configDetailResult.get("dataId").asText(), "test1"); - Assert.assertEquals(configDetailResult.get("group").asText(), "TEST_IMPORT2"); - Assert.assertEquals(configDetailResult.get("type").asText(), "yaml"); - Assert.assertEquals(configDetailResult.get("appName").asText(), "testAppName"); - Assert.assertEquals(configDetailResult.get("desc").asText(), "testDesc"); + assertEquals("test1", configDetailResult.get("dataId").asText()); + assertEquals("TEST_IMPORT2", configDetailResult.get("group").asText()); + assertEquals("yaml", configDetailResult.get("type").asText()); + assertEquals("testAppName", configDetailResult.get("appName").asText()); + assertEquals("testDesc", configDetailResult.get("desc").asText()); } @Test - public void testImportV2MetadataError() { + void testImportV2MetadataError() { List zipItemList = new ArrayList<>(3); zipItemList.add(new ZipUtils.ZipItem("TEST_IMPORT2/test2", "test: test2")); String metaDataStr = @@ -491,12 +499,12 @@ public void testImportV2MetadataError() { "testImport.zip", ZipUtils.zip(zipItemList)); JsonNode importResObj = JacksonUtils.toObj(importResult); - Assert.assertEquals(importResObj.get("code").intValue(), ResultCodeEnum.METADATA_ILLEGAL.getCode()); - Assert.assertEquals(importResObj.get("message").textValue(), ResultCodeEnum.METADATA_ILLEGAL.getCodeMsg()); + assertEquals(importResObj.get("code").intValue(), ResultCodeEnum.METADATA_ILLEGAL.getCode()); + assertEquals(importResObj.get("message").textValue(), ResultCodeEnum.METADATA_ILLEGAL.getCodeMsg()); } @Test - public void testImportV2MetadataNotFind() { + void testImportV2MetadataNotFind() { List zipItemList = new ArrayList<>(3); zipItemList.add(new ZipUtils.ZipItem("TEST_IMPORT2/test3.yml", "test: test3")); String metaDataStr = "metadata:\n" + "- dataId: notExist\n" + " group: TEST_IMPORT2\n" + " type: yaml\n" @@ -511,17 +519,17 @@ public void testImportV2MetadataNotFind() { JsonNode importResObj = JacksonUtils.toObj(importResult); JsonNode data = importResObj.get("data"); - Assert.assertEquals(1, data.get("succCount").intValue()); + assertEquals(1, data.get("succCount").intValue()); // test unrecognizedData int unrecognizedCount = data.get("unrecognizedCount").intValue(); - Assert.assertEquals(1, unrecognizedCount); + assertEquals(1, unrecognizedCount); JsonNode unrecognizedData = data.get("unrecognizedData").get(0); - Assert.assertEquals("未在文件中找到: TEST_IMPORT2/notExist", unrecognizedData.get("itemName").textValue()); + assertEquals("未在文件中找到: TEST_IMPORT2/notExist", unrecognizedData.get("itemName").textValue()); } @Test - public void testImportV2ConfigIgnore() { + void testImportV2ConfigIgnore() { List zipItemList = new ArrayList<>(3); zipItemList.add(new ZipUtils.ZipItem("TEST_IMPORT2/test4", "test: test4")); zipItemList.add(new ZipUtils.ZipItem("TEST_IMPORT2/ignore.yml", "test: test4")); @@ -537,12 +545,12 @@ public void testImportV2ConfigIgnore() { JsonNode importResObj = JacksonUtils.toObj(importResult); JsonNode data = importResObj.get("data"); - Assert.assertEquals(1, data.get("succCount").intValue()); + assertEquals(1, data.get("succCount").intValue()); // test unrecognizedData int unrecognizedCount = data.get("unrecognizedCount").intValue(); - Assert.assertEquals(1, unrecognizedCount); + assertEquals(1, unrecognizedCount); JsonNode unrecognizedData = data.get("unrecognizedData").get(0); - Assert.assertEquals("未在元数据中找到: TEST_IMPORT2/ignore.yml", unrecognizedData.get("itemName").textValue()); + assertEquals("未在元数据中找到: TEST_IMPORT2/ignore.yml", unrecognizedData.get("itemName").textValue()); } private String httpGetString(String url, Map param) { diff --git a/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigLongPoll_CITCase.java b/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigLongPollConfigITCase.java similarity index 70% rename from test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigLongPoll_CITCase.java rename to test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigLongPollConfigITCase.java index ddecc01ff35..89cda6199df 100644 --- a/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigLongPoll_CITCase.java +++ b/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigLongPollConfigITCase.java @@ -23,44 +23,47 @@ import com.alibaba.nacos.api.config.listener.Listener; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.test.base.ConfigCleanUtils; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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 org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.Properties; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; /** + * Integration test case for long polling configuration updates using Nacos. + * * @author liaochuntao * @date 2019-06-07 22:24 **/ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"}, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class ConfigLongPoll_CITCase { - +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +@ExtendWith(SpringExtension.class) +@SpringBootTest(classes = Nacos.class, properties = { + "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +class ConfigLongPollConfigITCase { + @LocalServerPort private int port; - + private ConfigService configService; - @BeforeClass - @AfterClass - public static void cleanClientCache() throws Exception { + @BeforeAll + @AfterAll + static void cleanClientCache() throws Exception { ConfigCleanUtils.cleanClientCache(); - ConfigCleanUtils.changeToNewTestNacosHome(ConfigLongPoll_CITCase.class.getSimpleName()); - + ConfigCleanUtils.changeToNewTestNacosHome(ConfigLongPollConfigITCase.class.getSimpleName()); + } - - @Before - public void init() throws NacosException { + + @BeforeEach + void init() throws NacosException { Properties properties = new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:" + port); properties.put(PropertyKeyConst.CONFIG_LONG_POLL_TIMEOUT, "20000"); @@ -68,44 +71,45 @@ public void init() throws NacosException { properties.put(PropertyKeyConst.MAX_RETRY, "5"); configService = NacosFactory.createConfigService(properties); } - - @After - public void destroy(){ + + @AfterEach + void destroy() { try { configService.shutDown(); - }catch (NacosException ex) { + } catch (NacosException ex) { + // ignore } } - + @Test - public void test() throws InterruptedException, NacosException { - + void test() throws InterruptedException, NacosException { + configService.addListener("test", "DEFAULT_GROUP", new Listener() { @Override public Executor getExecutor() { return null; } - + @Override public void receiveConfigInfo(String configInfo) { System.out.println(configInfo); } }); - + configService.addListener("test-1", "DEFAULT_GROUP", new Listener() { @Override public Executor getExecutor() { return null; } - + @Override public void receiveConfigInfo(String configInfo) { System.out.println(configInfo); } }); - + TimeUnit.SECONDS.sleep(10); - + } - + } diff --git a/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigLongPollReturnChanges_CITCase.java b/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigLongPollReturnChangesConfigITCase.java similarity index 68% rename from test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigLongPollReturnChanges_CITCase.java rename to test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigLongPollReturnChangesConfigITCase.java index 0047c95d6a4..2023edd621a 100644 --- a/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigLongPollReturnChanges_CITCase.java +++ b/test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigLongPollReturnChangesConfigITCase.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.test.config; import com.alibaba.nacos.Nacos; @@ -25,40 +26,44 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.client.config.listener.impl.AbstractConfigChangeListener; import com.alibaba.nacos.test.base.ConfigCleanUtils; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +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 org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"}, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class ConfigLongPollReturnChanges_CITCase { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +@ExtendWith(SpringExtension.class) +@SpringBootTest(classes = Nacos.class, properties = { + "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +class ConfigLongPollReturnChangesConfigITCase { + @LocalServerPort private int port; - + private ConfigService configService; - @BeforeClass - @AfterClass - public static void cleanClientCache() throws Exception { + @BeforeAll + @AfterAll + static void cleanClientCache() throws Exception { ConfigCleanUtils.cleanClientCache(); - ConfigCleanUtils.changeToNewTestNacosHome(ConfigLongPollReturnChanges_CITCase.class.getSimpleName()); + ConfigCleanUtils.changeToNewTestNacosHome(ConfigLongPollReturnChangesConfigITCase.class.getSimpleName()); } - - @Before - public void init() throws NacosException { + + @BeforeEach + void init() throws NacosException { Properties properties = new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:" + port); properties.put(PropertyKeyConst.CONFIG_LONG_POLL_TIMEOUT, "20000"); @@ -66,31 +71,32 @@ public void init() throws NacosException { properties.put(PropertyKeyConst.MAX_RETRY, "5"); configService = NacosFactory.createConfigService(properties); } - - @After - public void destroy(){ + + @AfterEach + void destroy() { try { configService.shutDown(); - }catch (NacosException ex) { + } catch (NacosException ex) { + // ignore } } - + @Test - public void testAdd() throws InterruptedException, NacosException { + void testAdd() throws InterruptedException, NacosException { CountDownLatch latch = new CountDownLatch(1); - + final String dataId = "test" + System.currentTimeMillis(); final String group = "DEFAULT_GROUP"; final String content = "config data"; - + configService.addListener(dataId, group, new AbstractConfigChangeListener() { @Override public void receiveConfigChange(ConfigChangeEvent event) { try { ConfigChangeItem cci = event.getChangeItem("content"); - Assert.assertNull(cci.getOldValue()); - Assert.assertEquals(content, cci.getNewValue()); - Assert.assertEquals(PropertyChangeType.ADDED, cci.getType()); + assertNull(cci.getOldValue()); + assertEquals(content, cci.getNewValue()); + assertEquals(PropertyChangeType.ADDED, cci.getType()); System.out.println(cci); } finally { latch.countDown(); @@ -98,75 +104,75 @@ public void receiveConfigChange(ConfigChangeEvent event) { } }); boolean result = configService.publishConfig(dataId, group, content); - Assert.assertTrue(result); - + assertTrue(result); + configService.getConfig(dataId, group, 50); - + latch.await(10_000L, TimeUnit.MILLISECONDS); } - + @Test - public void testModify() throws InterruptedException, NacosException { + void testModify() throws InterruptedException, NacosException { CountDownLatch latch = new CountDownLatch(1); - + final String dataId = "test" + System.currentTimeMillis(); final String group = "DEFAULT_GROUP"; final String oldData = "old data"; final String newData = "new data"; - + boolean result = configService.publishConfig(dataId, group, oldData); - - Assert.assertTrue(result); - + + assertTrue(result); + configService.addListener(dataId, group, new AbstractConfigChangeListener() { @Override public void receiveConfigChange(ConfigChangeEvent event) { try { ConfigChangeItem cci = event.getChangeItem("content"); - Assert.assertEquals(oldData, cci.getOldValue()); - Assert.assertEquals(newData, cci.getNewValue()); - Assert.assertEquals(PropertyChangeType.MODIFIED, cci.getType()); + assertEquals(oldData, cci.getOldValue()); + assertEquals(newData, cci.getNewValue()); + assertEquals(PropertyChangeType.MODIFIED, cci.getType()); System.out.println(cci); } finally { latch.countDown(); } } - + }); configService.publishConfig(dataId, group, newData); - + latch.await(10_000L, TimeUnit.MILLISECONDS); } - + @Test - public void testDelete() throws InterruptedException, NacosException { + void testDelete() throws InterruptedException, NacosException { CountDownLatch latch = new CountDownLatch(1); - + final String dataId = "test" + System.currentTimeMillis(); final String group = "DEFAULT_GROUP"; final String oldData = "old data"; - + boolean result = configService.publishConfig(dataId, group, oldData); - Assert.assertTrue(result); - + assertTrue(result); + configService.addListener(dataId, group, new AbstractConfigChangeListener() { @Override public void receiveConfigChange(ConfigChangeEvent event) { try { ConfigChangeItem cci = event.getChangeItem("content"); - Assert.assertEquals(oldData, cci.getOldValue()); - Assert.assertNull(cci.getNewValue()); - Assert.assertEquals(PropertyChangeType.DELETED, cci.getType()); + assertEquals(oldData, cci.getOldValue()); + assertNull(cci.getNewValue()); + assertEquals(PropertyChangeType.DELETED, cci.getType()); System.out.println(cci); } finally { latch.countDown(); } } - + }); configService.removeConfig(dataId, group); - + latch.await(10_000L, TimeUnit.MILLISECONDS); } - + } diff --git a/test/config-test/src/test/java/com/alibaba/nacos/test/config/EmbeddedStorageContextUtils_CITCase.java b/test/config-test/src/test/java/com/alibaba/nacos/test/config/EmbeddedStorageContextUtilsConfigITCase.java similarity index 73% rename from test/config-test/src/test/java/com/alibaba/nacos/test/config/EmbeddedStorageContextUtils_CITCase.java rename to test/config-test/src/test/java/com/alibaba/nacos/test/config/EmbeddedStorageContextUtilsConfigITCase.java index 5c8e46ebccc..35ac1795cb9 100644 --- a/test/config-test/src/test/java/com/alibaba/nacos/test/config/EmbeddedStorageContextUtils_CITCase.java +++ b/test/config-test/src/test/java/com/alibaba/nacos/test/config/EmbeddedStorageContextUtilsConfigITCase.java @@ -19,30 +19,34 @@ import com.alibaba.nacos.persistence.repository.embedded.EmbeddedStorageContextHolder; import com.alibaba.nacos.persistence.repository.embedded.sql.ModifyRequest; import com.alibaba.nacos.test.base.ConfigCleanUtils; -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.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** + * Integration test case for managing embedded storage contexts using utilities. + * * @author liaochuntao */ -public class EmbeddedStorageContextUtils_CITCase { +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +class EmbeddedStorageContextUtilsConfigITCase { - @BeforeClass - @AfterClass - public static void cleanClientCache() throws Exception { + @BeforeAll + @AfterAll + static void cleanClientCache() throws Exception { ConfigCleanUtils.cleanClientCache(); - ConfigCleanUtils.changeToNewTestNacosHome(EmbeddedStorageContextUtils_CITCase.class.getSimpleName()); + ConfigCleanUtils.changeToNewTestNacosHome(EmbeddedStorageContextUtilsConfigITCase.class.getSimpleName()); } @Test - public void test_multi_thread_sql_contexts() throws Exception { + void testMultiThreadSqlContexts() throws Exception { CountDownLatch latch = new CountDownLatch(3); ExecutorService service = Executors.newFixedThreadPool(3); @@ -55,8 +59,8 @@ public void test_multi_thread_sql_contexts() throws Exception { List list = EmbeddedStorageContextHolder.getCurrentSqlContext(); System.out.println(list); - Assert.assertEquals("test_" + j, list.get(0).getSql()); - Assert.assertEquals("test_" + j * 10, list.get(0).getSql()); + assertEquals("test_" + j, list.get(0).getSql()); + assertEquals("test_" + j * 10, list.get(0).getSql()); } finally { latch.countDown(); } diff --git a/test/config-test/src/test/java/com/alibaba/nacos/test/config/NacosConfigServiceComTlsGrpcClient_CITCase.java b/test/config-test/src/test/java/com/alibaba/nacos/test/config/NacosConfigServiceComTlsGrpcClientConfigITCase.java similarity index 66% rename from test/config-test/src/test/java/com/alibaba/nacos/test/config/NacosConfigServiceComTlsGrpcClient_CITCase.java rename to test/config-test/src/test/java/com/alibaba/nacos/test/config/NacosConfigServiceComTlsGrpcClientConfigITCase.java index b15c1e05f22..dde6a14bcf4 100644 --- a/test/config-test/src/test/java/com/alibaba/nacos/test/config/NacosConfigServiceComTlsGrpcClient_CITCase.java +++ b/test/config-test/src/test/java/com/alibaba/nacos/test/config/NacosConfigServiceComTlsGrpcClientConfigITCase.java @@ -23,14 +23,15 @@ import com.alibaba.nacos.client.config.NacosConfigService; import com.alibaba.nacos.client.config.listener.impl.AbstractConfigChangeListener; import com.alibaba.nacos.common.remote.client.RpcConstants; -import com.alibaba.nacos.core.remote.tls.RpcServerTlsConfig; import com.alibaba.nacos.test.base.ConfigCleanUtils; -import org.junit.*; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import java.io.IOException; import java.util.Properties; @@ -39,43 +40,37 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** - * use configPublishRequest for communication verification between client and server. + * Use configPublishRequest for communication verification between client and server. * * @author githubcheng2978. */ -@RunWith(SpringRunner.class) -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@SpringBootTest(classes = {Nacos.class}, - properties = { - "nacos.standalone=true", - RpcServerTlsConfig.PREFIX+".enableTls=true", - RpcServerTlsConfig.PREFIX+".compatibility=true", - RpcServerTlsConfig.PREFIX+".certChainFile=test-server-cert.pem", - RpcServerTlsConfig.PREFIX+".certPrivateKey=test-server-key.pem"}, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class NacosConfigServiceComTlsGrpcClient_CITCase { - +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +@ExtendWith(SpringExtension.class) +@TestMethodOrder(MethodName.class) +@SpringBootTest(classes = {Nacos.class}, properties = {"nacos.standalone=true", + RpcConstants.NACOS_SERVER_RPC + ".enableTls=true", RpcConstants.NACOS_SERVER_RPC + ".compatibility=true", + RpcConstants.NACOS_SERVER_RPC + ".certChainFile=test-server-cert.pem", RpcConstants.NACOS_SERVER_RPC + + ".certPrivateKey=test-server-key.pem"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +public class NacosConfigServiceComTlsGrpcClientConfigITCase { + public static AtomicInteger increment = new AtomicInteger(100); - - @LocalServerPort - private int port; - - @BeforeClass - public static void beforeClass() throws IOException { - ConfigCleanUtils.changeToNewTestNacosHome(NacosConfigServiceComTlsGrpcClient_CITCase.class.getSimpleName()); - + + @BeforeAll + static void beforeClass() throws IOException { + ConfigCleanUtils.changeToNewTestNacosHome(NacosConfigServiceComTlsGrpcClientConfigITCase.class.getSimpleName()); } - - @BeforeClass - @AfterClass - public static void cleanClientCache() throws Exception { + + @BeforeAll + @AfterAll + static void cleanClientCache() throws Exception { ConfigCleanUtils.cleanClientCache(); } - - + @Test - public void test_e_TlsServerAndPlainClient() throws Exception { + void testTlsServerAndPlainClient() throws Exception { Properties propertiesfalse = new Properties(); propertiesfalse.put(RpcConstants.RPC_CLIENT_TLS_ENABLE, "false"); propertiesfalse.put("serverAddr", "127.0.0.1"); @@ -97,6 +92,6 @@ public void receiveConfigChange(ConfigChangeEvent event) { } }); latch2.await(5, TimeUnit.SECONDS); - Assert.assertTrue(res); + assertTrue(res); } } diff --git a/test/config-test/src/test/java/com/alibaba/nacos/test/config/NacosConfigServiceNoComTlsGrpcClient_CITCase.java b/test/config-test/src/test/java/com/alibaba/nacos/test/config/NacosConfigServiceNoComTlsGrpcClientConfigITCase.java similarity index 72% rename from test/config-test/src/test/java/com/alibaba/nacos/test/config/NacosConfigServiceNoComTlsGrpcClient_CITCase.java rename to test/config-test/src/test/java/com/alibaba/nacos/test/config/NacosConfigServiceNoComTlsGrpcClientConfigITCase.java index da5ee0a6b05..760ee262bee 100644 --- a/test/config-test/src/test/java/com/alibaba/nacos/test/config/NacosConfigServiceNoComTlsGrpcClient_CITCase.java +++ b/test/config-test/src/test/java/com/alibaba/nacos/test/config/NacosConfigServiceNoComTlsGrpcClientConfigITCase.java @@ -23,16 +23,14 @@ import com.alibaba.nacos.client.config.NacosConfigService; import com.alibaba.nacos.client.config.listener.impl.AbstractConfigChangeListener; import com.alibaba.nacos.common.remote.client.RpcConstants; -import com.alibaba.nacos.core.remote.tls.RpcServerTlsConfig; import com.alibaba.nacos.test.base.ConfigCleanUtils; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import java.io.IOException; import java.util.Properties; @@ -41,39 +39,37 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** - * use configPublishRequest for communication verification between client and server. + * Use configPublishRequest for communication verification between client and server. * * @author githubcheng2978. */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = {Nacos.class}, - properties = { - "nacos.standalone=true", - RpcServerTlsConfig.PREFIX+".enableTls=true", - RpcServerTlsConfig.PREFIX+".compatibility=false", - RpcServerTlsConfig.PREFIX+".certChainFile=test-server-cert.pem", - RpcServerTlsConfig.PREFIX+".certPrivateKey=test-server-key.pem"}, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class NacosConfigServiceNoComTlsGrpcClient_CITCase { - +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +@ExtendWith(SpringExtension.class) +@SpringBootTest(classes = {Nacos.class}, properties = {"nacos.standalone=true", RpcConstants.NACOS_SERVER_RPC + ".enableTls=true", + RpcConstants.NACOS_SERVER_RPC + ".compatibility=false", RpcConstants.NACOS_SERVER_RPC + ".certChainFile=test-server-cert.pem", + RpcConstants.NACOS_SERVER_RPC + ".certPrivateKey=test-server-key.pem"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +public class NacosConfigServiceNoComTlsGrpcClientConfigITCase { + public static AtomicInteger increment = new AtomicInteger(100); - - @BeforeClass - public static void beforeClass() throws IOException { - ConfigCleanUtils.changeToNewTestNacosHome(NacosConfigServiceNoComTlsGrpcClient_CITCase.class.getSimpleName()); - + + @BeforeAll + static void beforeClass() throws IOException { + ConfigCleanUtils.changeToNewTestNacosHome(NacosConfigServiceNoComTlsGrpcClientConfigITCase.class.getSimpleName()); } - - @BeforeClass - @AfterClass - public static void cleanClientCache() throws Exception { + + @BeforeAll + @AfterAll + static void cleanClientCache() throws Exception { ConfigCleanUtils.cleanClientCache(); } - + @Test - @Ignore("TODO, Fix cert expired problem") - public void test_e_TlsServerAndTlsClient() throws Exception { + @Disabled("TODO, Fix cert expired problem") + void testTlsServerAndTlsClient() throws Exception { Properties properties = new Properties(); properties.put(RpcConstants.RPC_CLIENT_TLS_ENABLE, "true"); properties.put(RpcConstants.RPC_CLIENT_TLS_PROVIDER, "openssl"); @@ -83,7 +79,8 @@ public void test_e_TlsServerAndTlsClient() throws Exception { String content = UUID.randomUUID().toString(); String dataId = "test-group" + increment.getAndIncrement(); String groupId = "test-data" + increment.getAndIncrement(); - boolean b = configService.publishConfig("test-group" + increment.getAndIncrement(), "test-data" + increment.getAndIncrement(), content); + boolean b = configService.publishConfig("test-group" + increment.getAndIncrement(), "test-data" + increment.getAndIncrement(), + content); CountDownLatch latch = new CountDownLatch(1); configService.addListener(dataId, groupId, new AbstractConfigChangeListener() { @Override @@ -97,11 +94,11 @@ public void receiveConfigChange(ConfigChangeEvent event) { } }); latch.await(5, TimeUnit.SECONDS); - Assert.assertTrue(b); + assertTrue(b); } - + @Test - public void test_e_TlsServerAndPlainClient() throws Exception { + void testTlsServerAndPlainClient() throws Exception { Properties propertiesfalse = new Properties(); propertiesfalse.put(RpcConstants.RPC_CLIENT_TLS_ENABLE, "false"); propertiesfalse.put("serverAddr", "127.0.0.1"); @@ -123,6 +120,6 @@ public void receiveConfigChange(ConfigChangeEvent event) { } }); latch2.await(5, TimeUnit.SECONDS); - Assert.assertFalse(res); + assertFalse(res); } } diff --git a/test/config-test/src/test/java/com/alibaba/nacos/test/config/NacosConfigV2MutualAuth_CITCase.java b/test/config-test/src/test/java/com/alibaba/nacos/test/config/NacosConfigV2MutualAuthConfigITCase.java similarity index 70% rename from test/config-test/src/test/java/com/alibaba/nacos/test/config/NacosConfigV2MutualAuth_CITCase.java rename to test/config-test/src/test/java/com/alibaba/nacos/test/config/NacosConfigV2MutualAuthConfigITCase.java index b06c6d62095..5276b78d923 100644 --- a/test/config-test/src/test/java/com/alibaba/nacos/test/config/NacosConfigV2MutualAuth_CITCase.java +++ b/test/config-test/src/test/java/com/alibaba/nacos/test/config/NacosConfigV2MutualAuthConfigITCase.java @@ -14,7 +14,6 @@ * limitations under the License. */ - package com.alibaba.nacos.test.config; import com.alibaba.nacos.Nacos; @@ -24,16 +23,14 @@ import com.alibaba.nacos.client.config.NacosConfigService; import com.alibaba.nacos.client.config.listener.impl.AbstractConfigChangeListener; import com.alibaba.nacos.common.remote.client.RpcConstants; -import com.alibaba.nacos.core.remote.tls.RpcServerTlsConfig; import com.alibaba.nacos.test.base.ConfigCleanUtils; -import org.junit.After; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import java.io.IOException; import java.util.Properties; @@ -42,49 +39,45 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** - * use configPublishRequest for communication verification between client and server. + * Use configPublishRequest for communication verification between client and server. * * @author githubcheng2978. */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = {Nacos.class}, - properties = { - "nacos.standalone=true", - RpcServerTlsConfig.PREFIX+".enableTls=true", - RpcServerTlsConfig.PREFIX+".mutualAuthEnable=true", - RpcServerTlsConfig.PREFIX+".compatibility=false", - RpcServerTlsConfig.PREFIX+".certChainFile=test-server-cert.pem", - RpcServerTlsConfig.PREFIX+".certPrivateKey=test-server-key.pem", - RpcServerTlsConfig.PREFIX+".trustCollectionCertFile=test-ca-cert.pem", - - }, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class NacosConfigV2MutualAuth_CITCase { - - +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +@ExtendWith(SpringExtension.class) +@SpringBootTest(classes = {Nacos.class}, properties = {"nacos.standalone=true", RpcConstants.NACOS_SERVER_RPC + ".enableTls=true", + RpcConstants.NACOS_SERVER_RPC + ".mutualAuthEnable=true", RpcConstants.NACOS_SERVER_RPC + ".compatibility=false", + RpcConstants.NACOS_SERVER_RPC + ".certChainFile=test-server-cert.pem", + RpcConstants.NACOS_SERVER_RPC + ".certPrivateKey=test-server-key.pem", RpcConstants.NACOS_SERVER_RPC + + ".trustCollectionCertFile=test-ca-cert.pem"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +public class NacosConfigV2MutualAuthConfigITCase { + public static AtomicInteger increment = new AtomicInteger(100); - - @BeforeClass - public static void beforeClass() throws IOException { - ConfigCleanUtils.changeToNewTestNacosHome(NacosConfigV2MutualAuth_CITCase.class.getSimpleName()); - + + @BeforeAll + static void beforeClass() throws IOException { + ConfigCleanUtils.changeToNewTestNacosHome(NacosConfigV2MutualAuthConfigITCase.class.getSimpleName()); + } - - @After - public void cleanClientCache() throws Exception { + + @AfterEach + void cleanClientCache() throws Exception { ConfigCleanUtils.cleanClientCache(); } - + @Test - @Ignore("TODO, Fix cert expired problem") - public void test_d_MutualAuth() throws Exception { + @Disabled("TODO, Fix cert expired problem") + void testMutualAuth() throws Exception { Properties propertiesfalse = new Properties(); propertiesfalse.put(RpcConstants.RPC_CLIENT_TLS_ENABLE, "true"); - propertiesfalse.put(RpcConstants.RPC_CLIENT_MUTUAL_AUTH,"true"); - propertiesfalse.put(RpcConstants.RPC_CLIENT_TLS_CERT_KEY,"test-client-key.pem"); - propertiesfalse.put(RpcConstants.RPC_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH,"test-ca-cert.pem"); - propertiesfalse.put(RpcConstants.RPC_CLIENT_TLS_CERT_CHAIN_PATH,"test-client-cert.pem"); + propertiesfalse.put(RpcConstants.RPC_CLIENT_MUTUAL_AUTH, "true"); + propertiesfalse.put(RpcConstants.RPC_CLIENT_TLS_CERT_KEY, "test-client-key.pem"); + propertiesfalse.put(RpcConstants.RPC_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH, "test-ca-cert.pem"); + propertiesfalse.put(RpcConstants.RPC_CLIENT_TLS_CERT_CHAIN_PATH, "test-client-cert.pem"); propertiesfalse.put("serverAddr", "127.0.0.1"); ConfigService configServiceFalse = new NacosConfigService(propertiesfalse); String dataId = "test-group" + increment.getAndIncrement(); @@ -104,16 +97,16 @@ public void receiveConfigChange(ConfigChangeEvent event) { } }); latch2.await(5, TimeUnit.SECONDS); - Assert.assertTrue(res); + assertTrue(res); } - + @Test - public void test_d_MutualAuthButClientNot() throws Exception { - + void testMutualAuthButClientNot() throws Exception { + Properties propertiesfalse = new Properties(); propertiesfalse.put(RpcConstants.RPC_CLIENT_TLS_ENABLE, "true"); - propertiesfalse.put(RpcConstants.RPC_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH,"test-client-cert.pem"); - + propertiesfalse.put(RpcConstants.RPC_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH, "test-client-cert.pem"); + propertiesfalse.put("serverAddr", "127.0.0.1"); ConfigService configServiceFalse = new NacosConfigService(propertiesfalse); String dataId = "test-group" + increment.getAndIncrement(); @@ -133,6 +126,6 @@ public void receiveConfigChange(ConfigChangeEvent event) { } }); latch2.await(5, TimeUnit.SECONDS); - Assert.assertFalse(res); + assertFalse(res); } } diff --git a/test/config-test/src/test/java/com/alibaba/nacos/test/config/TextChangeParser.java b/test/config-test/src/test/java/com/alibaba/nacos/test/config/TextChangeParser.java index 998d6c8f8ef..c28e97749d1 100644 --- a/test/config-test/src/test/java/com/alibaba/nacos/test/config/TextChangeParser.java +++ b/test/config-test/src/test/java/com/alibaba/nacos/test/config/TextChangeParser.java @@ -25,16 +25,17 @@ import java.util.Map; public class TextChangeParser implements ConfigChangeParser { + @Override public boolean isResponsibleFor(String type) { return (null == type || "text".equalsIgnoreCase(type)); } - + @Override public Map doParse(String oldContent, String newContent, String type) throws IOException { Map map = new HashMap<>(4); final String key = "content"; - + ConfigChangeItem cci = new ConfigChangeItem(key, oldContent, newContent); if (null == oldContent && null != newContent) { cci.setType(PropertyChangeType.ADDED); @@ -44,7 +45,7 @@ public Map doParse(String oldContent, String newConten cci.setType(PropertyChangeType.DELETED); } map.put(key, cci); - + return map; } } diff --git a/test/core-test/pom.xml b/test/core-test/pom.xml index 9cdd0bcd1c6..399e4c2e7c5 100644 --- a/test/core-test/pom.xml +++ b/test/core-test/pom.xml @@ -29,6 +29,13 @@ core-test + + + org.junit.platform + junit-platform-suite-engine + test + + diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/ability/AbilityDiscovery.java b/test/core-test/src/test/java/com/alibaba/nacos/test/ability/AbilityDiscovery.java index fd22b7a8ccd..133e550e00f 100644 --- a/test/core-test/src/test/java/com/alibaba/nacos/test/ability/AbilityDiscovery.java +++ b/test/core-test/src/test/java/com/alibaba/nacos/test/ability/AbilityDiscovery.java @@ -28,7 +28,6 @@ import com.alibaba.nacos.api.naming.remote.request.NotifySubscriberRequest; import com.alibaba.nacos.api.remote.request.Request; import com.alibaba.nacos.api.remote.request.RequestMeta; -import com.alibaba.nacos.api.remote.request.SetupAckRequest; import com.alibaba.nacos.api.remote.response.Response; import com.alibaba.nacos.common.ability.AbstractAbilityControlManager; import com.alibaba.nacos.common.ability.discover.NacosAbilityManagerHolder; @@ -44,14 +43,13 @@ import com.alibaba.nacos.core.remote.RequestHandler; import com.alibaba.nacos.core.remote.RequestHandlerRegistry; import com.alibaba.nacos.test.ability.component.TestServerAbilityControlManager; -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.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import javax.annotation.Resource; import java.lang.reflect.Field; @@ -62,11 +60,15 @@ import java.util.Properties; import java.util.UUID; -@RunWith(SpringRunner.class) +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@ExtendWith(SpringExtension.class) @SpringBootTest(classes = Nacos.class, properties = { "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) @SuppressWarnings("all") -public class AbilityDiscovery { +class AbilityDiscovery { @LocalServerPort private int port; @@ -81,9 +83,9 @@ public class AbilityDiscovery { private ConnectionManager connectionManager; private RpcClient client; - + private RpcClient clusterClient; - + private ConfigService configService; private AbstractAbilityControlManager oldInstance; @@ -94,27 +96,26 @@ public class AbilityDiscovery { private volatile boolean serverSuccess = false; private volatile boolean clientSuccess = false; - + private volatile boolean clusterSuccess = false; private Field abstractAbilityControlManager; private Field registryHandlerFields; - + private Field serverReuqestHandlersField; private Field currentConnField; - + private Field setupRequestHandlerField; - @Before - public void setup() throws NoSuchFieldException, IllegalAccessException, NacosException { + @BeforeEach + void setup() throws NoSuchFieldException, IllegalAccessException, NacosException { // load class oldInstance = NacosAbilityManagerHolder.getInstance(); // replace - abstractAbilityControlManager = NacosAbilityManagerHolder.class - .getDeclaredField("abstractAbilityControlManager"); + abstractAbilityControlManager = NacosAbilityManagerHolder.class.getDeclaredField("abstractAbilityControlManager"); abstractAbilityControlManager.setAccessible(true); abstractAbilityControlManager.set(NacosAbilityManagerHolder.class, new TestServerAbilityControlManager()); @@ -130,15 +131,15 @@ public void setup() throws NoSuchFieldException, IllegalAccessException, NacosEx Properties properties = new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:" + port); configService = NacosFactory.createConfigService(properties); - + // server request handler serverReuqestHandlersField = RpcClient.class.getDeclaredField("serverRequestHandlers"); serverReuqestHandlersField.setAccessible(true); - + // setupRequestHandler setupRequestHandlerField = GrpcClient.class.getDeclaredField("setupRequestHandler"); setupRequestHandlerField.setAccessible(true); - + // init client client = RpcClientFactory.createClient(UUID.randomUUID().toString(), ConnectionType.GRPC, new HashMap<>()); client.serverListFactory(new ServerListFactory() { @@ -146,12 +147,12 @@ public void setup() throws NoSuchFieldException, IllegalAccessException, NacosEx public String genNextServer() { return "127.0.0.1:" + port; } - + @Override public String getCurrentServer() { return "127.0.0.1:" + port; } - + @Override public List getServerList() { return Collections.singletonList("127.0.0.1:" + port); @@ -159,19 +160,19 @@ public List getServerList() { }); // connect to server client.start(); - + clusterClient = RpcClientFactory.createClusterClient(UUID.randomUUID().toString(), ConnectionType.GRPC, new HashMap<>()); clusterClient.serverListFactory(new ServerListFactory() { @Override public String genNextServer() { return "127.0.0.1:" + port; } - + @Override public String getCurrentServer() { return "127.0.0.1:" + port; } - + @Override public List getServerList() { return Collections.singletonList("127.0.0.1:" + port); @@ -182,16 +183,15 @@ public List getServerList() { } @Test - public void testClientDiscovery() throws NacosException { + void testClientDiscovery() throws NacosException { // client judge ability - Assert.assertEquals(client.getConnectionAbility(AbilityKey.SERVER_TEST_1), AbilityStatus.SUPPORTED); - Assert.assertEquals(client.getConnectionAbility(AbilityKey.SERVER_TEST_2), AbilityStatus.NOT_SUPPORTED); + assertEquals(AbilityStatus.SUPPORTED, client.getConnectionAbility(AbilityKey.SERVER_TEST_1)); + assertEquals(AbilityStatus.NOT_SUPPORTED, client.getConnectionAbility(AbilityKey.SERVER_TEST_2)); } @Test - public void testServerDiscoveryAndJudge() throws Exception { - Map handlers = (Map) registryHandlerFields - .get(requestHandlerRegistry); + void testServerDiscoveryAndJudge() throws Exception { + Map handlers = (Map) registryHandlerFields.get(requestHandlerRegistry); // set handler RequestHandler oldRequestHandler = handlers.remove(ConfigQueryRequest.class.getSimpleName()); @@ -199,28 +199,29 @@ public void testServerDiscoveryAndJudge() throws Exception { configService.getConfig("test", "DEFAULT_GROUP", 2000); // wait server invoke Thread.sleep(3000); - Assert.assertTrue(serverSuccess); + assertTrue(serverSuccess); // recover handlers.remove(ConfigQueryRequest.class.getSimpleName()); handlers.put(ConfigQueryRequest.class.getSimpleName(), oldRequestHandler); } @Test - public void testClientJudge() throws Exception { + void testClientJudge() throws Exception { List handlers = (List) serverReuqestHandlersField.get(client); handlers.clear(); // register client.registerServerRequestHandler(new ServerRequestHandler() { @Override public Response requestReply(Request request, Connection connection) { - if (connection.getConnectionAbility(AbilityKey.SERVER_TEST_1).equals(AbilityStatus.SUPPORTED) && connection - .getConnectionAbility(AbilityKey.SERVER_TEST_2).equals(AbilityStatus.NOT_SUPPORTED)) { + if (connection.getConnectionAbility(AbilityKey.SERVER_TEST_1).equals(AbilityStatus.SUPPORTED) + && connection.getConnectionAbility(AbilityKey.SERVER_TEST_2).equals(AbilityStatus.NOT_SUPPORTED)) { clientSuccess = true; } - return new Response(){}; + return new Response() { + }; } }); - + // get id Connection conn = (Connection) currentConnField.get(client); @@ -233,40 +234,39 @@ public Response requestReply(Request request, Connection connection) { // wait client react Thread.sleep(4000); - Assert.assertTrue(clientSuccess); + assertTrue(clientSuccess); } - + @Test - public void testClusterClient() throws IllegalAccessException, NacosException, InterruptedException, NoSuchFieldException { - Map handlers = (Map) registryHandlerFields - .get(requestHandlerRegistry); - + void testClusterClient() throws IllegalAccessException, NacosException, InterruptedException, NoSuchFieldException { + Map handlers = (Map) registryHandlerFields.get(requestHandlerRegistry); + // set handler RequestHandler oldRequestHandler = handlers.remove(ConfigQueryRequest.class.getSimpleName()); handlers.put(ConfigQueryRequest.class.getSimpleName(), new ClusterClientRequestHandler(filters)); configService.getConfig("test", "DEFAULT_GROUP", 2000); // wait server invoke Thread.sleep(3000); - Assert.assertTrue(clusterSuccess); + assertTrue(clusterSuccess); // recover handlers.remove(ConfigQueryRequest.class.getSimpleName()); handlers.put(ConfigQueryRequest.class.getSimpleName(), oldRequestHandler); } - + @Test - public void testNegotiationTimeout() throws Exception { + void testNegotiationTimeout() throws Exception { Object origin = setupRequestHandlerField.get(client); // set null for setupRequestHandlerField setupRequestHandlerField.set(client, null); // try connect Connection connection = client.connectToServer(new RpcClient.ServerInfo("127.0.0.1", port)); - Assert.assertNull(connection); + assertNull(connection); // recovery setupRequestHandlerField.set(client, origin); } - @After - public void recover() throws IllegalAccessException, NacosException { + @AfterEach + void recover() throws IllegalAccessException, NacosException { abstractAbilityControlManager.set(NacosAbilityManagerHolder.class, oldInstance); client.shutdown(); } @@ -290,18 +290,18 @@ public ConfigQueryResponse handle(ConfigQueryRequest request, RequestMeta meta) return new ConfigQueryResponse(); } } - + /** * just to test ability. */ class ClusterClientRequestHandler extends RequestHandler { - + public ClusterClientRequestHandler(RequestFilters requestFilters) throws NoSuchFieldException, IllegalAccessException { Field declaredField = RequestHandler.class.getDeclaredField("requestFilters"); declaredField.setAccessible(true); declaredField.set(this, requestFilters); } - + @Override public ConfigQueryResponse handle(ConfigQueryRequest request, RequestMeta meta) throws NacosException { if (meta.getConnectionAbility(AbilityKey.CLUSTER_CLIENT_TEST_1).equals(AbilityStatus.SUPPORTED)) { diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/ability/component/TestServerAbilityControlManager.java b/test/core-test/src/test/java/com/alibaba/nacos/test/ability/component/TestServerAbilityControlManager.java index fccc8b22a33..5a7a1a5c097 100644 --- a/test/core-test/src/test/java/com/alibaba/nacos/test/ability/component/TestServerAbilityControlManager.java +++ b/test/core-test/src/test/java/com/alibaba/nacos/test/ability/component/TestServerAbilityControlManager.java @@ -24,19 +24,19 @@ import java.util.Map; public class TestServerAbilityControlManager extends ServerAbilityControlManager { - + @Override protected Map> initCurrentNodeAbilities() { Map map = new HashMap<>(); map.put(AbilityKey.SERVER_TEST_1, true); map.put(AbilityKey.SERVER_TEST_2, false); - HashMap res = new HashMap<>(); + HashMap> res = new HashMap<>(); res.put(AbilityMode.SERVER, map); - + Map map1 = new HashMap<>(); map1.put(AbilityKey.SDK_CLIENT_TEST_1, true); res.put(AbilityMode.SDK_CLIENT, map1); - + Map map2 = new HashMap<>(); map2.put(AbilityKey.CLUSTER_CLIENT_TEST_1, true); res.put(AbilityMode.CLUSTER_CLIENT, map2); diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/base/HttpClient4Test.java b/test/core-test/src/test/java/com/alibaba/nacos/test/base/HttpClient4Test.java index 5482f0c6fdc..fae9362f8e4 100644 --- a/test/core-test/src/test/java/com/alibaba/nacos/test/base/HttpClient4Test.java +++ b/test/core-test/src/test/java/com/alibaba/nacos/test/base/HttpClient4Test.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.test.base; import org.springframework.beans.factory.annotation.Autowired; @@ -27,41 +28,40 @@ import java.net.URL; /** - * Http client for test module + * Http client for test module. * * @author nkorange * @since 1.2.0 */ public class HttpClient4Test { - + protected URL base; - + @Autowired protected TestRestTemplate restTemplate; - + protected ResponseEntity request(String path, MultiValueMap params, Class clazz) { - + HttpHeaders headers = new HttpHeaders(); - + HttpEntity entity = new HttpEntity(headers); - + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.base.toString() + path) - .queryParams(params); - - return this.restTemplate.exchange( - builder.toUriString(), HttpMethod.GET, entity, clazz); + .queryParams(params); + + return this.restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, clazz); } - - protected ResponseEntity request(String path, MultiValueMap params, Class clazz, HttpMethod httpMethod) { - + + protected ResponseEntity request(String path, MultiValueMap params, Class clazz, + HttpMethod httpMethod) { + HttpHeaders headers = new HttpHeaders(); - + HttpEntity entity = new HttpEntity(headers); - + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.base.toString() + path) - .queryParams(params); - - return this.restTemplate.exchange( - builder.toUriString(), httpMethod, entity, clazz); + .queryParams(params); + + return this.restTemplate.exchange(builder.toUriString(), httpMethod, entity, clazz); } } diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/base/Params.java b/test/core-test/src/test/java/com/alibaba/nacos/test/base/Params.java index 9b3654eff23..ea8583d4e77 100644 --- a/test/core-test/src/test/java/com/alibaba/nacos/test/base/Params.java +++ b/test/core-test/src/test/java/com/alibaba/nacos/test/base/Params.java @@ -13,29 +13,49 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.test.base; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; /** + * Utility class for building HTTP request parameters. + * * @author nkorange */ public class Params { - + private MultiValueMap paramMap; - + + /** + * Creates a new Params instance. + * + * @return A new Params instance. + */ public static Params newParams() { Params params = new Params(); params.paramMap = new LinkedMultiValueMap(); return params; } - + + /** + * Appends a parameter to the parameter map. + * + * @param name The name of the parameter. + * @param value The value of the parameter. + * @return This Params instance for method chaining. + */ public Params appendParam(String name, String value) { this.paramMap.add(name, value); return this; } - + + /** + * Retrieves the built parameter map. + * + * @return The built MultiValueMap containing all appended parameters. + */ public MultiValueMap done() { return paramMap; } diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/base/TextChangeParser.java b/test/core-test/src/test/java/com/alibaba/nacos/test/base/TextChangeParser.java index 277b1680413..18ed6107e52 100644 --- a/test/core-test/src/test/java/com/alibaba/nacos/test/base/TextChangeParser.java +++ b/test/core-test/src/test/java/com/alibaba/nacos/test/base/TextChangeParser.java @@ -25,16 +25,17 @@ import java.util.Map; public class TextChangeParser implements ConfigChangeParser { + @Override public boolean isResponsibleFor(String type) { return (null == type || "text".equalsIgnoreCase(type)); } - + @Override public Map doParse(String oldContent, String newContent, String type) throws IOException { Map map = new HashMap<>(4); final String key = "content"; - + ConfigChangeItem cci = new ConfigChangeItem(key, oldContent, newContent); if (null == oldContent && null != newContent) { cci.setType(PropertyChangeType.ADDED); @@ -44,7 +45,7 @@ public Map doParse(String oldContent, String newConten cci.setType(PropertyChangeType.DELETED); } map.put(key, cci); - + return map; } } diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/client/ConfigIntegrationV1ServerNonCompatibility_CITCase.java b/test/core-test/src/test/java/com/alibaba/nacos/test/client/ConfigIntegrationV1ServerNonCompatibilityCoreITCase.java similarity index 67% rename from test/core-test/src/test/java/com/alibaba/nacos/test/client/ConfigIntegrationV1ServerNonCompatibility_CITCase.java rename to test/core-test/src/test/java/com/alibaba/nacos/test/client/ConfigIntegrationV1ServerNonCompatibilityCoreITCase.java index 74a4d18b423..ff966b3e853 100644 --- a/test/core-test/src/test/java/com/alibaba/nacos/test/client/ConfigIntegrationV1ServerNonCompatibility_CITCase.java +++ b/test/core-test/src/test/java/com/alibaba/nacos/test/client/ConfigIntegrationV1ServerNonCompatibilityCoreITCase.java @@ -14,7 +14,6 @@ * limitations under the License. */ - package com.alibaba.nacos.test.client; import com.alibaba.nacos.Nacos; @@ -25,18 +24,15 @@ import com.alibaba.nacos.common.remote.client.RpcClient; import com.alibaba.nacos.common.remote.client.RpcClientFactory; import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig; -import com.alibaba.nacos.core.remote.tls.RpcServerTlsConfig; +import com.alibaba.nacos.common.remote.client.RpcConstants; import com.alibaba.nacos.test.ConfigCleanUtils; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.junit4.SpringRunner; import java.io.IOException; import java.util.Collections; @@ -44,95 +40,96 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** - * use configPublishRequest for communication verification between client and server + * use configPublishRequest for communication verification between client and server. * * @author githubcheng2978 */ -@RunWith(SpringRunner.class) +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") @TestConfiguration -@SpringBootTest(classes = {Nacos.class}, - properties = { - "server.servlet.context-path=/nacos", - RpcServerTlsConfig.PREFIX+".compatibility=false", - RpcServerTlsConfig.PREFIX+".enableTls=true", - RpcServerTlsConfig.PREFIX+".certChainFile=test-server-cert.pem", - RpcServerTlsConfig.PREFIX+".certPrivateKey=test-server-key.pem", - }, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -@Ignore("TODO, Fix cert expired problem") -public class ConfigIntegrationV1ServerNonCompatibility_CITCase { - +@SpringBootTest(classes = {Nacos.class}, properties = {"server.servlet.context-path=/nacos", + RpcConstants.NACOS_SERVER_RPC + ".compatibility=false", RpcConstants.NACOS_SERVER_RPC + ".enableTls=true", + RpcConstants.NACOS_SERVER_RPC + ".certChainFile=test-server-cert.pem", RpcConstants.NACOS_SERVER_RPC + + ".certPrivateKey=test-server-key.pem"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +@Disabled("TODO, Fix cert expired problem") +public class ConfigIntegrationV1ServerNonCompatibilityCoreITCase { + public static AtomicInteger increment = new AtomicInteger(100); + @LocalServerPort private int port; - - @BeforeClass - public static void beforeClass() throws IOException { - ConfigCleanUtils.changeToNewTestNacosHome(ConfigIntegrationV1ServerNonCompatibility_CITCase.class.getSimpleName()); + + @BeforeAll + static void beforeClass() throws IOException { + ConfigCleanUtils.changeToNewTestNacosHome( + ConfigIntegrationV1ServerNonCompatibilityCoreITCase.class.getSimpleName()); } - - @BeforeClass - @AfterClass - public static void cleanClientCache() throws Exception { + + @BeforeAll + @AfterAll + static void cleanClientCache() throws Exception { ConfigCleanUtils.cleanClientCache(); } - + @Test - public void test_a_TlsServer() throws Exception { - RpcClient client = RpcClientFactory.createClient("testTlsServer", ConnectionType.GRPC, Collections.singletonMap("labelKey", "labelValue"), null); + void testTlsServer() throws Exception { + RpcClient client = RpcClientFactory.createClient("testTlsServer", ConnectionType.GRPC, + Collections.singletonMap("labelKey", "labelValue"), null); RpcClient.ServerInfo serverInfo = new RpcClient.ServerInfo(); serverInfo.setServerIp("127.0.0.1"); serverInfo.setServerPort(port); - + Connection connection = client.connectToServer(serverInfo); - Assert.assertNull(connection); + assertNull(connection); } - - + @Test - public void test_b_ServerTlsTrustAll() throws Exception { - + void testServerTlsTrustAll() throws Exception { RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig(); tlsConfig.setEnableTls(true); tlsConfig.setTrustAll(true); RpcClient.ServerInfo serverInfo = new RpcClient.ServerInfo(); serverInfo.setServerIp("127.0.0.1"); serverInfo.setServerPort(port); - - RpcClient clientTrustCa = RpcClientFactory.createClient("testServerTlsTrustCa", ConnectionType.GRPC, Collections.singletonMap("labelKey", "labelValue"), tlsConfig); + + RpcClient clientTrustCa = RpcClientFactory.createClient("testServerTlsTrustCa", ConnectionType.GRPC, + Collections.singletonMap("labelKey", "labelValue"), tlsConfig); Connection connectionTrustCa = clientTrustCa.connectToServer(serverInfo); ConfigPublishRequest configPublishRequest = new ConfigPublishRequest(); String content = UUID.randomUUID().toString(); configPublishRequest.setContent(content); configPublishRequest.setGroup("test-group" + increment.getAndIncrement()); configPublishRequest.setDataId("test-data" + increment.getAndIncrement()); - + Response response = connectionTrustCa.request(configPublishRequest, TimeUnit.SECONDS.toMillis(3)); - Assert.assertTrue(response.isSuccess()); + assertTrue(response.isSuccess()); connectionTrustCa.close(); } - + @Test - public void test_c_ServerTlsTrustCa() throws Exception { - + void testServerTlsTrustCa() throws Exception { + RpcClient.ServerInfo serverInfo = new RpcClient.ServerInfo(); serverInfo.setServerIp("127.0.0.1"); serverInfo.setServerPort(port); - + RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig(); tlsConfig.setEnableTls(true); tlsConfig.setTrustCollectionCertFile("test-ca-cert.pem"); - RpcClient clientTrustCa = RpcClientFactory.createClient("testServerTlsTrustCa", ConnectionType.GRPC, Collections.singletonMap("labelKey", "labelValue"), tlsConfig); + RpcClient clientTrustCa = RpcClientFactory.createClient("testServerTlsTrustCa", ConnectionType.GRPC, + Collections.singletonMap("labelKey", "labelValue"), tlsConfig); Connection connectionTrustCa = clientTrustCa.connectToServer(serverInfo); ConfigPublishRequest configPublishRequestCa = new ConfigPublishRequest(); String contentCa = UUID.randomUUID().toString(); - + configPublishRequestCa.setContent(contentCa); configPublishRequestCa.setGroup("test-group" + increment.getAndIncrement()); configPublishRequestCa.setDataId("test-data" + increment.getAndIncrement()); Response responseCa = connectionTrustCa.request(configPublishRequestCa, TimeUnit.SECONDS.toMillis(3)); - Assert.assertTrue(responseCa.isSuccess()); + assertTrue(responseCa.isSuccess()); connectionTrustCa.close(); } } diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/client/ConfigIntegrationV2MutualAuth_CITCase.java b/test/core-test/src/test/java/com/alibaba/nacos/test/client/ConfigIntegrationV2MutualAuthCoreITCase.java similarity index 61% rename from test/core-test/src/test/java/com/alibaba/nacos/test/client/ConfigIntegrationV2MutualAuth_CITCase.java rename to test/core-test/src/test/java/com/alibaba/nacos/test/client/ConfigIntegrationV2MutualAuthCoreITCase.java index 2d28d0621e5..02ffef48dbb 100644 --- a/test/core-test/src/test/java/com/alibaba/nacos/test/client/ConfigIntegrationV2MutualAuth_CITCase.java +++ b/test/core-test/src/test/java/com/alibaba/nacos/test/client/ConfigIntegrationV2MutualAuthCoreITCase.java @@ -14,7 +14,6 @@ * limitations under the License. */ - package com.alibaba.nacos.test.client; import com.alibaba.nacos.Nacos; @@ -25,13 +24,14 @@ import com.alibaba.nacos.common.remote.client.RpcClient; import com.alibaba.nacos.common.remote.client.RpcClientFactory; import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig; -import com.alibaba.nacos.core.remote.tls.RpcServerTlsConfig; +import com.alibaba.nacos.common.remote.client.RpcConstants; import com.alibaba.nacos.test.ConfigCleanUtils; -import org.junit.*; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.junit4.SpringRunner; import java.io.IOException; import java.util.Collections; @@ -39,85 +39,84 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** - * use configPublishRequest for communication verification between client and server + * use configPublishRequest for communication verification between client and server. * * @author githubcheng2978 */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = {Nacos.class}, - properties = { - "nacos.standalone=true", - RpcServerTlsConfig.PREFIX+".mutualAuthEnable=true", - RpcServerTlsConfig.PREFIX+".compatibility=false", - RpcServerTlsConfig.PREFIX+".enableTls=true", - RpcServerTlsConfig.PREFIX+".certChainFile=test-server-cert.pem", - RpcServerTlsConfig.PREFIX+".certPrivateKey=test-server-key.pem", - RpcServerTlsConfig.PREFIX+".trustCollectionCertFile=test-ca-cert.pem", - - }, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class ConfigIntegrationV2MutualAuth_CITCase { - +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +@SpringBootTest(classes = {Nacos.class}, properties = {"nacos.standalone=true", + RpcConstants.NACOS_SERVER_RPC + ".mutualAuthEnable=true", + RpcConstants.NACOS_SERVER_RPC + ".compatibility=false", RpcConstants.NACOS_SERVER_RPC + ".enableTls=true", + RpcConstants.NACOS_SERVER_RPC + ".certChainFile=test-server-cert.pem", + RpcConstants.NACOS_SERVER_RPC + ".certPrivateKey=test-server-key.pem", RpcConstants.NACOS_SERVER_RPC + + ".trustCollectionCertFile=test-ca-cert.pem"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +public class ConfigIntegrationV2MutualAuthCoreITCase { + + public static AtomicInteger increment = new AtomicInteger(100); + @LocalServerPort private int port; - - public static AtomicInteger increment = new AtomicInteger(100); - - @BeforeClass - public static void beforeClass() throws IOException { - ConfigCleanUtils.changeToNewTestNacosHome(ConfigIntegrationV2MutualAuth_CITCase.class.getSimpleName()); - + + @BeforeAll + static void beforeClass() throws IOException { + ConfigCleanUtils.changeToNewTestNacosHome(ConfigIntegrationV2MutualAuthCoreITCase.class.getSimpleName()); + } - - @After - public void cleanClientCache() throws Exception { + + @AfterEach + void cleanClientCache() throws Exception { ConfigCleanUtils.cleanClientCache(); } - + @Test - @Ignore("TODO, fix the cert expired problem") - public void test_d_MutualAuth() throws Exception { - + @Disabled("TODO, fix the cert expired problem") + void testMutualAuth() throws Exception { + RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig(); tlsConfig.setEnableTls(true); tlsConfig.setMutualAuthEnable(true); tlsConfig.setCertChainFile("test-client-cert.pem"); tlsConfig.setCertPrivateKey("test-client-key.pem"); tlsConfig.setTrustCollectionCertFile("test-ca-cert.pem"); - RpcClient client = RpcClientFactory.createClient("testMutualAuth", ConnectionType.GRPC, Collections.singletonMap("labelKey", "labelValue"), tlsConfig); - + RpcClient client = RpcClientFactory.createClient("testMutualAuth", ConnectionType.GRPC, + Collections.singletonMap("labelKey", "labelValue"), tlsConfig); + RpcClient.ServerInfo serverInfo = new RpcClient.ServerInfo(); serverInfo.setServerIp("127.0.0.1"); serverInfo.setServerPort(port); - + Connection connection = client.connectToServer(serverInfo); ConfigPublishRequest configPublishRequest = new ConfigPublishRequest(); - + String content = UUID.randomUUID().toString(); - + configPublishRequest.setContent(content); - configPublishRequest.setGroup("test-group"+increment.getAndIncrement()); - configPublishRequest.setDataId("test-data"+increment.getAndIncrement()); + configPublishRequest.setGroup("test-group" + increment.getAndIncrement()); + configPublishRequest.setDataId("test-data" + increment.getAndIncrement()); configPublishRequest.setRequestId(content); Response response = connection.request(configPublishRequest, TimeUnit.SECONDS.toMillis(5)); - Assert.assertTrue(response.isSuccess()); + assertTrue(response.isSuccess()); connection.close(); } - + @Test - public void test_e_ServerMutualAuthOnly() throws Exception { - + void testServerMutualAuthOnly() throws Exception { + RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig(); tlsConfig.setEnableTls(true); tlsConfig.setTrustCollectionCertFile("test-ca-cert.pem"); - RpcClient client = RpcClientFactory.createClient("testServerMutualAuthNoly", ConnectionType.GRPC, Collections.singletonMap("labelKey", "labelValue"), tlsConfig); - + RpcClient client = RpcClientFactory.createClient("testServerMutualAuthNoly", ConnectionType.GRPC, + Collections.singletonMap("labelKey", "labelValue"), tlsConfig); + RpcClient.ServerInfo serverInfo = new RpcClient.ServerInfo(); serverInfo.setServerIp("127.0.0.1"); serverInfo.setServerPort(port); Connection connection = client.connectToServer(serverInfo); - Assert.assertNull(connection); + assertNull(connection); TimeUnit.SECONDS.sleep(3); } } diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/client/ConfigIntegrationV3_CITCase.java b/test/core-test/src/test/java/com/alibaba/nacos/test/client/ConfigIntegrationV3CoreITCase.java similarity index 70% rename from test/core-test/src/test/java/com/alibaba/nacos/test/client/ConfigIntegrationV3_CITCase.java rename to test/core-test/src/test/java/com/alibaba/nacos/test/client/ConfigIntegrationV3CoreITCase.java index 17e93a6e560..1461a350110 100644 --- a/test/core-test/src/test/java/com/alibaba/nacos/test/client/ConfigIntegrationV3_CITCase.java +++ b/test/core-test/src/test/java/com/alibaba/nacos/test/client/ConfigIntegrationV3CoreITCase.java @@ -14,7 +14,6 @@ * limitations under the License. */ - package com.alibaba.nacos.test.client; import com.alibaba.nacos.Nacos; @@ -25,14 +24,15 @@ import com.alibaba.nacos.common.remote.client.RpcClient; import com.alibaba.nacos.common.remote.client.RpcClientFactory; import com.alibaba.nacos.common.remote.client.RpcClientTlsConfig; -import com.alibaba.nacos.core.remote.tls.RpcServerTlsConfig; +import com.alibaba.nacos.common.remote.client.RpcConstants; import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.test.ConfigCleanUtils; -import org.junit.*; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.junit4.SpringRunner; import java.io.IOException; import java.util.Collections; @@ -40,70 +40,69 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** - * use configPublishRequest for communication verification between client and server + * Use configPublishRequest for communication verification between client and server. * * @author githubcheng2978 */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = {Nacos.class}, - properties = { - "nacos.standalone=true", - RpcServerTlsConfig.PREFIX+".enableTls=true", - RpcServerTlsConfig.PREFIX+".certChainFile=test-server-cert.pem", - RpcServerTlsConfig.PREFIX+".certPrivateKey=test-server-key.pem" - }, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class ConfigIntegrationV3_CITCase { - +//todo fix this test case +//ConfigIntegrationV3_CITCase and ConfigIntegrationV2MutualAuth_CITCase will fail when run together +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +@SpringBootTest(classes = {Nacos.class}, properties = {"nacos.standalone=true", + RpcConstants.NACOS_SERVER_RPC + ".enableTls=true", + RpcConstants.NACOS_SERVER_RPC + ".certChainFile=test-server-cert.pem", RpcConstants.NACOS_SERVER_RPC + + ".certPrivateKey=test-server-key.pem"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +public class ConfigIntegrationV3CoreITCase { + + public static AtomicInteger increment = new AtomicInteger(100); + @LocalServerPort private int port; - - public static AtomicInteger increment = new AtomicInteger(100); - - @BeforeClass - public static void beforeClass() throws IOException { - ConfigCleanUtils.changeToNewTestNacosHome(ConfigIntegrationV3_CITCase.class.getSimpleName()); - + + @BeforeAll + static void beforeClass() throws IOException { + ConfigCleanUtils.changeToNewTestNacosHome(ConfigIntegrationV3CoreITCase.class.getSimpleName()); } - - @BeforeClass - @AfterClass - public static void cleanClientCache() throws Exception { + + @BeforeAll + @AfterAll + static void cleanClientCache() throws Exception { ConfigCleanUtils.cleanClientCache(); } - + @Test - public void test_e_TlsServerAndPlainClient() throws Exception { - RpcClient client = RpcClientFactory.createClient("testTlsServerAndPlainClient", ConnectionType.GRPC, Collections.singletonMap("labelKey", "labelValue"), null); + void testTlsServerAndPlainClient() throws Exception { + RpcClient client = RpcClientFactory.createClient("testTlsServerAndPlainClient", ConnectionType.GRPC, + Collections.singletonMap("labelKey", "labelValue"), null); RpcClient.ServerInfo serverInfo = new RpcClient.ServerInfo(); serverInfo.setServerIp("127.0.0.1"); serverInfo.setServerPort(port); Connection connection = client.connectToServer(serverInfo); ConfigPublishRequest configPublishRequest = new ConfigPublishRequest(); - + String content = UUID.randomUUID().toString(); - + configPublishRequest.setContent(content); configPublishRequest.setGroup("test-group" + increment.getAndIncrement()); configPublishRequest.setDataId("test-data" + increment.getAndIncrement()); configPublishRequest.setRequestId(content); Response response = connection.request(configPublishRequest, TimeUnit.SECONDS.toMillis(3)); - Assert.assertTrue(response.isSuccess()); + assertTrue(response.isSuccess()); connection.close(); - } - + @Test - public void test_f_ServerTlsTrustAll() throws Exception { - + void testServerTlsTrustAll() throws Exception { RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig(); tlsConfig.setEnableTls(true); tlsConfig.setTrustAll(true); RpcClient.ServerInfo serverInfo = new RpcClient.ServerInfo(); serverInfo.setServerIp("127.0.0.1"); serverInfo.setServerPort(port); - RpcClient clientTrustAll = RpcClientFactory.createClient("testServerTlsTrustAll", ConnectionType.GRPC, Collections.singletonMap("labelKey", "labelValue"), tlsConfig); + RpcClient clientTrustAll = RpcClientFactory.createClient("testServerTlsTrustAll", ConnectionType.GRPC, + Collections.singletonMap("labelKey", "labelValue"), tlsConfig); Connection connectionTrustAll = clientTrustAll.connectToServer(serverInfo); ConfigPublishRequest configPublishRequest = new ConfigPublishRequest(); String content = UUID.randomUUID().toString(); @@ -111,32 +110,33 @@ public void test_f_ServerTlsTrustAll() throws Exception { configPublishRequest.setGroup("test-group" + increment.getAndIncrement()); configPublishRequest.setDataId("test-data" + increment.getAndIncrement()); Response response = connectionTrustAll.request(configPublishRequest, TimeUnit.SECONDS.toMillis(3)); - Assert.assertTrue(response.isSuccess()); + assertTrue(response.isSuccess()); connectionTrustAll.close(); - + } - + + @Disabled("TODO, Fix cert expired problem") @Test - @Ignore("TODO, Fix cert expired problem") - public void test_g_ServerTlsTrustCa() throws Exception { - + void testServerTlsTrustCa() throws Exception { + RpcClient.ServerInfo serverInfo = new RpcClient.ServerInfo(); serverInfo.setServerIp("127.0.0.1"); - + serverInfo.setServerPort(EnvUtil.getPort()); RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig(); tlsConfig.setEnableTls(true); tlsConfig.setTrustCollectionCertFile("test-ca-cert.pem"); - RpcClient clientTrustCa = RpcClientFactory.createClient("testServerTlsTrustCa", ConnectionType.GRPC, Collections.singletonMap("labelKey", "labelValue"), tlsConfig); + RpcClient clientTrustCa = RpcClientFactory.createClient("testServerTlsTrustCa", ConnectionType.GRPC, + Collections.singletonMap("labelKey", "labelValue"), tlsConfig); Connection connectionTrustCa = clientTrustCa.connectToServer(serverInfo); ConfigPublishRequest configPublishRequestCa = new ConfigPublishRequest(); String contentCa = UUID.randomUUID().toString(); - + configPublishRequestCa.setContent(contentCa); configPublishRequestCa.setGroup("test-group" + increment.getAndIncrement()); configPublishRequestCa.setDataId("test-data" + increment.getAndIncrement()); Response responseCa = connectionTrustCa.request(configPublishRequestCa, TimeUnit.SECONDS.toMillis(3)); - Assert.assertTrue(responseCa.isSuccess()); + assertTrue(responseCa.isSuccess()); connectionTrustCa.close(); } } diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/common/FileTypeEnum_ITCase.java b/test/core-test/src/test/java/com/alibaba/nacos/test/common/FileTypeEnumCoreITCase.java similarity index 62% rename from test/core-test/src/test/java/com/alibaba/nacos/test/common/FileTypeEnum_ITCase.java rename to test/core-test/src/test/java/com/alibaba/nacos/test/common/FileTypeEnumCoreITCase.java index f5841dfd4ae..6b4a1160a6e 100644 --- a/test/core-test/src/test/java/com/alibaba/nacos/test/common/FileTypeEnum_ITCase.java +++ b/test/core-test/src/test/java/com/alibaba/nacos/test/common/FileTypeEnumCoreITCase.java @@ -17,46 +17,53 @@ package com.alibaba.nacos.test.common; import com.alibaba.nacos.config.server.enums.FileTypeEnum; -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; /** + * This class contains integration tests for the FileTypeEnum enumeration. It verifies the functionality of the + * getFileTypeEnumByFileExtensionOrFileType method. The tests ensure that the FileTypeEnum correctly maps file + * extensions and file types to their respective enum values. + * * @author by jiangmin.wu on 2020/12/30 */ -public class FileTypeEnum_ITCase { +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +class FileTypeEnumCoreITCase { @Test - public void fileTypeEnum_test1() { + void fileTypeEnumTest1() { for (FileTypeEnum value : FileTypeEnum.values()) { FileTypeEnum fileTypeEnum = FileTypeEnum.getFileTypeEnumByFileExtensionOrFileType(value.name()); - Assert.assertEquals(fileTypeEnum, value); + assertEquals(fileTypeEnum, value); } } @Test - public void fileTypeEnum_test2() { + void fileTypeEnumTest2() { for (FileTypeEnum value : FileTypeEnum.values()) { FileTypeEnum fileTypeEnum = FileTypeEnum.getFileTypeEnumByFileExtensionOrFileType(value.getFileType()); - Assert.assertNotNull(fileTypeEnum); + assertNotNull(fileTypeEnum); } } @Test - public void fileTypeEnum_test3() { + void fileTypeEnumTest3() { FileTypeEnum fileTypeEnum = FileTypeEnum.getFileTypeEnumByFileExtensionOrFileType("t"); - Assert.assertEquals(fileTypeEnum, FileTypeEnum.TEXT); + assertEquals(FileTypeEnum.TEXT, fileTypeEnum); fileTypeEnum = FileTypeEnum.getFileTypeEnumByFileExtensionOrFileType(""); - Assert.assertEquals(fileTypeEnum, FileTypeEnum.TEXT); + assertEquals(FileTypeEnum.TEXT, fileTypeEnum); fileTypeEnum = FileTypeEnum.getFileTypeEnumByFileExtensionOrFileType("."); - Assert.assertEquals(fileTypeEnum, FileTypeEnum.TEXT); + assertEquals(FileTypeEnum.TEXT, fileTypeEnum); fileTypeEnum = FileTypeEnum.getFileTypeEnumByFileExtensionOrFileType("1"); - Assert.assertEquals(fileTypeEnum, FileTypeEnum.TEXT); + assertEquals(FileTypeEnum.TEXT, fileTypeEnum); fileTypeEnum = FileTypeEnum.getFileTypeEnumByFileExtensionOrFileType(null); - Assert.assertEquals(fileTypeEnum, FileTypeEnum.TEXT); + assertEquals(FileTypeEnum.TEXT, fileTypeEnum); } } diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/common/NacosAsyncRestTemplate_ITCase.java b/test/core-test/src/test/java/com/alibaba/nacos/test/common/NacosAsyncRestTemplateCoreITCase.java similarity index 66% rename from test/core-test/src/test/java/com/alibaba/nacos/test/common/NacosAsyncRestTemplate_ITCase.java rename to test/core-test/src/test/java/com/alibaba/nacos/test/common/NacosAsyncRestTemplateCoreITCase.java index 39fa2fbc9e9..f9b6b789e50 100644 --- a/test/core-test/src/test/java/com/alibaba/nacos/test/common/NacosAsyncRestTemplate_ITCase.java +++ b/test/core-test/src/test/java/com/alibaba/nacos/test/common/NacosAsyncRestTemplateCoreITCase.java @@ -28,172 +28,144 @@ import com.alibaba.nacos.common.model.RestResult; import com.alibaba.nacos.naming.misc.HttpClientManager.ProcessorHttpClientFactory; import com.alibaba.nacos.sys.env.EnvUtil; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.HashMap; import java.util.Map; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** - * NacosAsyncRestTemplate_ITCase. + * This class provides integration tests for NacosAsyncRestTemplate. These tests cover various HTTP methods such as + * POST, GET, PUT, and DELETE to ensure the correct functioning of asynchronous HTTP requests in the context of Nacos. * * @author mai.jh */ -@SuppressWarnings("all") -@FixMethodOrder(MethodSorters.JVM) -@RunWith(SpringRunner.class) +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +@TestMethodOrder(MethodName.class) +@ExtendWith(SpringExtension.class) @SpringBootTest(classes = Nacos.class, properties = { "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class NacosAsyncRestTemplate_ITCase { +class NacosAsyncRestTemplateCoreITCase { - @LocalServerPort - private int port; + private static final HttpClientFactory PROCESSOR_ASYNC_HTTP_CLIENT_FACTORY = new ProcessorHttpClientFactory(); - private NacosAsyncRestTemplate nacosRestTemplate = HttpClientBeanHolder - .getNacosAsyncRestTemplate(LoggerFactory.getLogger(NacosAsyncRestTemplate_ITCase.class)); + private static final String CONFIG_INSTANCE_PATH = "/nacos/v1/ns"; - private static final HttpClientFactory PROCESSOR_ASYNC_HTTP_CLIENT_FACTORY = new ProcessorHttpClientFactory(); + private final NacosAsyncRestTemplate nacosRestTemplate = HttpClientBeanHolder.getNacosAsyncRestTemplate( + LoggerFactory.getLogger(NacosAsyncRestTemplateCoreITCase.class)); - private NacosAsyncRestTemplate processorRestTemplate = null; + @SuppressWarnings("deprecation") + @LocalServerPort + private int port; - private final String CONFIG_INSTANCE_PATH = "/nacos/v1/ns"; + private NacosAsyncRestTemplate processorRestTemplate = null; - private String IP = null; + private String ip = null; @Autowired private Environment environment; - @Before - public void init() throws NacosException { - IP = String.format("http://localhost:%d", port); + @BeforeEach + void init() throws NacosException { + ip = String.format("http://localhost:%d", port); EnvUtil.setEnvironment((ConfigurableEnvironment) environment); - processorRestTemplate = HttpClientBeanHolder - .getNacosAsyncRestTemplate(PROCESSOR_ASYNC_HTTP_CLIENT_FACTORY); - } - - private class CallbackMap implements Callback { - - private HttpRestResult restResult; - - private Throwable throwable; - - @Override - public void onReceive(RestResult result) { - restResult = (HttpRestResult) result; - } - - @Override - public void onError(Throwable throwable) { - this.throwable = throwable; - } - - @Override - public void onCancel() { - - } - - public HttpRestResult getRestResult() { - return restResult; - } - - public Throwable getThrowable() { - return throwable; - } + processorRestTemplate = HttpClientBeanHolder.getNacosAsyncRestTemplate(PROCESSOR_ASYNC_HTTP_CLIENT_FACTORY); } @Test - public void test_url_post_form() throws Exception { - String url = IP + CONFIG_INSTANCE_PATH + "/instance"; + void testUrlPostForm() throws Exception { Map param = new HashMap<>(); param.put("serviceName", "app-test"); param.put("port", "8080"); param.put("ip", "11.11.11.11"); CallbackMap callbackMap = new CallbackMap<>(); + String url = ip + CONFIG_INSTANCE_PATH + "/instance"; nacosRestTemplate.postForm(url, Header.newInstance(), Query.newInstance(), param, String.class, callbackMap); Thread.sleep(2000); HttpRestResult restResult = callbackMap.getRestResult(); System.out.println(restResult.getData()); System.out.println(restResult.getHeader()); - Assert.assertTrue(restResult.ok()); + assertTrue(restResult.ok()); } @Test - public void test_url_post_form_by_processor() throws Exception { - String url = IP + CONFIG_INSTANCE_PATH + "/instance"; + void testUrlPostFormByProcessor() throws Exception { Map param = new HashMap<>(); param.put("serviceName", "app-test2"); param.put("port", "8080"); param.put("ip", "11.11.11.11"); CallbackMap callbackMap = new CallbackMap<>(); - processorRestTemplate.postForm(url, Header.newInstance(), Query.newInstance(), param, String.class, callbackMap); + String url = ip + CONFIG_INSTANCE_PATH + "/instance"; + processorRestTemplate.postForm(url, Header.newInstance(), Query.newInstance(), param, String.class, + callbackMap); Thread.sleep(2000); HttpRestResult restResult = callbackMap.getRestResult(); System.out.println(restResult.getData()); System.out.println(restResult.getHeader()); - Assert.assertTrue(restResult.ok()); + assertTrue(restResult.ok()); } @Test - public void test_url_put_form() throws Exception { - String url = IP + CONFIG_INSTANCE_PATH + "/instance"; + void testUrlPutForm() throws Exception { Map param = new HashMap<>(); param.put("serviceName", "app-test-change"); param.put("port", "8080"); param.put("ip", "11.11.11.11"); CallbackMap callbackMap = new CallbackMap<>(); + String url = ip + CONFIG_INSTANCE_PATH + "/instance"; nacosRestTemplate.postForm(url, Header.newInstance(), Query.newInstance(), param, String.class, callbackMap); Thread.sleep(2000); HttpRestResult restResult = callbackMap.getRestResult(); System.out.println(restResult.getData()); System.out.println(restResult.getHeader()); - Assert.assertTrue(restResult.ok()); + assertTrue(restResult.ok()); } - @Test - public void test_url_get() throws Exception { - String url = IP + CONFIG_INSTANCE_PATH + "/instance/list"; + void testUrlGet() throws Exception { + String url = ip + CONFIG_INSTANCE_PATH + "/instance/list"; Query query = Query.newInstance().addParam("serviceName", "app-test"); - CallbackMap callbackMap = new CallbackMap<>(); + CallbackMap> callbackMap = new CallbackMap<>(); nacosRestTemplate.get(url, Header.newInstance(), query, Map.class, callbackMap); Thread.sleep(2000); - HttpRestResult restResult = callbackMap.getRestResult(); + HttpRestResult> restResult = callbackMap.getRestResult(); System.out.println(restResult.getData()); System.out.println(restResult.getHeader()); - Assert.assertTrue(restResult.ok()); - Assert.assertEquals(restResult.getData().get("name"), "DEFAULT_GROUP@@app-test"); + assertTrue(restResult.ok()); + assertEquals("DEFAULT_GROUP@@app-test", restResult.getData().get("name")); } @Test - public void test_url_by_map() throws Exception { - String url = IP + CONFIG_INSTANCE_PATH + "/instance/list"; + void testUrlByMap() throws Exception { + String url = ip + CONFIG_INSTANCE_PATH + "/instance/list"; Map param = new HashMap<>(); param.put("serviceName", "app-test"); - CallbackMap callbackMap = new CallbackMap<>(); + CallbackMap> callbackMap = new CallbackMap<>(); nacosRestTemplate.get(url, Header.newInstance(), Query.newInstance().initParams(param), Map.class, callbackMap); Thread.sleep(2000); - HttpRestResult restResult = callbackMap.getRestResult(); + HttpRestResult> restResult = callbackMap.getRestResult(); System.out.println(restResult.getData()); System.out.println(restResult.getHeader()); - Assert.assertTrue(restResult.ok()); - Assert.assertEquals(restResult.getData().get("name"), "DEFAULT_GROUP@@app-test"); + assertTrue(restResult.ok()); + assertEquals("DEFAULT_GROUP@@app-test", restResult.getData().get("name")); } @Test - public void test_url_delete() throws Exception { - String url = IP + CONFIG_INSTANCE_PATH + "/instance"; + void testUrlDelete() throws Exception { + String url = ip + CONFIG_INSTANCE_PATH + "/instance"; Query query = Query.newInstance().addParam("ip", "11.11.11.11").addParam("port", "8080") .addParam("serviceName", "app-test"); CallbackMap callbackMap = new CallbackMap<>(); @@ -202,7 +174,37 @@ public void test_url_delete() throws Exception { HttpRestResult restResult = callbackMap.getRestResult(); System.out.println(restResult.getData()); System.out.println(restResult.getHeader()); - Assert.assertTrue(restResult.ok()); + assertTrue(restResult.ok()); + } + + private static class CallbackMap implements Callback { + + private HttpRestResult restResult; + + private Throwable throwable; + + @Override + public void onReceive(RestResult result) { + restResult = (HttpRestResult) result; + } + + @Override + public void onError(Throwable throwable) { + this.throwable = throwable; + } + + @Override + public void onCancel() { + + } + + public HttpRestResult getRestResult() { + return restResult; + } + + public Throwable getThrowable() { + return throwable; + } } } diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/common/NacosRestTemplate_ITCase.java b/test/core-test/src/test/java/com/alibaba/nacos/test/common/NacosRestTemplateCoreITCase.java similarity index 51% rename from test/core-test/src/test/java/com/alibaba/nacos/test/common/NacosRestTemplate_ITCase.java rename to test/core-test/src/test/java/com/alibaba/nacos/test/common/NacosRestTemplateCoreITCase.java index f482ef3060b..b1035be29a0 100644 --- a/test/core-test/src/test/java/com/alibaba/nacos/test/common/NacosRestTemplate_ITCase.java +++ b/test/core-test/src/test/java/com/alibaba/nacos/test/common/NacosRestTemplateCoreITCase.java @@ -26,132 +26,134 @@ import com.alibaba.nacos.common.model.RestResult; import com.alibaba.nacos.config.server.model.ConfigInfo4Beta; import com.fasterxml.jackson.core.type.TypeReference; -import org.junit.Assert; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.LoggerFactory; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.HashMap; import java.util.Map; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** - * NacosRestTemplate_ITCase. + * Integration tests for NacosRestTemplate.This class contains integration tests for NacosRestTemplate using various + * HTTP methods. * * @author mai.jh */ -@RunWith(SpringRunner.class) +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +@ExtendWith(SpringExtension.class) @SpringBootTest(classes = Nacos.class, properties = { "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -@FixMethodOrder(MethodSorters.JVM) -public class NacosRestTemplate_ITCase { +@TestMethodOrder(MethodName.class) +class NacosRestTemplateCoreITCase { - @LocalServerPort - private int port; + private static final String INSTANCE_PATH = "/nacos/v1/ns"; - private NacosRestTemplate nacosRestTemplate = HttpClientBeanHolder - .getNacosRestTemplate(LoggerFactory.getLogger(NacosRestTemplate_ITCase.class)); + private static final String CONFIG_PATH = "/nacos/v1/cs"; - private final String INSTANCE_PATH = "/nacos/v1/ns"; + private final NacosRestTemplate nacosRestTemplate = HttpClientBeanHolder.getNacosRestTemplate( + LoggerFactory.getLogger(NacosRestTemplateCoreITCase.class)); - private final String CONFIG_PATH = "/nacos/v1/cs"; + @LocalServerPort + private int port; - private String IP = null; + private String ip = null; - @Before - public void init() throws NacosException { - IP = String.format("http://localhost:%d", port); + @BeforeEach + void init() throws NacosException { + ip = String.format("http://localhost:%d", port); } @Test - public void test_url_post_config() throws Exception { - String url = IP + CONFIG_PATH + "/configs"; + void testUrlPostConfig() throws Exception { + String url = ip + CONFIG_PATH + "/configs"; Map param = new HashMap<>(); param.put("dataId", "test-1"); param.put("group", "DEFAULT_GROUP"); param.put("content", "aaa=b"); - HttpRestResult restResult = nacosRestTemplate - .postForm(url, Header.newInstance(), param, String.class); - Assert.assertTrue(restResult.ok()); + HttpRestResult restResult = nacosRestTemplate.postForm(url, Header.newInstance(), param, String.class); + assertTrue(restResult.ok()); System.out.println(restResult.getData()); System.out.println(restResult.getHeader()); } @Test - public void test_url_get_return_restResult() throws Exception { - String url = IP + CONFIG_PATH + "/configs"; + void testUrlGetReturnRestResult() throws Exception { + String url = ip + CONFIG_PATH + "/configs"; Query query = Query.newInstance().addParam("beta", true).addParam("dataId", "test-1") .addParam("group", "DEFAULT_GROUP"); - HttpRestResult restResult = nacosRestTemplate - .get(url, Header.newInstance(), query, new TypeReference>() { + HttpRestResult restResult = nacosRestTemplate.get(url, Header.newInstance(), query, + new TypeReference>() { }.getType()); - Assert.assertTrue(restResult.ok()); + assertTrue(restResult.ok()); System.out.println(restResult.getData()); System.out.println(restResult.getHeader()); } - @Test - public void test_url_post_form() throws Exception { - String url = IP + INSTANCE_PATH + "/instance"; + void testUrlPostForm() throws Exception { + String url = ip + INSTANCE_PATH + "/instance"; Map param = new HashMap<>(); param.put("serviceName", "app-test"); param.put("port", "8080"); param.put("ip", "11.11.11.11"); - HttpRestResult restResult = nacosRestTemplate - .postForm(url, Header.newInstance(), param, String.class); - Assert.assertTrue(restResult.ok()); + HttpRestResult restResult = nacosRestTemplate.postForm(url, Header.newInstance(), param, String.class); + assertTrue(restResult.ok()); System.out.println(restResult.getData()); } @Test - @Ignore("new version can't update instance when service and instance is not exist") - public void test_url_put_from() throws Exception { - String url = IP + INSTANCE_PATH + "/instance"; + @Disabled("new version can't update instance when service and instance is not exist") + void testUrlPutFrom() throws Exception { + String url = ip + INSTANCE_PATH + "/instance"; Map param = new HashMap<>(); param.put("serviceName", "app-test-change"); param.put("port", "8080"); param.put("ip", "11.11.11.11"); - HttpRestResult restResult = nacosRestTemplate - .putForm(url, Header.newInstance(), param, String.class); - Assert.assertTrue(restResult.ok()); + HttpRestResult restResult = nacosRestTemplate.putForm(url, Header.newInstance(), param, String.class); + assertTrue(restResult.ok()); System.out.println(restResult.getData()); } @Test - public void test_url_get() throws Exception { - String url = IP + INSTANCE_PATH + "/instance/list"; + void testUrlGet() throws Exception { + String url = ip + INSTANCE_PATH + "/instance/list"; Query query = Query.newInstance().addParam("serviceName", "app-test"); - HttpRestResult restResult = nacosRestTemplate.get(url, Header.newInstance(), query, Map.class); - Assert.assertTrue(restResult.ok()); - Assert.assertEquals(restResult.getData().get("name"), "DEFAULT_GROUP@@app-test"); + HttpRestResult> restResult = nacosRestTemplate.get(url, Header.newInstance(), query, + Map.class); + assertTrue(restResult.ok()); + assertEquals("DEFAULT_GROUP@@app-test", restResult.getData().get("name")); System.out.println(restResult.getData()); } @Test - public void test_url_get_by_map() throws Exception { - String url = IP + INSTANCE_PATH + "/instance/list"; + void testUrlGetByMap() throws Exception { + String url = ip + INSTANCE_PATH + "/instance/list"; Map param = new HashMap<>(); param.put("serviceName", "app-test"); - HttpRestResult restResult = nacosRestTemplate.get(url, Header.newInstance(), Query.newInstance().initParams(param), Map.class); - Assert.assertTrue(restResult.ok()); - Assert.assertEquals(restResult.getData().get("name"), "DEFAULT_GROUP@@app-test"); + HttpRestResult> restResult = nacosRestTemplate.get(url, Header.newInstance(), + Query.newInstance().initParams(param), Map.class); + assertTrue(restResult.ok()); + assertEquals("DEFAULT_GROUP@@app-test", restResult.getData().get("name")); System.out.println(restResult.getData()); } @Test - public void test_url_delete() throws Exception { - String url = IP + INSTANCE_PATH + "/instance"; + void testUrlDelete() throws Exception { + String url = ip + INSTANCE_PATH + "/instance"; Query query = Query.newInstance().addParam("ip", "11.11.11.11").addParam("port", "8080") .addParam("serviceName", "app-test"); HttpRestResult restResult = nacosRestTemplate.delete(url, Header.newInstance(), query, String.class); - Assert.assertTrue(restResult.ok()); + assertTrue(restResult.ok()); System.out.println(restResult); } diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/common/NacosRestTemplate_Interceptors_ITCase.java b/test/core-test/src/test/java/com/alibaba/nacos/test/common/NacosRestTemplateInterceptorsCoreITCase.java similarity index 65% rename from test/core-test/src/test/java/com/alibaba/nacos/test/common/NacosRestTemplate_Interceptors_ITCase.java rename to test/core-test/src/test/java/com/alibaba/nacos/test/common/NacosRestTemplateInterceptorsCoreITCase.java index de328e35901..39eb17a5b22 100644 --- a/test/core-test/src/test/java/com/alibaba/nacos/test/common/NacosRestTemplate_Interceptors_ITCase.java +++ b/test/core-test/src/test/java/com/alibaba/nacos/test/common/NacosRestTemplateInterceptorsCoreITCase.java @@ -25,47 +25,71 @@ import com.alibaba.nacos.common.http.client.response.HttpClientResponse; import com.alibaba.nacos.common.http.param.Header; import com.alibaba.nacos.common.model.RequestHttpEntity; -import org.junit.Assert; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.LoggerFactory; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.Map; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** - * NacosRestTemplate_Interceptors_ITCase + * Integration tests for NacosRestTemplateInterceptorsCoreITCase.These tests verify the functionality of HTTP request + * interceptors in NacosRestTemplate. * * @author mai.jh */ -@RunWith(SpringRunner.class) +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +@ExtendWith(SpringExtension.class) @SpringBootTest(classes = Nacos.class, properties = { "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -@FixMethodOrder(MethodSorters.JVM) -public class NacosRestTemplate_Interceptors_ITCase { +@TestMethodOrder(MethodName.class) +class NacosRestTemplateInterceptorsCoreITCase { + + private static final String CONFIG_PATH = "/nacos/v1/cs"; + + private final NacosRestTemplate nacosRestTemplate = HttpClientBeanHolder.getNacosRestTemplate( + LoggerFactory.getLogger(NacosRestTemplateInterceptorsCoreITCase.class)); + @SuppressWarnings("deprecation") @LocalServerPort private int port; - private NacosRestTemplate nacosRestTemplate = HttpClientBeanHolder - .getNacosRestTemplate(LoggerFactory.getLogger(NacosRestTemplate_Interceptors_ITCase.class)); + private String ip = null; - private final String CONFIG_PATH = "/nacos/v1/cs"; + @BeforeEach + void init() throws NacosException { + nacosRestTemplate.setInterceptors(Collections.singletonList(new TerminationInterceptor())); + ip = String.format("http://localhost:%d", port); + } - private String IP = null; + @Test + void testUrlPostConfig() throws Exception { + String url = ip + CONFIG_PATH + "/configs"; + Map param = new HashMap<>(); + param.put("dataId", "test-1"); + param.put("group", "DEFAULT_GROUP"); + param.put("content", "aaa=b"); + HttpRestResult restResult = nacosRestTemplate.postForm(url, Header.newInstance(), param, String.class); + assertEquals(500, restResult.getCode()); + assertEquals("Stop request", restResult.getMessage()); + System.out.println(restResult.getData()); + System.out.println(restResult.getHeader()); + } - private class TerminationInterceptor implements HttpClientRequestInterceptor { + private static class TerminationInterceptor implements HttpClientRequestInterceptor { @Override public HttpClientResponse intercept() { @@ -103,25 +127,4 @@ public boolean isIntercept(URI uri, String httpMethod, RequestHttpEntity request } } - - @Before - public void init() throws NacosException { - nacosRestTemplate.setInterceptors(Arrays.asList(new TerminationInterceptor())); - IP = String.format("http://localhost:%d", port); - } - - @Test - public void test_url_post_config() throws Exception { - String url = IP + CONFIG_PATH + "/configs"; - Map param = new HashMap<>(); - param.put("dataId", "test-1"); - param.put("group", "DEFAULT_GROUP"); - param.put("content", "aaa=b"); - HttpRestResult restResult = nacosRestTemplate - .postForm(url, Header.newInstance(), param, String.class); - Assert.assertEquals(500, restResult.getCode()); - Assert.assertEquals("Stop request", restResult.getMessage()); - System.out.println(restResult.getData()); - System.out.println(restResult.getHeader()); - } } diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/common/WatchFileCenter_ITCase.java b/test/core-test/src/test/java/com/alibaba/nacos/test/common/WatchFileCenterCoreITCase.java similarity index 76% rename from test/core-test/src/test/java/com/alibaba/nacos/test/common/WatchFileCenter_ITCase.java rename to test/core-test/src/test/java/com/alibaba/nacos/test/common/WatchFileCenterCoreITCase.java index 8a5c80fe89f..3497158a957 100644 --- a/test/core-test/src/test/java/com/alibaba/nacos/test/common/WatchFileCenter_ITCase.java +++ b/test/core-test/src/test/java/com/alibaba/nacos/test/common/WatchFileCenterCoreITCase.java @@ -16,18 +16,17 @@ package com.alibaba.nacos.test.common; +import com.alibaba.nacos.common.utils.ByteUtils; +import com.alibaba.nacos.common.utils.ConcurrentHashSet; +import com.alibaba.nacos.common.utils.StringUtils; +import com.alibaba.nacos.common.utils.ThreadUtils; import com.alibaba.nacos.sys.file.FileChangeEvent; import com.alibaba.nacos.sys.file.FileWatcher; import com.alibaba.nacos.sys.file.WatchFileCenter; -import com.alibaba.nacos.common.utils.ByteUtils; -import com.alibaba.nacos.common.utils.ConcurrentHashSet; import com.alibaba.nacos.sys.utils.DiskUtils; -import com.alibaba.nacos.common.utils.ThreadUtils; -import com.alibaba.nacos.common.utils.StringUtils; -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.io.File; import java.nio.charset.StandardCharsets; @@ -41,36 +40,42 @@ import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** + * Integration tests for file watching and modification handling using WatchFileCenter.These tests verify the + * concurrency and accuracy of file change notifications under high loads. + * * @author liaochuntao */ -public class WatchFileCenter_ITCase { +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +class WatchFileCenterCoreITCase { - static final String path = Paths.get(System.getProperty("user.home"), "/watch_file_change_test").toString(); + private static final String PATH = Paths.get(System.getProperty("user.home"), "/watch_file_change_test").toString(); - final Object monitor = new Object(); + private static final Executor EXECUTOR = Executors.newFixedThreadPool(32); - static final Executor executor = Executors.newFixedThreadPool(32); + final Object monitor = new Object(); - @BeforeClass - public static void beforeCls() throws Exception { - DiskUtils.deleteDirThenMkdir(path); + @BeforeAll + static void beforeCls() throws Exception { + DiskUtils.deleteDirThenMkdir(PATH); } - @AfterClass - public static void afterCls() throws Exception { - DiskUtils.deleteDirectory(path); + @AfterAll + static void afterCls() throws Exception { + DiskUtils.deleteDirectory(PATH); } // The last file change must be notified @Test - public void test_high_concurrency_modify() throws Exception { + void testHighConcurrencyModify() throws Exception { AtomicInteger count = new AtomicInteger(0); Set set = new ConcurrentHashSet<>(); final String fileName = "test2_file_change"; - final File file = Paths.get(path, fileName).toFile(); + final File file = Paths.get(PATH, fileName).toFile(); func(fileName, file, content -> { set.add(content); @@ -81,14 +86,14 @@ public void test_high_concurrency_modify() throws Exception { } @Test - public void test_modify_file_much() throws Exception { + void testModifyFileMuch() throws Exception { final String fileName = "modify_file_much"; - final File file = Paths.get(path, fileName).toFile(); + final File file = Paths.get(PATH, fileName).toFile(); CountDownLatch latch = new CountDownLatch(3); AtomicInteger count = new AtomicInteger(0); - WatchFileCenter.registerWatcher(path, new FileWatcher() { + WatchFileCenter.registerWatcher(PATH, new FileWatcher() { @Override public void onChange(FileChangeEvent event) { try { @@ -113,20 +118,20 @@ public boolean interest(String context) { latch.await(10_000L, TimeUnit.MILLISECONDS); - Assert.assertEquals(3, count.get()); + assertEquals(3, count.get()); } @Test - public void test_multi_file_modify() throws Exception { + void testMultiFileModify() throws Exception { CountDownLatch latch = new CountDownLatch(10); for (int i = 0; i < 10; i++) { AtomicInteger count = new AtomicInteger(0); Set set = new ConcurrentHashSet<>(); final String fileName = "test2_file_change_" + i; - final File file = Paths.get(path, fileName).toFile(); + final File file = Paths.get(PATH, fileName).toFile(); - executor.execute(() -> { + EXECUTOR.execute(() -> { try { func(fileName, file, content -> { set.add(content); @@ -147,10 +152,10 @@ public void test_multi_file_modify() throws Exception { private void func(final String fileName, final File file, final Consumer consumer) throws Exception { CountDownLatch latch = new CountDownLatch(100); DiskUtils.touch(file); - WatchFileCenter.registerWatcher(path, new FileWatcher() { + WatchFileCenter.registerWatcher(PATH, new FileWatcher() { @Override public void onChange(FileChangeEvent event) { - final File file = Paths.get(path, fileName).toFile(); + final File file = Paths.get(PATH, fileName).toFile(); final String content = DiskUtils.readFile(file); consumer.accept(content); } @@ -164,10 +169,10 @@ public boolean interest(String context) { final AtomicInteger id = new AtomicInteger(0); final AtomicReference finalContent = new AtomicReference<>(null); for (int i = 0; i < 100; i++) { - executor.execute(() -> { + EXECUTOR.execute(() -> { final String j = fileName + "_" + id.incrementAndGet(); try { - final File file1 = Paths.get(path, fileName).toFile(); + final File file1 = Paths.get(PATH, fileName).toFile(); synchronized (monitor) { finalContent.set(j); DiskUtils.writeFile(file1, j.getBytes(StandardCharsets.UTF_8), false); diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/core/SnowFlowerIdGeneratorCoreITCase.java b/test/core-test/src/test/java/com/alibaba/nacos/test/core/SnowFlowerIdGeneratorCoreITCase.java new file mode 100644 index 00000000000..3929192d29c --- /dev/null +++ b/test/core-test/src/test/java/com/alibaba/nacos/test/core/SnowFlowerIdGeneratorCoreITCase.java @@ -0,0 +1,56 @@ +/* + * Copyright 1999-2018 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.test.core; + +import com.alibaba.nacos.core.distributed.id.SnowFlowerIdGenerator; +import com.alibaba.nacos.sys.env.EnvUtil; +import org.junit.jupiter.api.Test; +import org.springframework.core.env.StandardEnvironment; + +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +/** + * Integration test case for validating unique ID generation using SnowFlowerIdGenerator with distinct initializations + * and assertions for uniqueness. + * + * @author liaochuntao + */ +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +class SnowFlowerIdGeneratorCoreITCase { + + @Test + void testIdGenerator() { + EnvUtil.setEnvironment(new StandardEnvironment()); + SnowFlowerIdGenerator generator1 = new SnowFlowerIdGenerator(); + SnowFlowerIdGenerator generator2 = new SnowFlowerIdGenerator(); + SnowFlowerIdGenerator generator3 = new SnowFlowerIdGenerator(); + + generator1.initialize(1); + generator2.initialize(2); + generator3.initialize(3); + + long id1 = generator1.nextId(); + long id2 = generator2.nextId(); + long id3 = generator3.nextId(); + + assertNotEquals(id1, id2); + assertNotEquals(id1, id3); + assertNotEquals(id2, id3); + + } + +} diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/core/SnowFlowerIdGenerator_ITCase.java b/test/core-test/src/test/java/com/alibaba/nacos/test/core/SnowFlowerIdGenerator_ITCase.java deleted file mode 100644 index a09c1a2f4c9..00000000000 --- a/test/core-test/src/test/java/com/alibaba/nacos/test/core/SnowFlowerIdGenerator_ITCase.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.test.core; - -import com.alibaba.nacos.core.distributed.id.SnowFlowerIdGenerator; -import com.alibaba.nacos.sys.env.EnvUtil; -import org.junit.Assert; -import org.junit.Test; -import org.springframework.core.env.StandardEnvironment; - -/** - * @author liaochuntao - */ -public class SnowFlowerIdGenerator_ITCase { - - @Test - public void test_idGenerator() { - EnvUtil.setEnvironment(new StandardEnvironment()); - SnowFlowerIdGenerator generator1 = new SnowFlowerIdGenerator(); - SnowFlowerIdGenerator generator2 = new SnowFlowerIdGenerator(); - SnowFlowerIdGenerator generator3 = new SnowFlowerIdGenerator(); - - generator1.initialize(1); - generator2.initialize(2); - generator3.initialize(3); - - long id1 = generator1.nextId(); - long id2 = generator2.nextId(); - long id3 = generator3.nextId(); - - Assert.assertNotEquals(id1, id2); - Assert.assertNotEquals(id1, id3); - Assert.assertNotEquals(id2, id3); - - } - -} diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/AuthBase.java b/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/AuthBase.java index 219cacbe543..71e25870a4e 100644 --- a/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/AuthBase.java +++ b/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/AuthBase.java @@ -22,8 +22,6 @@ import com.alibaba.nacos.test.base.HttpClient4Test; import com.alibaba.nacos.test.base.Params; import com.fasterxml.jackson.databind.JsonNode; - -import org.junit.Assert; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; @@ -31,8 +29,11 @@ import java.util.Properties; import java.util.concurrent.TimeUnit; +import static org.junit.jupiter.api.Assertions.assertTrue; /** + * Base class for authentication tests in Nacos.` + * * @author nkorange * @since 1.2.0 */ @@ -62,14 +63,22 @@ public class AuthBase extends HttpClient4Test { protected String namespace1 = "namespace1"; + /** + * Logs in a user with the provided username and password, then returns the access token. + * + * @param username the username of the user + * @param password the password of the user + * @return the access token (accessToken) as a String + * @throws AssertionError if the response status is not 2xx or the accessToken is missing + */ public String login(String username, String password) { ResponseEntity response = request("/nacos/v1/auth/users/login", Params.newParams().appendParam("username", username).appendParam("password", password).done(), String.class, HttpMethod.POST); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); JsonNode json = JacksonUtils.toObj(response.getBody()); - Assert.assertTrue(json.has("accessToken")); + assertTrue(json.has("accessToken")); return json.get("accessToken").textValue(); } @@ -90,7 +99,7 @@ protected void init(int port) throws Exception { Params.newParams().appendParam("username", username1).appendParam("password", password1) .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST); System.out.println(response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Create a user: response = request("/nacos/v1/auth/users", @@ -98,7 +107,7 @@ protected void init(int port) throws Exception { .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST); System.out.println(response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Create a user: response = request("/nacos/v1/auth/users", @@ -106,7 +115,7 @@ protected void init(int port) throws Exception { .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST); System.out.println(response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Create a role: response = request("/nacos/v1/auth/roles", @@ -114,21 +123,21 @@ protected void init(int port) throws Exception { .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST); System.out.println(response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Create a role: response = request("/nacos/v1/auth/roles", Params.newParams().appendParam("role", role2).appendParam("username", username2) .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST); System.out.println(response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Create a role: response = request("/nacos/v1/auth/roles", Params.newParams().appendParam("role", role3).appendParam("username", username3) .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST); System.out.println(response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Add read permission of namespace1 to role1: response = request("/nacos/v1/auth/permissions", @@ -136,7 +145,7 @@ protected void init(int port) throws Exception { .appendParam("action", "r").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST); System.out.println(response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Add write permission of namespace1 to role2: response = request("/nacos/v1/auth/permissions", @@ -144,7 +153,7 @@ protected void init(int port) throws Exception { .appendParam("action", "w").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST); System.out.println(response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Add read/write permission of namespace1 to role3: response = request("/nacos/v1/auth/permissions", @@ -152,7 +161,7 @@ protected void init(int port) throws Exception { .appendParam("action", "rw").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST); System.out.println(response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Init properties: properties = new Properties(); @@ -168,7 +177,7 @@ protected void destroy() { .appendParam("action", "r").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Delete permission: response = request("/nacos/v1/auth/permissions", @@ -176,7 +185,7 @@ protected void destroy() { .appendParam("action", "w").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Delete permission: response = request("/nacos/v1/auth/permissions", @@ -184,49 +193,49 @@ protected void destroy() { .appendParam("action", "rw").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Delete a role: response = request("/nacos/v1/auth/roles", Params.newParams().appendParam("role", role1).appendParam("username", username1) .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Delete a role: response = request("/nacos/v1/auth/roles", Params.newParams().appendParam("role", role2).appendParam("username", username2) .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Delete a role: response = request("/nacos/v1/auth/roles", Params.newParams().appendParam("role", role3).appendParam("username", username3) .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Delete a user: response = request("/nacos/v1/auth/users", Params.newParams().appendParam("username", username1).appendParam("password", password1) .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Delete a user: response = request("/nacos/v1/auth/users", Params.newParams().appendParam("username", username2).appendParam("password", password2) .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Delete a user: response = request("/nacos/v1/auth/users", Params.newParams().appendParam("username", username3).appendParam("password", password3) .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); System.setProperty("nacos.core.auth.enabled", "false"); } diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/ConfigAuth_ITCase.java b/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/ConfigAuthCoreITCase.java similarity index 73% rename from test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/ConfigAuth_ITCase.java rename to test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/ConfigAuthCoreITCase.java index b3bca96e3c7..8b3eb7a3e26 100644 --- a/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/ConfigAuth_ITCase.java +++ b/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/ConfigAuthCoreITCase.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.test.core.auth; import com.alibaba.nacos.Nacos; @@ -24,84 +25,86 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.client.config.listener.impl.AbstractConfigChangeListener; import org.apache.http.HttpStatus; -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.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.junit4.SpringRunner; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** + * Integration tests for Nacos configuration with authentication. + * * @author nkorange * @since 1.2.0 */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"}, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class ConfigAuth_ITCase extends AuthBase { - - @LocalServerPort - private int port; - +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +@SpringBootTest(classes = Nacos.class, properties = { + "server.servlet.contextPath=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +public class ConfigAuthCoreITCase extends AuthBase { + public static final long TIME_OUT = 2000; - + public ConfigService iconfig = null; - - private String dataId = "yanlin"; - private String group = "yanlin"; - - @Before - public void init() throws Exception { + + @LocalServerPort + private int port; + + private final String dataId = "yanlin"; + + private final String group = "yanlin"; + + @BeforeEach + void init() throws Exception { super.init(port); } - - @After - public void destroy(){ + + /** + * Cleans up resources after each test execution. + */ + @AfterEach + public void destroy() { super.destroy(); try { - iconfig.shutDown(); - }catch (NacosException ex) { - + if (iconfig != null) { + iconfig.shutDown(); + } + } catch (NacosException ex) { + // Ignored exception during shutdown } } - - + @Test - public void writeWithReadPermission() throws Exception { - + void writeWithReadPermission() throws Exception { + // Construct configService: properties.put(PropertyKeyConst.USERNAME, username1); properties.put(PropertyKeyConst.PASSWORD, password1); properties.put(PropertyKeyConst.NAMESPACE, namespace1); iconfig = NacosFactory.createConfigService(properties); - + final String content = "test"; assertFalse(iconfig.publishConfig(dataId, group, content)); assertFalse(iconfig.removeConfig(dataId, group)); } - + @Test - public void readWithReadPermission() throws Exception { - - CountDownLatch latch = new CountDownLatch(1); - AtomicInteger ai = new AtomicInteger(0); - + void readWithReadPermission() throws Exception { properties.put(PropertyKeyConst.USERNAME, username1); properties.put(PropertyKeyConst.PASSWORD, password1); iconfig = NacosFactory.createConfigService(properties); - + final String content = "test" + System.currentTimeMillis(); System.out.println(content); - + + CountDownLatch latch = new CountDownLatch(1); iconfig.addListener(dataId, group, new AbstractConfigChangeListener() { @Override public void receiveConfigChange(ConfigChangeEvent event) { @@ -113,52 +116,50 @@ public void receiveConfigChange(ConfigChangeEvent event) { latch.countDown(); } }); - + TimeUnit.SECONDS.sleep(3L); - + properties.put(PropertyKeyConst.USERNAME, username2); properties.put(PropertyKeyConst.PASSWORD, password2); ConfigService configService = NacosFactory.createConfigService(properties); - + boolean result = configService.publishConfig(dataId, group, content); - Assert.assertTrue(result); + assertTrue(result); TimeUnit.SECONDS.sleep(5L); - + String res = iconfig.getConfig(dataId, group, TIME_OUT); - Assert.assertEquals(content, res); - + assertEquals(content, res); + latch.await(5L, TimeUnit.SECONDS); - Assert.assertEquals(0, latch.getCount()); + assertEquals(0, latch.getCount()); } - + @Test - public void writeWithWritePermission() throws Exception { - + void writeWithWritePermission() throws Exception { + // Construct configService: properties.put(PropertyKeyConst.USERNAME, username2); properties.put(PropertyKeyConst.PASSWORD, password2); iconfig = NacosFactory.createConfigService(properties); - + final String content = "test"; boolean res = iconfig.publishConfig(dataId, group, content); - Assert.assertTrue(res); - + assertTrue(res); + res = iconfig.removeConfig(dataId, group); - Assert.assertTrue(res); + assertTrue(res); } - + @Test - public void readWithWritePermission() throws Exception { - - CountDownLatch latch = new CountDownLatch(1); - + void readWithWritePermission() throws Exception { properties.put(PropertyKeyConst.NAMESPACE, namespace1); properties.put(PropertyKeyConst.USERNAME, username2); properties.put(PropertyKeyConst.PASSWORD, password2); iconfig = NacosFactory.createConfigService(properties); - + final String content = "test" + System.currentTimeMillis(); - + + CountDownLatch latch = new CountDownLatch(1); iconfig.addListener(dataId, group, new AbstractConfigChangeListener() { @Override public void receiveConfigChange(ConfigChangeEvent event) { @@ -170,38 +171,34 @@ public void receiveConfigChange(ConfigChangeEvent event) { latch.countDown(); } }); - + TimeUnit.SECONDS.sleep(3L); - + boolean result = iconfig.publishConfig(dataId, group, content); - Assert.assertTrue(result); + assertTrue(result); TimeUnit.SECONDS.sleep(5L); - + try { iconfig.getConfig(dataId, group, TIME_OUT); fail(); - } catch (NacosException ne) { - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ne.getErrCode()); + } catch (NacosException e) { + assertEquals(HttpStatus.SC_FORBIDDEN, e.getErrCode()); } - + latch.await(5L, TimeUnit.SECONDS); - - Assert.assertTrue(latch.getCount() > 0); + + assertTrue(latch.getCount() > 0); } - - + @Test - public void ReadWriteWithFullPermission() throws Exception { - - CountDownLatch latch = new CountDownLatch(1); - AtomicInteger ai = new AtomicInteger(0); - + void readWriteWithFullPermission() throws Exception { properties.put(PropertyKeyConst.USERNAME, username3); properties.put(PropertyKeyConst.PASSWORD, password3); iconfig = NacosFactory.createConfigService(properties); - + final String content = "test" + System.currentTimeMillis(); - + + CountDownLatch latch = new CountDownLatch(1); iconfig.addListener(dataId, group, new AbstractConfigChangeListener() { @Override public void receiveConfigChange(ConfigChangeEvent event) { @@ -213,22 +210,22 @@ public void receiveConfigChange(ConfigChangeEvent event) { latch.countDown(); } }); - + TimeUnit.SECONDS.sleep(3L); - + boolean result = iconfig.publishConfig(dataId, group, content); - Assert.assertTrue(result); + assertTrue(result); TimeUnit.SECONDS.sleep(5L); - + String res = iconfig.getConfig(dataId, group, TIME_OUT); - Assert.assertEquals(content, res); - + assertEquals(content, res); + latch.await(5L, TimeUnit.SECONDS); - - Assert.assertEquals(0, latch.getCount()); - + + assertEquals(0, latch.getCount()); + result = iconfig.removeConfig(dataId, group); - Assert.assertTrue(result); + assertTrue(result); } - + } diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/LdapAuth_ITCase.java b/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/LdapAuthCoreITCase.java similarity index 54% rename from test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/LdapAuth_ITCase.java rename to test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/LdapAuthCoreITCase.java index bb842ad1de5..2d73cf342a3 100644 --- a/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/LdapAuth_ITCase.java +++ b/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/LdapAuthCoreITCase.java @@ -18,65 +18,74 @@ import com.alibaba.nacos.Nacos; import com.alibaba.nacos.auth.config.AuthConfigs; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.platform.suite.api.SelectClasses; +import org.junit.platform.suite.api.Suite; import org.mockito.Mockito; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.ldap.core.LdapTemplate; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.annotation.DirtiesContext; import java.net.URL; import java.util.concurrent.TimeUnit; -@RunWith(Suite.class) -@Suite.SuiteClasses({ LdapAuth_ITCase.NonTlsTest.class,LdapAuth_ITCase.TlsTest.class}) -public class LdapAuth_ITCase extends AuthBase { +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +@Suite +@SelectClasses({LdapAuthCoreITCase.NonTlsTest.class, LdapAuthCoreITCase.TlsTest.class}) +class LdapAuthCoreITCase { - @LocalServerPort - private int port; - - private String filterPrefix = "uid"; - - @MockBean - private LdapTemplate ldapTemplate; + @Test + void empty() { + } - @Before - public void init() throws Exception { - Mockito.when(ldapTemplate.authenticate("", "(" + filterPrefix + "=" + "karson" + ")", "karson")) - .thenReturn(true); - AuthConfigs.setCachingEnabled(false); - TimeUnit.SECONDS.sleep(5L); - String url = String.format("http://localhost:%d/", port); - System.setProperty("nacos.core.auth.enabled", "true"); - this.base = new URL(url); + abstract static class LdapBase extends AuthBase { + + @LocalServerPort + private int port; + + private String filterPrefix = "uid"; + + @MockBean + private LdapTemplate ldapTemplate; + + @BeforeEach + void init() throws Exception { + Mockito.when(ldapTemplate.authenticate("", "(" + filterPrefix + "=" + "karson" + ")", "karson")) + .thenReturn(true); + AuthConfigs.setCachingEnabled(false); + TimeUnit.SECONDS.sleep(5L); + String url = String.format("http://localhost:%d/", port); + System.setProperty("nacos.core.auth.enabled", "true"); + this.base = new URL(url); + } } - @RunWith(SpringRunner.class) + @Nested + @DirtiesContext @SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos", "nacos.core.auth.system.type=ldap"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) - public static class NonTlsTest extends LdapAuth_ITCase { + class NonTlsTest extends LdapBase { @Test - public void testLdapAuth() throws Exception { + void testLdapAuth() throws Exception { super.login("karson", "karson"); } } - @RunWith(SpringRunner.class) + @Nested + @DirtiesContext @SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos", "nacos.core.auth.system.type=ldap", "nacos.core.auth.ldap.url=ldaps://localhost:636"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) - public static class TlsTest extends LdapAuth_ITCase { + class TlsTest extends LdapBase { @Test - public void testLdapAuth() throws Exception { + void testLdapAuth() throws Exception { super.login("karson", "karson"); } } - - } diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/NamingAuth_ITCase.java b/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/NamingAuthCoreITCase.java similarity index 66% rename from test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/NamingAuth_ITCase.java rename to test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/NamingAuthCoreITCase.java index 42b1de6eb0a..6854bb882ae 100644 --- a/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/NamingAuth_ITCase.java +++ b/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/NamingAuthCoreITCase.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.test.core.auth; import com.alibaba.nacos.Nacos; @@ -21,139 +22,141 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; -import com.alibaba.nacos.sys.utils.ApplicationUtils; import org.apache.http.HttpStatus; -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.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.List; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** + * Integration tests for Nacos naming service with various authentication scenarios. + * * @author nkorange * @since 1.2.0 */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"}, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class NamingAuth_ITCase extends AuthBase { - +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +@ExtendWith(SpringExtension.class) +@SpringBootTest(classes = Nacos.class, properties = { + "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +class NamingAuthCoreITCase extends AuthBase { + @LocalServerPort private int port; - + private NamingService namingService; - - @Before - public void init() throws Exception { + + @BeforeEach + void init() throws Exception { super.init(port); } - - @After + + @AfterEach public void destroy() { super.destroy(); } - + @Test - public void writeWithReadPermission() throws Exception { - + void writeWithReadPermission() throws Exception { + properties.put(PropertyKeyConst.USERNAME, username1); properties.put(PropertyKeyConst.PASSWORD, password1); namingService = NacosFactory.createNamingService(properties); - + try { namingService.registerInstance("test.1", "1.2.3.4", 80); fail(); - } catch (NacosException ne) { - NacosException cause = (NacosException) ne.getCause(); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, cause.getErrCode()); + } catch (NacosException e) { + NacosException cause = (NacosException) e.getCause(); + assertEquals(HttpStatus.SC_FORBIDDEN, cause.getErrCode()); } - + try { namingService.deregisterInstance("test.1", "1.2.3.4", 80); fail(); - } catch (NacosException ne) { - NacosException cause = (NacosException) ne.getCause(); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, cause.getErrCode()); + } catch (NacosException e) { + NacosException cause = (NacosException) e.getCause(); + assertEquals(HttpStatus.SC_FORBIDDEN, cause.getErrCode()); } namingService.shutDown(); } - + @Test - public void readWithReadPermission() throws Exception { + void readWithReadPermission() throws Exception { properties.put(PropertyKeyConst.USERNAME, username2); properties.put(PropertyKeyConst.PASSWORD, password2); NamingService namingService1 = NacosFactory.createNamingService(properties); namingService1.registerInstance("test.1", "1.2.3.4", 80); TimeUnit.SECONDS.sleep(5L); - + properties.put(PropertyKeyConst.USERNAME, username1); properties.put(PropertyKeyConst.PASSWORD, password1); namingService = NacosFactory.createNamingService(properties); - + List list = namingService.getAllInstances("test.1"); - Assert.assertEquals(1, list.size()); + assertEquals(1, list.size()); namingService1.shutDown(); namingService.shutDown(); } - + @Test - public void writeWithWritePermission() throws Exception { - + void writeWithWritePermission() throws Exception { + properties.put(PropertyKeyConst.USERNAME, username2); properties.put(PropertyKeyConst.PASSWORD, password2); namingService = NacosFactory.createNamingService(properties); - + namingService.registerInstance("test.1", "1.2.3.4", 80); - + TimeUnit.SECONDS.sleep(5L); - + namingService.deregisterInstance("test.1", "1.2.3.4", 80); namingService.shutDown(); } - + @Test - public void readWithWritePermission() throws Exception { - + void readWithWritePermission() throws Exception { + properties.put(PropertyKeyConst.USERNAME, username2); properties.put(PropertyKeyConst.PASSWORD, password2); namingService = NacosFactory.createNamingService(properties); - + namingService.registerInstance("test.1", "1.2.3.4", 80); TimeUnit.SECONDS.sleep(5L); - + try { namingService.getAllInstances("test.1"); fail(); - } catch (NacosException ne) { - NacosException cause = (NacosException) ne.getCause(); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, cause.getErrCode()); + } catch (NacosException e) { + NacosException cause = (NacosException) e.getCause(); + assertEquals(HttpStatus.SC_FORBIDDEN, cause.getErrCode()); } - + namingService.shutDown(); } - + @Test - public void readWriteWithFullPermission() throws Exception { - + void readWriteWithFullPermission() throws Exception { + properties.put(PropertyKeyConst.USERNAME, username3); properties.put(PropertyKeyConst.PASSWORD, password3); namingService = NacosFactory.createNamingService(properties); - + namingService.registerInstance("test.1", "1.2.3.4", 80); TimeUnit.SECONDS.sleep(5L); - + List list = namingService.getAllInstances("test.1"); - - Assert.assertEquals(1, list.size()); + + assertEquals(1, list.size()); namingService.shutDown(); } - + } diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/Permission_ITCase.java b/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/PermissionCoreITCase.java similarity index 78% rename from test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/Permission_ITCase.java rename to test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/PermissionCoreITCase.java index 9bea9c67b5d..436a99cf8c8 100644 --- a/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/Permission_ITCase.java +++ b/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/PermissionCoreITCase.java @@ -24,43 +24,50 @@ import com.alibaba.nacos.test.base.Params; import com.fasterxml.jackson.core.type.TypeReference; 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.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import java.net.URL; import java.util.concurrent.TimeUnit; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** + * Integration tests for Nacos permission management with various scenarios. + * * @author nkorange * @since 1.2.0 */ -@RunWith(SpringRunner.class) +//todo fix this test case +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +@ExtendWith(SpringExtension.class) @SpringBootTest(classes = Nacos.class, properties = { "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class Permission_ITCase extends HttpClient4Test { +class PermissionCoreITCase extends HttpClient4Test { @LocalServerPort private int port; private String accessToken; - @Before - public void init() throws Exception { + @BeforeEach + void init() throws Exception { TimeUnit.SECONDS.sleep(5L); String url = String.format("http://localhost:%d/", port); this.base = new URL(url); } - @After - public void destroy() { + @AfterEach + void destroy() { // Delete permission: ResponseEntity response = request("/nacos/v1/auth/permissions", @@ -68,7 +75,7 @@ public void destroy() { .appendParam("action", "rw").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Delete permission: response = request("/nacos/v1/auth/permissions", @@ -76,38 +83,38 @@ public void destroy() { .appendParam("action", "r").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Delete role: response = request("/nacos/v1/auth/roles", Params.newParams().appendParam("role", "role1").appendParam("username", "username3") .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Delete a user: response = request("/nacos/v1/auth/users", Params.newParams().appendParam("username", "username3").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); } @Test - public void login() { + void login() { ResponseEntity response = request("/nacos/v1/auth/users/login", Params.newParams().appendParam("username", "nacos").appendParam("password", "nacos").done(), String.class, HttpMethod.POST); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); JsonNode json = JacksonUtils.toObj(response.getBody()); - Assert.assertTrue(json.has("accessToken")); + assertTrue(json.has("accessToken")); accessToken = json.get("accessToken").textValue(); } @Test - public void createDeleteQueryPermission() { + void createDeleteQueryPermission() { login(); @@ -116,14 +123,14 @@ public void createDeleteQueryPermission() { Params.newParams().appendParam("username", "username3").appendParam("password", "password1") .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Create role: response = request("/nacos/v1/auth/roles", Params.newParams().appendParam("role", "role1").appendParam("username", "username3") .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Create permission: response = request("/nacos/v1/auth/permissions", @@ -131,7 +138,7 @@ public void createDeleteQueryPermission() { .appendParam("action", "rw").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Create another permission: response = request("/nacos/v1/auth/permissions", @@ -139,7 +146,7 @@ public void createDeleteQueryPermission() { .appendParam("action", "r").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Query permission: response = request("/nacos/v1/auth/permissions", @@ -147,15 +154,16 @@ public void createDeleteQueryPermission() { .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.GET); System.out.println(response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); Page permissionPage = JacksonUtils.toObj(response.getBody(), new TypeReference>() { }); - Assert.assertNotNull(permissionPage); - Assert.assertNotNull(permissionPage.getPageItems()); + assertNotNull(permissionPage); + assertNotNull(permissionPage.getPageItems()); - boolean found1 = false, found2 = false; + boolean found1 = false; + boolean found2 = false; for (Permission permission : permissionPage.getPageItems()) { if (permission.getResource().equals("public:*:*") && permission.getAction().equals("rw")) { found1 = true; @@ -167,8 +175,8 @@ public void createDeleteQueryPermission() { break; } } - Assert.assertTrue(found1); - Assert.assertTrue(found2); + assertTrue(found1); + assertTrue(found2); // Delete permission: response = request("/nacos/v1/auth/permissions", @@ -176,20 +184,20 @@ public void createDeleteQueryPermission() { .appendParam("action", "rw").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Query permission: response = request("/nacos/v1/auth/permissions", Params.newParams().appendParam("role", "role1").appendParam("pageNo", "1").appendParam("pageSize", "10") .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.GET); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); permissionPage = JacksonUtils.toObj(response.getBody(), new TypeReference>() { }); - Assert.assertNotNull(permissionPage); - Assert.assertNotNull(permissionPage.getPageItems()); + assertNotNull(permissionPage); + assertNotNull(permissionPage.getPageItems()); found1 = false; found2 = false; @@ -202,8 +210,8 @@ public void createDeleteQueryPermission() { found2 = true; } } - Assert.assertFalse(found1); - Assert.assertTrue(found2); + assertFalse(found1); + assertTrue(found2); // Delete permission: response = request("/nacos/v1/auth/permissions", @@ -211,20 +219,20 @@ public void createDeleteQueryPermission() { .appendParam("action", "r").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); // Query permission: response = request("/nacos/v1/auth/permissions", Params.newParams().appendParam("role", "role1").appendParam("pageNo", "1").appendParam("pageSize", "10") .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.GET); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); permissionPage = JacksonUtils.toObj(response.getBody(), new TypeReference>() { }); - Assert.assertNotNull(permissionPage); - Assert.assertNotNull(permissionPage.getPageItems()); + assertNotNull(permissionPage); + assertNotNull(permissionPage.getPageItems()); found1 = false; found2 = false; @@ -237,7 +245,7 @@ public void createDeleteQueryPermission() { found2 = true; } } - Assert.assertFalse(found1); - Assert.assertFalse(found2); + assertFalse(found1); + assertFalse(found2); } } diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/RoleCoreITCase.java b/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/RoleCoreITCase.java new file mode 100644 index 00000000000..8be22fc02e8 --- /dev/null +++ b/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/RoleCoreITCase.java @@ -0,0 +1,248 @@ +/* + * Copyright 1999-2018 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.test.core.auth; + +import com.alibaba.nacos.Nacos; +import com.alibaba.nacos.common.utils.JacksonUtils; +import com.alibaba.nacos.persistence.model.Page; +import com.alibaba.nacos.plugin.auth.impl.persistence.RoleInfo; +import com.alibaba.nacos.test.base.HttpClient4Test; +import com.alibaba.nacos.test.base.Params; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; + +import java.net.URL; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Integration tests for Nacos role management, including role creation, deletion, and querying. + * + * @author nkorange + * @since 1.2.0 + */ +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +@SpringBootTest(classes = Nacos.class, properties = { + "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +@Disabled("todo fix this test case") +class RoleCoreITCase extends HttpClient4Test { + + @LocalServerPort + private int port; + + private String accessToken; + + @BeforeEach + void init() throws Exception { + TimeUnit.SECONDS.sleep(5L); + String url = String.format("http://localhost:%d/", port); + this.base = new URL(url); + } + + @AfterEach + void destroy() { + + // Delete role: + ResponseEntity response = request("/nacos/v1/auth/roles", + Params.newParams().appendParam("role", "role1").appendParam("username", "username2") + .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + + // Delete role: + response = request("/nacos/v1/auth/roles", + Params.newParams().appendParam("role", "role2").appendParam("username", "username2") + .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + + // Delete a user: + response = request("/nacos/v1/auth/users", + Params.newParams().appendParam("username", "username2").appendParam("accessToken", accessToken).done(), + String.class, HttpMethod.DELETE); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + } + + @Test + void login() { + + ResponseEntity response = request("/nacos/v1/auth/users/login", + Params.newParams().appendParam("username", "nacos").appendParam("password", "nacos").done(), + String.class, HttpMethod.POST); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + JsonNode json = JacksonUtils.toObj(response.getBody()); + assertTrue(json.has("accessToken")); + accessToken = json.get("accessToken").textValue(); + } + + @Test + void createDeleteQueryRole() { + + login(); + + // Create a user: + ResponseEntity response = request("/nacos/v1/auth/users", + Params.newParams().appendParam("username", "username2").appendParam("password", "password1") + .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + + // Create a role: + response = request("/nacos/v1/auth/roles", + Params.newParams().appendParam("role", "role1").appendParam("username", "username2") + .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + + // Query role of user: + response = request("/nacos/v1/auth/roles", + Params.newParams().appendParam("username", "username2").appendParam("pageNo", "1") + .appendParam("pageSize", "10").appendParam("accessToken", accessToken).done(), String.class, + HttpMethod.GET); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + + Page roleInfoPage = JacksonUtils.toObj(response.getBody(), new TypeReference>() { + }); + + assertNotNull(roleInfoPage); + assertNotNull(roleInfoPage.getPageItems()); + boolean found = false; + for (RoleInfo roleInfo : roleInfoPage.getPageItems()) { + if (roleInfo.getRole().equals("role1")) { + found = true; + break; + } + } + assertTrue(found); + + // Add second role to user: + response = request("/nacos/v1/auth/roles", + Params.newParams().appendParam("role", "role2").appendParam("username", "username2") + .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + + // Query roles of user: + response = request("/nacos/v1/auth/roles", + Params.newParams().appendParam("username", "username2").appendParam("pageNo", "1") + .appendParam("pageSize", "10").appendParam("accessToken", accessToken).done(), String.class, + HttpMethod.GET); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + + roleInfoPage = JacksonUtils.toObj(response.getBody(), new TypeReference>() { + }); + + assertNotNull(roleInfoPage); + assertNotNull(roleInfoPage.getPageItems()); + found = false; + boolean found2 = false; + for (RoleInfo roleInfo : roleInfoPage.getPageItems()) { + if (roleInfo.getRole().equals("role1")) { + found = true; + } + if (roleInfo.getRole().equals("role2")) { + found2 = true; + } + if (found && found2) { + break; + } + } + assertTrue(found); + assertTrue(found2); + + // Delete role: + response = request("/nacos/v1/auth/roles", + Params.newParams().appendParam("role", "role2").appendParam("username", "username2") + .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + + // Query roles of user: + response = request("/nacos/v1/auth/roles", + Params.newParams().appendParam("username", "username2").appendParam("pageNo", "1") + .appendParam("pageSize", "10").appendParam("accessToken", accessToken).done(), String.class, + HttpMethod.GET); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + + roleInfoPage = JacksonUtils.toObj(response.getBody(), new TypeReference>() { + }); + + assertNotNull(roleInfoPage); + assertNotNull(roleInfoPage.getPageItems()); + found = false; + found2 = false; + for (RoleInfo roleInfo : roleInfoPage.getPageItems()) { + if (roleInfo.getRole().equals("role1")) { + found = true; + } + if (roleInfo.getRole().equals("role2")) { + found2 = true; + } + } + assertFalse(found2); + assertTrue(found); + + // Delete role: + response = request("/nacos/v1/auth/roles", + Params.newParams().appendParam("role", "role1").appendParam("username", "username2") + .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + + // Query roles of user: + response = request("/nacos/v1/auth/roles", + Params.newParams().appendParam("username", "username2").appendParam("pageNo", "1") + .appendParam("pageSize", "10").appendParam("accessToken", accessToken).done(), String.class, + HttpMethod.GET); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + + roleInfoPage = JacksonUtils.toObj(response.getBody(), new TypeReference>() { + }); + + assertNotNull(roleInfoPage); + assertNotNull(roleInfoPage.getPageItems()); + found = false; + found2 = false; + for (RoleInfo roleInfo : roleInfoPage.getPageItems()) { + if (roleInfo.getRole().equals("role1")) { + found = true; + } + if (roleInfo.getRole().equals("role2")) { + found2 = true; + } + } + assertFalse(found2); + assertFalse(found); + } +} diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/Role_ITCase.java b/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/Role_ITCase.java deleted file mode 100644 index bfdae6359e6..00000000000 --- a/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/Role_ITCase.java +++ /dev/null @@ -1,302 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.nacos.test.core.auth; - -import com.alibaba.nacos.Nacos; -import com.alibaba.nacos.common.utils.JacksonUtils; -import com.alibaba.nacos.plugin.auth.impl.persistence.RoleInfo; -import com.alibaba.nacos.persistence.model.Page; -import com.alibaba.nacos.test.base.HttpClient4Test; -import com.alibaba.nacos.test.base.Params; -import com.fasterxml.jackson.core.type.TypeReference; -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.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; - -import java.net.URL; -import java.util.concurrent.TimeUnit; - -/** - * @author nkorange - * @since 1.2.0 - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"}, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class Role_ITCase extends HttpClient4Test { - - @LocalServerPort - private int port; - - private String accessToken; - - @Before - public void init() throws Exception { - TimeUnit.SECONDS.sleep(5L); - String url = String.format("http://localhost:%d/", port); - this.base = new URL(url); - } - - @After - public void destroy() { - - // Delete role: - ResponseEntity response = request("/nacos/v1/auth/roles", - Params.newParams() - .appendParam("role", "role1") - .appendParam("username", "username2") - .appendParam("accessToken", accessToken) - .done(), - String.class, - HttpMethod.DELETE); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - - // Delete role: - response = request("/nacos/v1/auth/roles", - Params.newParams() - .appendParam("role", "role2") - .appendParam("username", "username2") - .appendParam("accessToken", accessToken) - .done(), - String.class, - HttpMethod.DELETE); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - - // Delete a user: - response = request("/nacos/v1/auth/users", - Params.newParams() - .appendParam("username", "username2") - .appendParam("accessToken", accessToken) - .done(), - String.class, - HttpMethod.DELETE); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - } - - @Test - public void login() { - - ResponseEntity response = request("/nacos/v1/auth/users/login", - Params.newParams() - .appendParam("username", "nacos") - .appendParam("password", "nacos") - .done(), - String.class, - HttpMethod.POST); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - JsonNode json = JacksonUtils.toObj(response.getBody()); - Assert.assertTrue(json.has("accessToken")); - accessToken = json.get("accessToken").textValue(); - } - - @Test - public void createDeleteQueryRole() { - - login(); - - // Create a user: - ResponseEntity response = request("/nacos/v1/auth/users", - Params.newParams() - .appendParam("username", "username2") - .appendParam("password", "password1") - .appendParam("accessToken", accessToken) - .done(), - String.class, - HttpMethod.POST); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - - // Create a role: - response = request("/nacos/v1/auth/roles", - Params.newParams() - .appendParam("role", "role1") - .appendParam("username", "username2") - .appendParam("accessToken", accessToken) - .done(), - String.class, - HttpMethod.POST); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - - // Query role of user: - response = request("/nacos/v1/auth/roles", - Params.newParams() - .appendParam("username", "username2") - .appendParam("pageNo", "1") - .appendParam("pageSize", "10") - .appendParam("accessToken", accessToken) - .done(), - String.class, - HttpMethod.GET); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - - Page roleInfoPage = JacksonUtils.toObj(response.getBody(), new TypeReference>() {}); - - Assert.assertNotNull(roleInfoPage); - Assert.assertNotNull(roleInfoPage.getPageItems()); - boolean found = false; - for (RoleInfo roleInfo : roleInfoPage.getPageItems()) { - if (roleInfo.getRole().equals("role1")) { - found = true; - break; - } - } - Assert.assertTrue(found); - - // Add second role to user: - response = request("/nacos/v1/auth/roles", - Params.newParams() - .appendParam("role", "role2") - .appendParam("username", "username2") - .appendParam("accessToken", accessToken) - .done(), - String.class, - HttpMethod.POST); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - - // Query roles of user: - response = request("/nacos/v1/auth/roles", - Params.newParams() - .appendParam("username", "username2") - .appendParam("pageNo", "1") - .appendParam("pageSize", "10") - .appendParam("accessToken", accessToken) - .done(), - String.class, - HttpMethod.GET); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - - roleInfoPage = JacksonUtils.toObj(response.getBody(), new TypeReference>() {}); - - Assert.assertNotNull(roleInfoPage); - Assert.assertNotNull(roleInfoPage.getPageItems()); - found = false; - boolean found2 = false; - for (RoleInfo roleInfo : roleInfoPage.getPageItems()) { - if (roleInfo.getRole().equals("role1")) { - found = true; - } - if (roleInfo.getRole().equals("role2")) { - found2 = true; - } - if (found && found2) { - break; - } - } - Assert.assertTrue(found); - Assert.assertTrue(found2); - - // Delete role: - response = request("/nacos/v1/auth/roles", - Params.newParams() - .appendParam("role", "role2") - .appendParam("username", "username2") - .appendParam("accessToken", accessToken) - .done(), - String.class, - HttpMethod.DELETE); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - - // Query roles of user: - response = request("/nacos/v1/auth/roles", - Params.newParams() - .appendParam("username", "username2") - .appendParam("pageNo", "1") - .appendParam("pageSize", "10") - .appendParam("accessToken", accessToken) - .done(), - String.class, - HttpMethod.GET); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - - roleInfoPage = JacksonUtils.toObj(response.getBody(), new TypeReference>() {}); - - Assert.assertNotNull(roleInfoPage); - Assert.assertNotNull(roleInfoPage.getPageItems()); - found = false; - found2 = false; - for (RoleInfo roleInfo : roleInfoPage.getPageItems()) { - if (roleInfo.getRole().equals("role1")) { - found = true; - } - if (roleInfo.getRole().equals("role2")) { - found2 = true; - } - } - Assert.assertFalse(found2); - Assert.assertTrue(found); - - // Delete role: - response = request("/nacos/v1/auth/roles", - Params.newParams() - .appendParam("role", "role1") - .appendParam("username", "username2") - .appendParam("accessToken", accessToken) - .done(), - String.class, - HttpMethod.DELETE); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - - // Query roles of user: - response = request("/nacos/v1/auth/roles", - Params.newParams() - .appendParam("username", "username2") - .appendParam("pageNo", "1") - .appendParam("pageSize", "10") - .appendParam("accessToken", accessToken) - .done(), - String.class, - HttpMethod.GET); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - - roleInfoPage = JacksonUtils.toObj(response.getBody(), new TypeReference>() {}); - - Assert.assertNotNull(roleInfoPage); - Assert.assertNotNull(roleInfoPage.getPageItems()); - found = false; - found2 = false; - for (RoleInfo roleInfo : roleInfoPage.getPageItems()) { - if (roleInfo.getRole().equals("role1")) { - found = true; - } - if (roleInfo.getRole().equals("role2")) { - found2 = true; - } - } - Assert.assertFalse(found2); - Assert.assertFalse(found); - } -} diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/UserCoreITCase.java b/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/UserCoreITCase.java new file mode 100644 index 00000000000..7bb4963bc18 --- /dev/null +++ b/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/UserCoreITCase.java @@ -0,0 +1,247 @@ +/* + * Copyright 1999-2018 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.test.core.auth; + +import com.alibaba.nacos.Nacos; +import com.alibaba.nacos.common.utils.JacksonUtils; +import com.alibaba.nacos.persistence.model.Page; +import com.alibaba.nacos.plugin.auth.impl.persistence.User; +import com.alibaba.nacos.plugin.auth.impl.utils.PasswordEncoderUtil; +import com.alibaba.nacos.test.base.HttpClient4Test; +import com.alibaba.nacos.test.base.Params; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +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.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import java.net.URL; +import java.util.concurrent.TimeUnit; + +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.assertTrue; + +/** + * Integration tests for user management in Nacos, including user creation, deletion, updating, and permissions. + * + * @author nkorange + * @since 1.2.0 + */ +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +@ExtendWith(SpringExtension.class) +@SpringBootTest(classes = Nacos.class, properties = { + "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +class UserCoreITCase extends HttpClient4Test { + + @LocalServerPort + private int port; + + private String accessToken; + + @BeforeEach + void init() throws Exception { + TimeUnit.SECONDS.sleep(5L); + String url = String.format("http://localhost:%d/", port); + this.base = new URL(url); + } + + @AfterEach + void destroy() { + + // Delete a user: + ResponseEntity response = request("/nacos/v1/auth/users", + Params.newParams().appendParam("username", "username1").appendParam("accessToken", accessToken).done(), + String.class, HttpMethod.DELETE); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + + // Delete a user: + request("/nacos/v1/auth/users", + Params.newParams().appendParam("username", "username2").appendParam("accessToken", accessToken).done(), + String.class, HttpMethod.DELETE); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + + System.setProperty("nacos.core.auth.enabled", "false"); + } + + @Test + void login() { + ResponseEntity response = login("nacos", "nacos"); + assertTrue(response.getStatusCode().is2xxSuccessful()); + JsonNode json = JacksonUtils.toObj(response.getBody()); + assertTrue(json.has("accessToken")); + accessToken = json.get("accessToken").textValue(); + } + + private ResponseEntity login(String username, String password) { + return request("/nacos/v1/auth/users/login", + Params.newParams().appendParam("username", username).appendParam("password", password).done(), + String.class, HttpMethod.POST); + } + + @Test + void createUpdateDeleteUser() { + + login(); + + // Create a user: + ResponseEntity response = request("/nacos/v1/auth/users", + Params.newParams().appendParam("username", "username1").appendParam("password", "password1") + .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + + // Query a user: + response = request("/nacos/v1/auth/users", + Params.newParams().appendParam("pageNo", "1").appendParam("pageSize", String.valueOf(Integer.MAX_VALUE)) + .appendParam("accessToken", accessToken).done(), String.class); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + + Page userPage = JacksonUtils.toObj(response.getBody(), new TypeReference>() { + }); + + assertNotNull(userPage); + assertNotNull(userPage.getPageItems()); + assertTrue(userPage.getPageItems().size() > 0); + + boolean found = false; + for (User user : userPage.getPageItems()) { + if ("username1".equals(user.getUsername()) && PasswordEncoderUtil.matches("password1", + user.getPassword())) { + found = true; + break; + } + } + assertTrue(found); + + // Update a user: + response = request("/nacos/v1/auth/users", + Params.newParams().appendParam("username", "username1").appendParam("newPassword", "password2") + .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.PUT); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + + // Query a user: + response = request("/nacos/v1/auth/users", + Params.newParams().appendParam("pageNo", "1").appendParam("pageSize", String.valueOf(Integer.MAX_VALUE)) + .appendParam("accessToken", accessToken).done(), String.class); + + userPage = JacksonUtils.toObj(response.getBody(), new TypeReference>() { + }); + + assertNotNull(userPage); + assertNotNull(userPage.getPageItems()); + assertTrue(userPage.getPageItems().size() > 0); + + found = false; + for (User user : userPage.getPageItems()) { + if ("username1".equals(user.getUsername()) && PasswordEncoderUtil.matches("password2", + user.getPassword())) { + found = true; + break; + } + } + assertTrue(found); + + // Delete a user: + response = request("/nacos/v1/auth/users", + Params.newParams().appendParam("username", "username1").appendParam("accessToken", accessToken).done(), + String.class, HttpMethod.DELETE); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + + // Query a user: + response = request("/nacos/v1/auth/users", + Params.newParams().appendParam("pageNo", "1").appendParam("pageSize", String.valueOf(Integer.MAX_VALUE)) + .appendParam("accessToken", accessToken).done(), String.class); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + + userPage = JacksonUtils.toObj(response.getBody(), new TypeReference>() { + }); + + assertNotNull(userPage); + assertNotNull(userPage.getPageItems()); + assertTrue(userPage.getPageItems().size() > 0); + + found = false; + for (User user : userPage.getPageItems()) { + if ("username1".equals(user.getUsername())) { + found = true; + break; + } + } + assertFalse(found); + } + + @Test + void updateUserWithPermission() { + System.setProperty("nacos.core.auth.enabled", "true"); + + // admin login + login(); + + // create username1 + ResponseEntity response = request("/nacos/v1/auth/users", + Params.newParams().appendParam("username", "username1").appendParam("password", "password1") + .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST); + assertTrue(response.getStatusCode().is2xxSuccessful()); + // create username2 + response = request("/nacos/v1/auth/users", + Params.newParams().appendParam("username", "username2").appendParam("password", "password2") + .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST); + assertTrue(response.getStatusCode().is2xxSuccessful()); + + // user login + response = login("username1", "password1"); + assertTrue(response.getStatusCode().is2xxSuccessful()); + + response = login("username2", "password2"); + assertTrue(response.getStatusCode().is2xxSuccessful()); + + // update by admin + response = request("/nacos/v1/auth/users", + Params.newParams().appendParam("username", "username1").appendParam("newPassword", "password3") + .appendParam("accessToken", accessToken).done(), String.class, HttpMethod.PUT); + assertTrue(response.getStatusCode().is2xxSuccessful()); + + // update by same user + String user1AccessToken = JacksonUtils.toObj(response.getBody()).get("accessToken").textValue(); + response = request("/nacos/v1/auth/users", + Params.newParams().appendParam("username", "username1").appendParam("newPassword", "password4") + .appendParam("accessToken", user1AccessToken).done(), String.class, HttpMethod.PUT); + assertTrue(response.getStatusCode().is2xxSuccessful()); + + // update by another user + String user2AccessToken = JacksonUtils.toObj(response.getBody()).get("accessToken").textValue(); + response = request("/nacos/v1/auth/users", + Params.newParams().appendParam("username", "username1").appendParam("newPassword", "password5") + .appendParam("accessToken", user2AccessToken).done(), String.class, HttpMethod.PUT); + assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); + } +} diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/User_ITCase.java b/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/User_ITCase.java deleted file mode 100644 index 9cb710e5dba..00000000000 --- a/test/core-test/src/test/java/com/alibaba/nacos/test/core/auth/User_ITCase.java +++ /dev/null @@ -1,302 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.nacos.test.core.auth; - -import com.alibaba.nacos.Nacos; -import com.alibaba.nacos.common.utils.JacksonUtils; -import com.alibaba.nacos.persistence.model.Page; -import com.alibaba.nacos.plugin.auth.impl.persistence.User; -import com.alibaba.nacos.plugin.auth.impl.utils.PasswordEncoderUtil; -import com.alibaba.nacos.test.base.HttpClient4Test; -import com.alibaba.nacos.test.base.Params; -import com.fasterxml.jackson.core.type.TypeReference; -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.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; - -import java.net.URL; -import java.util.concurrent.TimeUnit; - -/** - * @author nkorange - * @since 1.2.0 - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"}, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class User_ITCase extends HttpClient4Test { - - @LocalServerPort - private int port; - - private String accessToken; - - @Before - public void init() throws Exception { - TimeUnit.SECONDS.sleep(5L); - String url = String.format("http://localhost:%d/", port); - this.base = new URL(url); - } - - @After - public void destroy() { - - // Delete a user: - ResponseEntity response = request("/nacos/v1/auth/users", - Params.newParams() - .appendParam("username", "username1") - .appendParam("accessToken", accessToken) - .done(), - String.class, - HttpMethod.DELETE); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - - // Delete a user: - request("/nacos/v1/auth/users", - Params.newParams() - .appendParam("username", "username2") - .appendParam("accessToken", accessToken) - .done(), - String.class, - HttpMethod.DELETE); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - - System.setProperty("nacos.core.auth.enabled", "false"); - } - - - @Test - public void login() { - - ResponseEntity response = login("nacos", "nacos"); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - JsonNode json = JacksonUtils.toObj(response.getBody()); - Assert.assertTrue(json.has("accessToken")); - accessToken = json.get("accessToken").textValue(); - } - - private ResponseEntity login(String username,String password){ - return request("/nacos/v1/auth/users/login", - Params.newParams() - .appendParam("username", username) - .appendParam("password", password) - .done(), - String.class, - HttpMethod.POST); - } - - @Test - public void createUpdateDeleteUser() { - - login(); - - // Create a user: - ResponseEntity response = request("/nacos/v1/auth/users", - Params.newParams() - .appendParam("username", "username1") - .appendParam("password", "password1") - .appendParam("accessToken", accessToken) - .done(), - String.class, - HttpMethod.POST); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - - // Query a user: - response = request("/nacos/v1/auth/users", - Params.newParams() - .appendParam("pageNo", "1") - .appendParam("pageSize", String.valueOf(Integer.MAX_VALUE)) - .appendParam("accessToken", accessToken) - .done(), - String.class); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - - Page userPage = JacksonUtils.toObj(response.getBody(), new TypeReference>() {}); - - Assert.assertNotNull(userPage); - Assert.assertNotNull(userPage.getPageItems()); - Assert.assertTrue(userPage.getPageItems().size() > 0); - - boolean found = false; - for (User user : userPage.getPageItems()) { - if ("username1".equals(user.getUsername()) && - PasswordEncoderUtil.matches("password1", user.getPassword())) { - found = true; - break; - } - } - Assert.assertTrue(found); - - // Update a user: - response = request("/nacos/v1/auth/users", - Params.newParams() - .appendParam("username", "username1") - .appendParam("newPassword", "password2") - .appendParam("accessToken", accessToken) - .done(), - String.class, - HttpMethod.PUT); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - - // Query a user: - response = request("/nacos/v1/auth/users", - Params.newParams() - .appendParam("pageNo", "1") - .appendParam("pageSize", String.valueOf(Integer.MAX_VALUE)) - .appendParam("accessToken", accessToken) - .done(), - String.class); - - userPage = JacksonUtils.toObj(response.getBody(), new TypeReference>() {}); - - Assert.assertNotNull(userPage); - Assert.assertNotNull(userPage.getPageItems()); - Assert.assertTrue(userPage.getPageItems().size() > 0); - - found = false; - for (User user : userPage.getPageItems()) { - if ("username1".equals(user.getUsername()) && - PasswordEncoderUtil.matches("password2", user.getPassword())) { - found = true; - break; - } - } - Assert.assertTrue(found); - - // Delete a user: - response = request("/nacos/v1/auth/users", - Params.newParams() - .appendParam("username", "username1") - .appendParam("accessToken", accessToken) - .done(), - String.class, - HttpMethod.DELETE); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - - // Query a user: - response = request("/nacos/v1/auth/users", - Params.newParams() - .appendParam("pageNo", "1") - .appendParam("pageSize", String.valueOf(Integer.MAX_VALUE)) - .appendParam("accessToken", accessToken) - .done(), - String.class); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - - userPage = JacksonUtils.toObj(response.getBody(), new TypeReference>() {}); - - Assert.assertNotNull(userPage); - Assert.assertNotNull(userPage.getPageItems()); - Assert.assertTrue(userPage.getPageItems().size() > 0); - - found = false; - for (User user : userPage.getPageItems()) { - if ("username1".equals(user.getUsername())) { - found = true; - break; - } - } - Assert.assertFalse(found); - } - - @Test - public void updateUserWithPermission() { - System.setProperty("nacos.core.auth.enabled", "true"); - - // admin login - login(); - - // create username1 - ResponseEntity response = request("/nacos/v1/auth/users", - Params.newParams() - .appendParam("username", "username1") - .appendParam("password", "password1") - .appendParam("accessToken", accessToken) - .done(), - String.class, - HttpMethod.POST); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - // create username2 - response= request("/nacos/v1/auth/users", - Params.newParams() - .appendParam("username", "username2") - .appendParam("password", "password2") - .appendParam("accessToken", accessToken) - .done(), - String.class, - HttpMethod.POST); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - - // user login - response = login("username1", "password1"); - String user1AccessToken = JacksonUtils.toObj(response.getBody()).get("accessToken").textValue(); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - - response = login("username2", "password2"); - String user2AccessToken = JacksonUtils.toObj(response.getBody()).get("accessToken").textValue(); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - - // update by admin - response = request("/nacos/v1/auth/users", - Params.newParams() - .appendParam("username", "username1") - .appendParam("newPassword", "password3") - .appendParam("accessToken", accessToken) - .done(), - String.class, - HttpMethod.PUT); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - - // update by same user - response = request("/nacos/v1/auth/users", - Params.newParams() - .appendParam("username", "username1") - .appendParam("newPassword", "password4") - .appendParam("accessToken", user1AccessToken) - .done(), - String.class, - HttpMethod.PUT); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - - // update by another user - response = request("/nacos/v1/auth/users", - Params.newParams() - .appendParam("username", "username1") - .appendParam("newPassword", "password5") - .appendParam("accessToken", user2AccessToken) - .done(), - String.class, - HttpMethod.PUT); - Assert.assertEquals(response.getStatusCode(), HttpStatus.FORBIDDEN); - } -} diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/core/cluster/MemberLookupCoreITCase.java b/test/core-test/src/test/java/com/alibaba/nacos/test/core/cluster/MemberLookupCoreITCase.java new file mode 100644 index 00000000000..8622d5812c5 --- /dev/null +++ b/test/core-test/src/test/java/com/alibaba/nacos/test/core/cluster/MemberLookupCoreITCase.java @@ -0,0 +1,157 @@ +/* + * Copyright 1999-2018 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.test.core.cluster; + +import com.alibaba.nacos.api.exception.NacosException; +import com.alibaba.nacos.common.utils.StringUtils; +import com.alibaba.nacos.core.cluster.Member; +import com.alibaba.nacos.core.cluster.MemberLookup; +import com.alibaba.nacos.core.cluster.ServerMemberManager; +import com.alibaba.nacos.core.cluster.lookup.AddressServerMemberLookup; +import com.alibaba.nacos.core.cluster.lookup.FileConfigMemberLookup; +import com.alibaba.nacos.core.cluster.lookup.LookupFactory; +import com.alibaba.nacos.core.cluster.lookup.StandaloneMemberLookup; +import com.alibaba.nacos.sys.env.EnvUtil; +import com.alibaba.nacos.sys.utils.DiskUtils; +import com.alibaba.nacos.sys.utils.InetUtils; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.springframework.core.env.StandardEnvironment; +import org.springframework.mock.web.MockServletContext; + +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Integration test case for Member Lookup functionality, validating different lookup strategies: file configuration, + * standalone mode, and address server lookup. + * + * @author liaochuntao + */ +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +@TestMethodOrder(MethodName.class) +class MemberLookupCoreITCase { + + private final String path = Paths.get(System.getProperty("user.home"), "/member_look").toString(); + + private final String name = "cluster.conf"; + + ServerMemberManager memberManager; + + @BeforeEach + void before() throws Exception { + System.setProperty("nacos.home", path); + EnvUtil.setEnvironment(new StandardEnvironment()); + EnvUtil.setIsStandalone(false); + System.out.println(EnvUtil.getStandaloneMode()); + + System.out.println(Arrays.toString(LookupFactory.LookupType.values())); + DiskUtils.forceMkdir(path); + DiskUtils.forceMkdir(Paths.get(path, "conf").toString()); + File file = Paths.get(path, "conf", name).toFile(); + DiskUtils.touch(file); + String ip = InetUtils.getSelfIP(); + DiskUtils.writeFile(file, (ip + ":8848," + ip + ":8847," + ip + ":8849").getBytes(StandardCharsets.UTF_8), + false); + + try { + memberManager = new ServerMemberManager(new MockServletContext()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @AfterEach + void after() throws Exception { + try { + memberManager.shutdown(); + } catch (Throwable ex) { + ex.printStackTrace(); + } + DiskUtils.deleteDirectory(path); + } + + @Test + void testLookupFileConfig() throws Exception { + try { + LookupFactory.createLookUp(memberManager); + } catch (Throwable ignore) { + } + MemberLookup lookup = LookupFactory.getLookUp(); + System.out.println(lookup); + assertInstanceOf(FileConfigMemberLookup.class, lookup); + func(lookup); + } + + @Test + void testLookupStandalone() throws Exception { + EnvUtil.setIsStandalone(true); + try { + LookupFactory.createLookUp(memberManager); + } catch (Throwable ignore) { + + } finally { + EnvUtil.setIsStandalone(false); + } + MemberLookup lookup = LookupFactory.getLookUp(); + System.out.println(lookup); + assertInstanceOf(StandaloneMemberLookup.class, lookup); + } + + @Test + void testLookupAddressServer() throws Exception { + EnvUtil.setIsStandalone(false); + System.out.println(EnvUtil.getClusterConfFilePath()); + DiskUtils.deleteFile(Paths.get(path, "conf").toString(), "cluster.conf"); + System.out.println(new File(EnvUtil.getClusterConfFilePath()).exists()); + try { + LookupFactory.createLookUp(memberManager); + } catch (Throwable ignore) { + } + MemberLookup lookup = LookupFactory.getLookUp(); + System.out.println(lookup); + assertInstanceOf(AddressServerMemberLookup.class, lookup); + try { + func(lookup); + } catch (NacosException e) { + System.out.println(e.getErrMsg()); + assertTrue(StringUtils.containsIgnoreCase(e.getErrMsg(), "jmenv.tbsite.net")); + } + } + + private void func(MemberLookup lookup) throws Exception { + func(lookup, 3); + } + + private void func(MemberLookup lookup, int expectSize) throws Exception { + lookup.start(); + Map tmp = memberManager.getServerList(); + System.out.println(lookup + " : " + tmp); + assertEquals(expectSize, tmp.size()); + } + +} diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/core/cluster/MemberLookup_ITCase.java b/test/core-test/src/test/java/com/alibaba/nacos/test/core/cluster/MemberLookup_ITCase.java deleted file mode 100644 index 5ecfd34f400..00000000000 --- a/test/core-test/src/test/java/com/alibaba/nacos/test/core/cluster/MemberLookup_ITCase.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.nacos.test.core.cluster; - -import com.alibaba.nacos.api.exception.NacosException; -import com.alibaba.nacos.core.cluster.Member; -import com.alibaba.nacos.core.cluster.ServerMemberManager; -import com.alibaba.nacos.core.cluster.lookup.AddressServerMemberLookup; -import com.alibaba.nacos.core.cluster.lookup.FileConfigMemberLookup; -import com.alibaba.nacos.core.cluster.lookup.LookupFactory; -import com.alibaba.nacos.core.cluster.MemberLookup; -import com.alibaba.nacos.core.cluster.lookup.StandaloneMemberLookup; -import com.alibaba.nacos.sys.env.EnvUtil; -import com.alibaba.nacos.sys.utils.DiskUtils; -import com.alibaba.nacos.sys.utils.InetUtils; -import com.alibaba.nacos.common.utils.StringUtils; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; -import org.springframework.core.env.StandardEnvironment; -import org.springframework.mock.web.MockServletContext; - -import java.io.File; -import java.nio.charset.StandardCharsets; -import java.nio.file.Paths; -import java.util.Arrays; -import java.util.Map; - -/** - * @author liaochuntao - */ -@FixMethodOrder(value = MethodSorters.NAME_ASCENDING) -public class MemberLookup_ITCase { - - static final String path = Paths.get(System.getProperty("user.home"), "/member_look") - .toString(); - - static final String name = "cluster.conf"; - - ServerMemberManager memberManager; - - @Before - public void before() throws Exception { - System.setProperty("nacos.home", path); - EnvUtil.setEnvironment(new StandardEnvironment()); - EnvUtil.setIsStandalone(false); - System.out.println(EnvUtil.getStandaloneMode()); - - System.out.println(Arrays.toString(LookupFactory.LookupType.values())); - DiskUtils.forceMkdir(path); - DiskUtils.forceMkdir(Paths.get(path, "conf").toString()); - File file = Paths.get(path, "conf", name).toFile(); - DiskUtils.touch(file); - String ip = InetUtils.getSelfIP(); - DiskUtils.writeFile(file, (ip + ":8848," + ip + ":8847," + ip + ":8849").getBytes( - StandardCharsets.UTF_8), false); - - try { - memberManager = new ServerMemberManager( - new MockServletContext()); - } - catch (Exception e) { - e.printStackTrace(); - } - } - - @After - public void after() throws Exception { - try { - memberManager.shutdown(); - } catch (Throwable ex) { - ex.printStackTrace(); - } - DiskUtils.deleteDirectory(path); - } - - @Test - public void test_a_lookup_file_config() throws Exception { - try { - LookupFactory.createLookUp(memberManager); - } - catch (Throwable ignore) { - } - MemberLookup lookup = LookupFactory.getLookUp(); - System.out.println(lookup); - Assert.assertTrue(lookup instanceof FileConfigMemberLookup); - func(lookup); - } - - @Test - public void test_b_lookup_standalone() throws Exception { - EnvUtil.setIsStandalone(true); - try { - LookupFactory.createLookUp(memberManager); - } - catch (Throwable ignore) { - - } finally { - EnvUtil.setIsStandalone(false); - } - MemberLookup lookup = LookupFactory.getLookUp(); - System.out.println(lookup); - Assert.assertTrue(lookup instanceof StandaloneMemberLookup); - } - - @Test - public void test_c_lookup_address_server() throws Exception { - EnvUtil.setIsStandalone(false); - System.out.println(EnvUtil.getClusterConfFilePath()); - DiskUtils.deleteFile(Paths.get(path, "conf").toString(), "cluster.conf"); - System.out.println(new File(EnvUtil.getClusterConfFilePath()).exists()); - try { - LookupFactory.createLookUp(memberManager); - } - catch (Throwable ignore) { - } - MemberLookup lookup = LookupFactory.getLookUp(); - System.out.println(lookup); - Assert.assertTrue(lookup instanceof AddressServerMemberLookup); - try { - func(lookup); - } catch (NacosException e) { - System.out.println(e.getErrMsg()); - Assert.assertTrue(StringUtils.containsIgnoreCase(e.getErrMsg(), "jmenv.tbsite.net")); - } - } - - private void func(MemberLookup lookup) throws Exception { - func(lookup, 3); - } - - private void func(MemberLookup lookup, int expectSize) throws Exception { - lookup.start(); - Map tmp = memberManager.getServerList(); - System.out.println(lookup + " : " + tmp); - Assert.assertEquals(expectSize, tmp.size()); - } - -} diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/core/cluster/ServerMemberManager_ITCase.java b/test/core-test/src/test/java/com/alibaba/nacos/test/core/cluster/ServerMemberManagerCoreITCase.java similarity index 80% rename from test/core-test/src/test/java/com/alibaba/nacos/test/core/cluster/ServerMemberManager_ITCase.java rename to test/core-test/src/test/java/com/alibaba/nacos/test/core/cluster/ServerMemberManagerCoreITCase.java index 000daea9795..8a13bb29abe 100644 --- a/test/core-test/src/test/java/com/alibaba/nacos/test/core/cluster/ServerMemberManager_ITCase.java +++ b/test/core-test/src/test/java/com/alibaba/nacos/test/core/cluster/ServerMemberManagerCoreITCase.java @@ -20,20 +20,19 @@ import com.alibaba.nacos.common.notify.NotifyCenter; import com.alibaba.nacos.common.notify.listener.Subscriber; import com.alibaba.nacos.core.cluster.Member; -import com.alibaba.nacos.core.cluster.MembersChangeEvent; import com.alibaba.nacos.core.cluster.MemberUtil; +import com.alibaba.nacos.core.cluster.MembersChangeEvent; import com.alibaba.nacos.core.cluster.NodeState; import com.alibaba.nacos.core.cluster.ServerMemberManager; -import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.env.Constants; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import com.alibaba.nacos.sys.env.EnvUtil; +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.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.springframework.core.env.StandardEnvironment; import org.springframework.mock.web.MockServletContext; @@ -50,42 +49,47 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Cluster node manages unit tests. * * @author liaochuntao */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class ServerMemberManager_ITCase { +// todo fix +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +@TestMethodOrder(MethodName.class) +class ServerMemberManagerCoreITCase { private ServerMemberManager memberManager; - @BeforeClass - public static void initClass() throws Exception { + @BeforeAll + static void initClass() throws Exception { System.setProperty(Constants.NACOS_SERVER_IP, "127.0.0.1"); System.setProperty("server.port", "8847"); EnvUtil.setIsStandalone(true); EnvUtil.setEnvironment(new StandardEnvironment()); } - @AfterClass - public static void destroyClass() { + @AfterAll + static void destroyClass() { System.clearProperty(Constants.NACOS_SERVER_IP); System.clearProperty("server.port"); } - @Before - public void before() throws Exception { + @BeforeEach + void before() throws Exception { memberManager = new ServerMemberManager(new MockServletContext()); } - @After - public void after() throws Exception { + @AfterEach + void after() throws Exception { memberManager.shutdown(); } @Test - public void testKisFirst() { + void testKisFirst() { String firstIp = "127.0.0.1:8847"; String secondIp = "127.0.0.1:8848"; String thirdIp = "127.0.0.1:8849"; @@ -99,11 +103,11 @@ public void testKisFirst() { Collections.sort(members); List ss = MemberUtil.simpleMembers(members); - Assert.assertEquals(ss.get(0), members.get(0).getAddress()); + assertEquals(ss.get(0), members.get(0).getAddress()); } @Test - public void testMemberChange() throws Exception { + void testMemberChange() throws Exception { AtomicInteger integer = new AtomicInteger(0); CountDownLatch latch = new CountDownLatch(1); @@ -129,15 +133,15 @@ public Class subscribeType() { members.add(Member.builder().ip("115.159.3.213").port(8848).build()); boolean changed = memberManager.memberJoin(members); - Assert.assertTrue(changed); + assertTrue(changed); latch.await(10_000L, TimeUnit.MILLISECONDS); - Assert.assertEquals(1, integer.get()); + assertEquals(1, integer.get()); } @Test - public void testMemberHealthCheck() throws Exception { + void testMemberHealthCheck() throws Exception { AtomicReference> healthMembers = new AtomicReference<>(); CountDownLatch first = new CountDownLatch(1); CountDownLatch second = new CountDownLatch(1); @@ -145,7 +149,8 @@ public void testMemberHealthCheck() throws Exception { @Override public void onEvent(MembersChangeEvent event) { System.out.println(event); - healthMembers.set(MemberUtil.selectTargetMembers(event.getMembers(), member -> !NodeState.DOWN.equals(member.getState()))); + healthMembers.set(MemberUtil.selectTargetMembers(event.getMembers(), + member -> !NodeState.DOWN.equals(member.getState()))); if (first.getCount() == 1) { first.countDown(); return; @@ -174,20 +179,20 @@ public Class subscribeType() { memberManager.memberJoin(map.values()); - first.await(); + first.await(); //fix blocking Set copy = new HashSet<>(firstMemberList); copy.removeAll(healthMembers.get()); - Assert.assertEquals(2, copy.size()); + assertEquals(2, copy.size()); Member member = map.get(firstIp); member.setState(NodeState.DOWN); - Assert.assertTrue(memberManager.update(member)); + assertTrue(memberManager.update(member)); - second.await(); + second.await(); //fix blocking copy = new HashSet<>(firstMemberList); copy.removeAll(healthMembers.get()); - Assert.assertEquals(3, copy.size()); - Assert.assertTrue(copy.contains(map.get(firstIp))); + assertEquals(3, copy.size()); + assertTrue(copy.contains(map.get(firstIp))); } } diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/core/code/ControllerMethodsCache_ITCase.java b/test/core-test/src/test/java/com/alibaba/nacos/test/core/code/ControllerMethodsCacheCoreITCase.java similarity index 86% rename from test/core-test/src/test/java/com/alibaba/nacos/test/core/code/ControllerMethodsCache_ITCase.java rename to test/core-test/src/test/java/com/alibaba/nacos/test/core/code/ControllerMethodsCacheCoreITCase.java index 80801b1ebed..64f8e167c82 100644 --- a/test/core-test/src/test/java/com/alibaba/nacos/test/core/code/ControllerMethodsCache_ITCase.java +++ b/test/core-test/src/test/java/com/alibaba/nacos/test/core/code/ControllerMethodsCacheCoreITCase.java @@ -16,66 +16,71 @@ package com.alibaba.nacos.test.core.code; -import static org.junit.Assert.assertEquals; - import com.alibaba.nacos.core.code.ControllerMethodsCache; import com.alibaba.nacos.sys.env.EnvUtil; -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Map; import org.apache.catalina.connector.Connector; import org.apache.catalina.connector.Request; import org.apache.tomcat.util.buf.MessageBytes; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** + * Integration test case for validating ControllerMethodsCache functionality,ensuring correct method retrieval based on + * different request parameters. + * * @author horizonzy * @since 1.3.2 */ -public class ControllerMethodsCache_ITCase { - +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +class ControllerMethodsCacheCoreITCase { + private ControllerMethodsCache methodsCache; - - @Before - public void setUp() throws Exception { + + @BeforeEach + void setUp() throws Exception { methodsCache = new ControllerMethodsCache(); EnvUtil.setContextPath("/nacos"); methodsCache.initClassMethod("com.alibaba.nacos.config.server.controller"); } - + @Test - public void testGetMethod() { + void testGetMethod() { Request getConfigRequest = buildGetConfigRequest(); Method getConfigMethod = methodsCache.getMethod(getConfigRequest); assertEquals("getConfig", getConfigMethod.getName()); - + Request searchConfigRequest = buildSearchConfigRequest(); Method searchConfigMethod = methodsCache.getMethod(searchConfigRequest); assertEquals("searchConfig", searchConfigMethod.getName()); - + Request detailConfigInfoRequest = buildDetailConfigInfoRequest(); Method detailConfigInfoMethod = methodsCache.getMethod(detailConfigInfoRequest); assertEquals("detailConfigInfo", detailConfigInfoMethod.getName()); } - + private Request buildDetailConfigInfoRequest() { Map parameter = new HashMap<>(); parameter.put("show", "all"); return buildRequest("GET", "/nacos/v1/cs/configs", parameter); } - + private Request buildSearchConfigRequest() { Map parameter = new HashMap<>(); parameter.put("search", "accurate"); return buildRequest("GET", "/nacos/v1/cs/configs", parameter); } - + private Request buildGetConfigRequest() { Map parameter = new HashMap<>(); return buildRequest("GET", "/nacos/v1/cs/configs", parameter); } - + private Request buildRequest(String method, String path, Map parameters) { Connector connector = new Connector(); connector.setParseBodyMethods("GET,POST,PUT,DELETE,PATCH"); @@ -92,5 +97,5 @@ private Request buildRequest(String method, String path, Map par } return request; } - + } diff --git a/test/core-test/src/test/java/com/alibaba/nacos/test/smoke/nacosSmoke_ITCase.java b/test/core-test/src/test/java/com/alibaba/nacos/test/smoke/NacosSmokeCoreITCase.java similarity index 68% rename from test/core-test/src/test/java/com/alibaba/nacos/test/smoke/nacosSmoke_ITCase.java rename to test/core-test/src/test/java/com/alibaba/nacos/test/smoke/NacosSmokeCoreITCase.java index 650b4bb4b14..1b55a1d96bc 100644 --- a/test/core-test/src/test/java/com/alibaba/nacos/test/smoke/nacosSmoke_ITCase.java +++ b/test/core-test/src/test/java/com/alibaba/nacos/test/smoke/NacosSmokeCoreITCase.java @@ -17,25 +17,26 @@ package com.alibaba.nacos.test.smoke; import org.apache.log4j.Logger; -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; -public class nacosSmoke_ITCase { - - private static Logger logger = Logger.getLogger(nacosSmoke_ITCase.class); - - @Before - public void setUp() { +@SuppressWarnings("checkstyle:AbbreviationAsWordInName") +class NacosSmokeCoreITCase { + + private static Logger logger = Logger.getLogger(NacosSmokeCoreITCase.class); + + @BeforeEach + void setUp() { logger.info(String.format("nacosSmoke_ITCase: %s;", "setUp")); } - - @After - public void tearDown() { + + @AfterEach + void tearDown() { logger.info(String.format("nacosSmoke_ITCase: %s;", "tearDown")); } - + @Test - public void testSmoke() { + void testSmoke() { } } diff --git a/test/naming-test/src/test/java/com/alibaba/nacos/test/base/BaseClusterTest.java b/test/naming-test/src/test/java/com/alibaba/nacos/test/base/BaseClusterTest.java index fd464a12c47..24b8969f80e 100644 --- a/test/naming-test/src/test/java/com/alibaba/nacos/test/base/BaseClusterTest.java +++ b/test/naming-test/src/test/java/com/alibaba/nacos/test/base/BaseClusterTest.java @@ -24,16 +24,16 @@ import com.alibaba.nacos.common.notify.Event; import com.alibaba.nacos.common.notify.NotifyCenter; import com.alibaba.nacos.common.notify.listener.Subscriber; -import com.alibaba.nacos.persistence.model.event.RaftDbErrorEvent; -import com.alibaba.nacos.core.persistence.DistributedDatabaseOperateImpl; import com.alibaba.nacos.consistency.ProtocolMetaData; import com.alibaba.nacos.consistency.cp.CPProtocol; import com.alibaba.nacos.consistency.cp.MetadataKey; +import com.alibaba.nacos.core.persistence.DistributedDatabaseOperateImpl; +import com.alibaba.nacos.persistence.model.event.RaftDbErrorEvent; import com.alibaba.nacos.sys.env.EnvUtil; import com.alibaba.nacos.sys.utils.DiskUtils; import com.alibaba.nacos.sys.utils.InetUtils; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; @@ -57,19 +57,19 @@ public class BaseClusterTest extends HttpClient4Test { + protected static final AtomicBoolean[] FINISHED = new AtomicBoolean[] {new AtomicBoolean(false), new AtomicBoolean(false), + new AtomicBoolean(false)}; + private static final Logger LOGGER = LoggerFactory.getLogger(BaseClusterTest.class); + protected static final NacosRestTemplate NACOS_REST_TEMPLATE = HttpClientBeanHolder.getNacosRestTemplate(LOGGER); + protected static NamingService inaming7; protected static NamingService inaming8; protected static NamingService inaming9; - protected static final NacosRestTemplate NACOS_REST_TEMPLATE = HttpClientBeanHolder.getNacosRestTemplate(LOGGER); - - protected static final AtomicBoolean[] FINISHED = new AtomicBoolean[] {new AtomicBoolean(false), - new AtomicBoolean(false), new AtomicBoolean(false)}; - protected static Map applications = new HashMap<>(); protected static String clusterInfo; @@ -93,8 +93,8 @@ public Class subscribeType() { }); } - @BeforeClass - public static void before() throws Exception { + @BeforeAll + static void before() throws Exception { CountDownLatch latch = new CountDownLatch(3); @@ -142,8 +142,8 @@ public static void before() throws Exception { TimeUnit.SECONDS.sleep(20L); } - @AfterClass - public static void after() throws Exception { + @AfterAll + static void after() throws Exception { CountDownLatch latch = new CountDownLatch(applications.size()); for (ConfigurableApplicationContext context : applications.values()) { new Thread(() -> { @@ -177,15 +177,14 @@ private static void run(final int index, final CountDownLatch latch, final Class Map properties = new HashMap<>(); properties.put("server.port", "884" + (7 + index)); properties.put("nacos.home", path); - properties.put("nacos.logs.path", - Paths.get(System.getProperty("user.home"), "nacos-" + index, "/logs/").toString()); + properties.put("nacos.logs.path", Paths.get(System.getProperty("user.home"), "nacos-" + index, "/logs/").toString()); properties.put("spring.jmx.enabled", false); properties.put("nacos.core.snowflake.worker-id", index + 1); MapPropertySource propertySource = new MapPropertySource("nacos_cluster_test", properties); ConfigurableEnvironment environment = new StandardServletEnvironment(); environment.getPropertySources().addFirst(propertySource); - SpringApplication cluster = new SpringApplicationBuilder(cls).web(WebApplicationType.SERVLET) - .environment(environment).properties(clusterInfo).properties("embeddedStorage=true").build(); + SpringApplication cluster = new SpringApplicationBuilder(cls).web(WebApplicationType.SERVLET).environment(environment) + .properties(clusterInfo).properties("embeddedStorage=true").build(); ConfigurableApplicationContext context = cluster.run(); diff --git a/test/naming-test/src/test/java/com/alibaba/nacos/test/base/HttpClient4Test.java b/test/naming-test/src/test/java/com/alibaba/nacos/test/base/HttpClient4Test.java index 5fd2f0fb7af..1b48c13868d 100644 --- a/test/naming-test/src/test/java/com/alibaba/nacos/test/base/HttpClient4Test.java +++ b/test/naming-test/src/test/java/com/alibaba/nacos/test/base/HttpClient4Test.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.test.base; import org.springframework.beans.factory.annotation.Autowired; @@ -33,35 +34,31 @@ * @since 1.2.0 */ public class HttpClient4Test { - + protected URL base; - + @Autowired protected TestRestTemplate restTemplate; - + protected ResponseEntity request(String path, MultiValueMap params, Class clazz) { - + HttpHeaders headers = new HttpHeaders(); - + HttpEntity entity = new HttpEntity(headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.base.toString() + path) - .queryParams(params); - - return this.restTemplate.exchange( - builder.toUriString(), HttpMethod.GET, entity, clazz); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.base.toString() + path).queryParams(params); + + return this.restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, clazz); } - + protected ResponseEntity request(String path, MultiValueMap params, Class clazz, HttpMethod httpMethod) { - + HttpHeaders headers = new HttpHeaders(); - + HttpEntity entity = new HttpEntity(headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.base.toString() + path) - .queryParams(params); - - return this.restTemplate.exchange( - builder.toUriString(), httpMethod, entity, clazz); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.base.toString() + path).queryParams(params); + + return this.restTemplate.exchange(builder.toUriString(), httpMethod, entity, clazz); } } diff --git a/test/naming-test/src/test/java/com/alibaba/nacos/test/base/Params.java b/test/naming-test/src/test/java/com/alibaba/nacos/test/base/Params.java index aacdd631db0..3506b2edfc2 100644 --- a/test/naming-test/src/test/java/com/alibaba/nacos/test/base/Params.java +++ b/test/naming-test/src/test/java/com/alibaba/nacos/test/base/Params.java @@ -19,21 +19,47 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; +/** + * Helper class for building HTTP request parameters using Spring's MultiValueMap. Provides methods to construct and + * append parameters. + */ public class Params { private MultiValueMap paramMap; + /** + * Private constructor to enforce usage of static factory method `newParams()`. + */ + private Params() { + this.paramMap = new LinkedMultiValueMap<>(); + } + + /** + * Static factory method to create a new instance of Params. + * + * @return A new Params instance. + */ public static Params newParams() { - Params params = new Params(); - params.paramMap = new LinkedMultiValueMap(); - return params; + return new Params(); } + /** + * Appends a parameter with the specified name and value to the parameter map. + * + * @param name The parameter name. + * @param value The parameter value. + * @return This Params instance for method chaining. + */ public Params appendParam(String name, String value) { this.paramMap.add(name, value); return this; } + /** + * Retrieves the constructed parameter map. + * + * @return The MultiValueMap containing the appended parameters. + */ public MultiValueMap done() { return paramMap; } diff --git a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/AbstractInstanceOperate_ITCase.java b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/AbstractInstanceOperate_ITCase.java index cb3f32007d3..ae2dec1b957 100644 --- a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/AbstractInstanceOperate_ITCase.java +++ b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/AbstractInstanceOperate_ITCase.java @@ -25,11 +25,8 @@ import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.client.naming.remote.NamingClientProxy; import com.alibaba.nacos.common.utils.ReflectUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.server.LocalServerPort; @@ -42,12 +39,12 @@ import static com.alibaba.nacos.test.naming.NamingBase.TEST_PORT; import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; public abstract class AbstractInstanceOperate_ITCase { - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private NamingService naming; @LocalServerPort @@ -56,7 +53,7 @@ public abstract class AbstractInstanceOperate_ITCase { @Value("${server.servlet.context-path}") private String contextPath; - @Before + @BeforeEach public void init() throws Exception { NamingBase.prepareServer(port, contextPath); @@ -93,7 +90,7 @@ public void dregDomTest() throws Exception { verifyInstanceList(instances, 1, serviceName); instances = naming.getAllInstances(serviceName); - Assert.assertEquals(1, instances.size()); + assertEquals(1, instances.size()); naming.deregisterInstance(serviceName, "127.0.0.1", TEST_PORT); @@ -101,7 +98,7 @@ public void dregDomTest() throws Exception { instances = naming.getAllInstances(serviceName); - Assert.assertEquals(instances.size(), 0); + assertEquals(0, instances.size()); } /** @@ -122,7 +119,7 @@ public void dregDomClusterTest() throws Exception { verifyInstanceList(instances, 1, serviceName); instances = naming.getAllInstances(serviceName); - Assert.assertEquals(1, instances.size()); + assertEquals(1, instances.size()); naming.deregisterInstance(serviceName, "127.0.0.1", TEST_PORT, "c1"); @@ -130,7 +127,7 @@ public void dregDomClusterTest() throws Exception { instances = naming.getAllInstances(serviceName); - Assert.assertEquals(0, instances.size()); + assertEquals(0, instances.size()); } /** @@ -149,7 +146,7 @@ public void dregLastDomTest() throws Exception { instances = naming.getAllInstances(serviceName); verifyInstanceList(instances, 1, serviceName); - Assert.assertEquals(1, instances.size()); + assertEquals(1, instances.size()); naming.deregisterInstance(serviceName, "127.0.0.1", TEST_PORT, "c1"); @@ -157,7 +154,7 @@ public void dregLastDomTest() throws Exception { instances = naming.getAllInstances(serviceName); - Assert.assertEquals(0, instances.size()); + assertEquals(0, instances.size()); } private void verifyInstanceList(List instances, int size, String serviceName) throws Exception { @@ -189,7 +186,7 @@ public void regService() throws NacosException, InterruptedException { naming.registerInstance(serviceName, "127.0.0.2", 80, "c2"); List instances = naming.getAllInstances(serviceName); - Assert.assertEquals(1, instances.size()); + assertEquals(1, instances.size()); } /** @@ -207,9 +204,9 @@ public void regDomTest() throws Exception { List instances = naming.getAllInstances(serviceName); - Assert.assertEquals(1, instances.size()); - Assert.assertEquals(instances.get(0).getIp(), NamingBase.TEST_IP_4_DOM_1); - Assert.assertEquals(instances.get(0).getPort(), NamingBase.TEST_PORT); + assertEquals(1, instances.size()); + assertEquals(NamingBase.TEST_IP_4_DOM_1, instances.get(0).getIp()); + assertEquals(NamingBase.TEST_PORT, instances.get(0).getPort()); } /** @@ -224,23 +221,21 @@ public void regDomClusterTest() throws Exception { System.out.println(serviceName); - naming.registerInstance(serviceName, NamingBase.TEST_IP_4_DOM_1, NamingBase.TEST_PORT, - NamingBase.TEST_NEW_CLUSTER_4_DOM_1); + naming.registerInstance(serviceName, NamingBase.TEST_IP_4_DOM_1, NamingBase.TEST_PORT, NamingBase.TEST_NEW_CLUSTER_4_DOM_1); TimeUnit.SECONDS.sleep(3); List instances = naming.getAllInstances(serviceName); - Assert.assertEquals(1, instances.size()); - Assert.assertEquals(instances.get(0).getIp(), NamingBase.TEST_IP_4_DOM_1); - Assert.assertEquals(instances.get(0).getPort(), NamingBase.TEST_PORT); + assertEquals(1, instances.size()); + assertEquals(NamingBase.TEST_IP_4_DOM_1, instances.get(0).getIp()); + assertEquals(NamingBase.TEST_PORT, instances.get(0).getPort()); - List instances2 = naming - .getAllInstances(serviceName, Arrays.asList(NamingBase.TEST_NEW_CLUSTER_4_DOM_1)); + List instances2 = naming.getAllInstances(serviceName, Arrays.asList(NamingBase.TEST_NEW_CLUSTER_4_DOM_1)); - Assert.assertEquals(instances2.size(), 1); - Assert.assertEquals(instances2.get(0).getIp(), NamingBase.TEST_IP_4_DOM_1); - Assert.assertEquals(instances2.get(0).getPort(), NamingBase.TEST_PORT); + assertEquals(1, instances2.size()); + assertEquals(NamingBase.TEST_IP_4_DOM_1, instances2.get(0).getIp()); + assertEquals(NamingBase.TEST_PORT, instances2.get(0).getPort()); } /** @@ -259,9 +254,9 @@ public void regDomWithInstance() throws Exception { List instances = naming.getAllInstances(serviceName); - Assert.assertEquals(instances.size(), 1); + assertEquals(1, instances.size()); - Assert.assertTrue(NamingBase.verifyInstance(i1, instances.get(0))); + assertTrue(NamingBase.verifyInstance(i1, instances.get(0))); } @@ -282,7 +277,7 @@ public void regDomNotHealth() throws Exception { List instances = naming.selectInstances(serviceName, false); - Assert.assertEquals(0, instances.size()); + assertEquals(0, instances.size()); } @Test @@ -305,9 +300,9 @@ public void regServiceWithMetadata() throws Exception { List instances = naming.getAllInstances(serviceName); - Assert.assertEquals(1, instances.size()); - Assert.assertEquals("1.0", instances.get(0).getMetadata().get("version")); - Assert.assertEquals("prod", instances.get(0).getMetadata().get("env")); + assertEquals(1, instances.size()); + assertEquals("1.0", instances.get(0).getMetadata().get("version")); + assertEquals("prod", instances.get(0).getMetadata().get("env")); } @Test @@ -331,7 +326,7 @@ public void regServiceWithTTL() throws Exception { List instances = naming.getAllInstances(serviceName); - Assert.assertEquals(1, instances.size()); + assertEquals(1, instances.size()); naming.deregisterInstance(serviceName, instance); @@ -339,7 +334,7 @@ public void regServiceWithTTL() throws Exception { instances = naming.getAllInstances(serviceName); - Assert.assertEquals(0, instances.size()); + assertEquals(0, instances.size()); } /** @@ -349,22 +344,22 @@ public void regServiceWithTTL() throws Exception { */ @Test public void registerEphemeralInstanceWithInvalidClusterName() throws Exception { - expectedException.expect(Exception.class); - expectedException.expectMessage( - "Param 'cluster' is illegal, illegal characters should not appear in the param."); - - String serviceName = NamingBase.randomDomainName(); - Instance instance = new Instance(); - instance.setIp(NamingBase.TEST_IP_4_DOM_1); - instance.setPort(NamingBase.TEST_PORT); - instance.setWeight(1.0); - instance.setEphemeral(true); - instance.setClusterName("cluster1,cluster2"); - - // Directly invoke `NamingClientProxy.registerService` to skip client-side parameters checking - // in ``NamingService.registerInstance(Instance)``, so we can verify server-side checking is effective or not. - NamingClientProxy clientProxy = (NamingClientProxy) ReflectUtils.getFieldValue(naming, "clientProxy"); - clientProxy.registerService(serviceName, Constants.DEFAULT_GROUP, instance); + Throwable exception = assertThrows(Exception.class, () -> { + + String serviceName = NamingBase.randomDomainName(); + Instance instance = new Instance(); + instance.setIp(NamingBase.TEST_IP_4_DOM_1); + instance.setPort(NamingBase.TEST_PORT); + instance.setWeight(1.0); + instance.setEphemeral(true); + instance.setClusterName("cluster1,cluster2"); + + // Directly invoke `NamingClientProxy.registerService` to skip client-side parameters checking + // in ``NamingService.registerInstance(Instance)``, so we can verify server-side checking is effective or not. + NamingClientProxy clientProxy = (NamingClientProxy) ReflectUtils.getFieldValue(naming, "clientProxy"); + clientProxy.registerService(serviceName, Constants.DEFAULT_GROUP, instance); + }); + assertTrue(exception.getMessage().contains("Param 'cluster' is illegal, illegal characters should not appear in the param.")); } /** @@ -374,21 +369,21 @@ public void registerEphemeralInstanceWithInvalidClusterName() throws Exception { */ @Test public void registerPersistentInstanceWithInvalidClusterName() throws Exception { - expectedException.expect(NacosException.class); - expectedException.expectMessage( - "Param 'cluster' is illegal, illegal characters should not appear in the param."); - - String serviceName = NamingBase.randomDomainName(); - Instance instance = new Instance(); - instance.setIp(NamingBase.TEST_IP_4_DOM_1); - instance.setPort(NamingBase.TEST_PORT); - instance.setWeight(1.0); - instance.setEphemeral(false); - instance.setClusterName("cluster1,cluster2"); - - // Directly invoke `NamingClientProxy.registerService` to skip client-side parameters checking - // in ``NamingService.registerInstance(Instance)``, so we can verify server-side checking is effective or not. - NamingClientProxy clientProxy = (NamingClientProxy) ReflectUtils.getFieldValue(naming, "clientProxy"); - clientProxy.registerService(serviceName, Constants.DEFAULT_GROUP, instance); + Throwable exception = assertThrows(NacosException.class, () -> { + + String serviceName = NamingBase.randomDomainName(); + Instance instance = new Instance(); + instance.setIp(NamingBase.TEST_IP_4_DOM_1); + instance.setPort(NamingBase.TEST_PORT); + instance.setWeight(1.0); + instance.setEphemeral(false); + instance.setClusterName("cluster1,cluster2"); + + // Directly invoke `NamingClientProxy.registerService` to skip client-side parameters checking + // in ``NamingService.registerInstance(Instance)``, so we can verify server-side checking is effective or not. + NamingClientProxy clientProxy = (NamingClientProxy) ReflectUtils.getFieldValue(naming, "clientProxy"); + clientProxy.registerService(serviceName, Constants.DEFAULT_GROUP, instance); + }); + assertTrue(exception.getMessage().contains("Param 'cluster' is illegal, illegal characters should not appear in the param.")); } } diff --git a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/CPInstancesAPI_ITCase.java b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/CPInstancesAPI_ITCase.java index d06c985a90d..351454fabf8 100644 --- a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/CPInstancesAPI_ITCase.java +++ b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/CPInstancesAPI_ITCase.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.test.naming; import com.alibaba.nacos.Nacos; @@ -25,83 +26,70 @@ import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.test.base.Params; 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.springframework.beans.factory.annotation.Autowired; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.util.MultiValueMap; -import org.springframework.web.util.UriComponentsBuilder; import java.net.URL; import java.util.List; import java.util.Properties; import java.util.concurrent.TimeUnit; -import static com.alibaba.nacos.test.naming.NamingBase.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author nkorange */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"}, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class CPInstancesAPI_ITCase { - +@SpringBootTest(classes = Nacos.class, properties = { + "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +class CPInstancesAPI_ITCase extends NamingBase { + private NamingService naming; + private NamingService naming1; + private NamingService naming2; - + @LocalServerPort private int port; - - private URL base; - - @Autowired - private TestRestTemplate restTemplate; - - @Before - public void setUp() throws Exception { + + @BeforeEach + void setUp() throws Exception { String url = String.format("http://localhost:%d/", port); this.base = new URL(url); - + naming = NamingFactory.createNamingService("127.0.0.1" + ":" + port); - + Properties properties = new Properties(); properties.put(PropertyKeyConst.NAMESPACE, TEST_NAMESPACE_1); properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1" + ":" + port); naming1 = NamingFactory.createNamingService(properties); - - + properties = new Properties(); properties.put(PropertyKeyConst.NAMESPACE, TEST_NAMESPACE_2); properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1" + ":" + port); naming2 = NamingFactory.createNamingService(properties); + isNamingServerReady(); } - - @After - public void cleanup() throws Exception { + + @AfterEach + void cleanup() throws Exception { } - + /** * @TCDescription : 根据serviceName创建服务, 通过registerInstance接口注册实例, ephemeral为true * @TestStep : * @ExpectResult : */ @Test - public void registerInstance_ephemeral_true() throws Exception { + void registerInstance_ephemeral_true() throws Exception { String serviceName = NamingBase.randomDomainName(); - + Instance instance = new Instance(); instance.setEphemeral(true); //是否临时实例 instance.setClusterName("c1"); @@ -112,17 +100,17 @@ public void registerInstance_ephemeral_true() throws Exception { naming1.deregisterInstance(serviceName, TEST_GROUP_1, instance); namingServiceDelete(serviceName, TEST_NAMESPACE_1, TEST_GROUP_1); } - + /** * @TCDescription : 根据serviceName创建服务, 通过registerInstance接口注册实例, ephemeral为false * @TestStep : * @ExpectResult : */ @Test - public void registerInstance_ephemeral_false() throws Exception { + void registerInstance_ephemeral_false() throws Exception { String serviceName = NamingBase.randomDomainName(); namingServiceCreate(serviceName, TEST_NAMESPACE_1, TEST_GROUP_1); - + Instance instance = new Instance(); instance.setEphemeral(false); //是否临时实例 instance.setClusterName("c1"); @@ -133,17 +121,17 @@ public void registerInstance_ephemeral_false() throws Exception { naming1.deregisterInstance(serviceName, TEST_GROUP_1, instance); namingServiceDelete(serviceName, TEST_NAMESPACE_1, TEST_GROUP_1); } - + /** * @TCDescription : 根据serviceName创建服务, 通过registerInstance接口注册实例, ephemeral为false * @TestStep : * @ExpectResult : */ @Test - public void registerInstance_ephemeral_false_deregisterInstance() throws Exception { + void registerInstance_ephemeral_false_deregisterInstance() throws Exception { String serviceName = NamingBase.randomDomainName(); namingServiceCreate(serviceName, TEST_NAMESPACE_1, TEST_GROUP_1); - + Instance instance = new Instance(); instance.setEphemeral(false); //是否临时实例 instance.setClusterName("c1"); @@ -152,320 +140,247 @@ public void registerInstance_ephemeral_false_deregisterInstance() throws Excepti naming1.registerInstance(serviceName, TEST_GROUP_1, instance); naming1.deregisterInstance(serviceName, TEST_GROUP_1, instance); TimeUnit.SECONDS.sleep(3L); - + namingServiceDelete(serviceName, TEST_NAMESPACE_1, TEST_GROUP_1); } - + /** * @TCDescription : 根据serviceName创建服务 * @TestStep : * @ExpectResult : */ @Test - public void createService() throws Exception { + void createService() throws Exception { String serviceName = NamingBase.randomDomainName(); namingServiceCreate(serviceName, TEST_NAMESPACE_1); - + namingServiceDelete(serviceName, TEST_NAMESPACE_1); } - + /** * @TCDescription : 根据serviceName创建服务, 存在实例不能被删除, 抛异常 * @TestStep : * @ExpectResult : */ @Test - public void deleteService_hasInstace() { + void deleteService_hasInstace() { String serviceName = NamingBase.randomDomainName(); - + ResponseEntity registerResponse = request(NamingBase.NAMING_CONTROLLER_PATH + "/instance", - Params.newParams() - .appendParam("serviceName", serviceName) - .appendParam("ip", "11.11.11.11") - .appendParam("port", "80") - .appendParam("namespaceId", TEST_NAMESPACE_1) - .done(), - String.class, - HttpMethod.POST); - Assert.assertTrue(registerResponse.getStatusCode().is2xxSuccessful()); - + Params.newParams().appendParam("serviceName", serviceName).appendParam("ip", "11.11.11.11") + .appendParam("port", "80").appendParam("namespaceId", TEST_NAMESPACE_1).done(), String.class, + HttpMethod.POST); + assertTrue(registerResponse.getStatusCode().is2xxSuccessful()); + ResponseEntity deleteServiceResponse = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", - Params.newParams() - .appendParam("serviceName", serviceName) - .appendParam("namespaceId", TEST_NAMESPACE_1) - .done(), - String.class, - HttpMethod.DELETE); - Assert.assertTrue(deleteServiceResponse.getStatusCode().is4xxClientError()); + Params.newParams().appendParam("serviceName", serviceName).appendParam("namespaceId", TEST_NAMESPACE_1) + .done(), String.class, HttpMethod.DELETE); + assertTrue(deleteServiceResponse.getStatusCode().is4xxClientError()); } - + /** * @TCDescription : 根据serviceName修改服务,并通过HTTP接口获取服务信息 * @TestStep : * @ExpectResult : */ @Test - public void getService() throws Exception { + void getService() throws Exception { String serviceName = NamingBase.randomDomainName(); namingServiceCreate(serviceName, TEST_NAMESPACE_1); - + ResponseEntity response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", - Params.newParams() - .appendParam("serviceName", serviceName) - .appendParam("namespaceId", TEST_NAMESPACE_1) - .appendParam("protectThreshold", "0.5") - .done(), - String.class, - HttpMethod.PUT); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - Assert.assertEquals("ok", response.getBody()); - + Params.newParams().appendParam("serviceName", serviceName).appendParam("namespaceId", TEST_NAMESPACE_1) + .appendParam("protectThreshold", "0.5").done(), String.class, HttpMethod.PUT); + assertTrue(response.getStatusCode().is2xxSuccessful()); + assertEquals("ok", response.getBody()); + //get service response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", - Params.newParams() - .appendParam("serviceName", serviceName) - .appendParam("namespaceId", TEST_NAMESPACE_1) - .done(), - String.class); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - + Params.newParams().appendParam("serviceName", serviceName).appendParam("namespaceId", TEST_NAMESPACE_1) + .done(), String.class); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + JsonNode json = JacksonUtils.toObj(response.getBody()); - Assert.assertEquals(serviceName, json.get("name").textValue()); - Assert.assertEquals("0.5", json.get("protectThreshold").asText()); - + assertEquals(serviceName, json.get("name").textValue()); + assertEquals("0.5", json.get("protectThreshold").asText()); + namingServiceDelete(serviceName, TEST_NAMESPACE_1); } - + /** * @TCDescription : 根据serviceName修改服务,并通过接口获取服务信息 * @TestStep : * @ExpectResult : */ @Test - public void getService_1() throws Exception { + void getService_1() throws Exception { String serviceName = NamingBase.randomDomainName(); ListView listView = naming1.getServicesOfServer(1, 50); - + namingServiceCreate(serviceName, TEST_NAMESPACE_1); TimeUnit.SECONDS.sleep(5L); - + ListView listView1 = naming1.getServicesOfServer(1, 50); - Assert.assertEquals(listView.getCount()+1, listView1.getCount()); - + assertEquals(listView.getCount() + 1, listView1.getCount()); + namingServiceDelete(serviceName, TEST_NAMESPACE_1); } - + /** * @TCDescription : 获取服务list信息 * @TestStep : * @ExpectResult : */ @Test - public void listService() throws Exception { + void listService() throws Exception { String serviceName = NamingBase.randomDomainName(); ListView listView = naming.getServicesOfServer(1, 50); namingServiceCreate(serviceName, Constants.DEFAULT_NAMESPACE_ID); - + //get service ResponseEntity response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service/list", - Params.newParams() - .appendParam("serviceName", serviceName) - .appendParam("pageNo", "1") - .appendParam("pageSize", "150") - .done(), - String.class); - + Params.newParams().appendParam("serviceName", serviceName).appendParam("pageNo", "1") + .appendParam("pageSize", "150").done(), String.class); + System.out.println("json = " + response.getBody()); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); JsonNode json = JacksonUtils.toObj(response.getBody()); int count = json.get("count").intValue(); - Assert.assertEquals(listView.getCount() + 1, count); - + assertEquals(listView.getCount() + 1, count); + namingServiceDelete(serviceName, Constants.DEFAULT_NAMESPACE_ID); } - + /** * @TCDescription : 根据serviceName创建服务,注册持久化实例, 注销实例,删除服务 * @TestStep : * @ExpectResult : */ @Test - public void registerInstance_api() throws Exception { + void registerInstance_api() throws Exception { String serviceName = NamingBase.randomDomainName(); namingServiceCreate(serviceName, Constants.DEFAULT_NAMESPACE_ID); - + instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, "33.33.33.33", TEST_PORT2_4_DOM_1); - + ResponseEntity response = request(NAMING_CONTROLLER_PATH + "/instance/list", - Params.newParams() - .appendParam("serviceName", serviceName) //获取naming中的实例 - .appendParam("namespaceId", Constants.DEFAULT_NAMESPACE_ID) - .done(), - String.class); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例 + .appendParam("namespaceId", Constants.DEFAULT_NAMESPACE_ID).done(), String.class); + assertTrue(response.getStatusCode().is2xxSuccessful()); JsonNode json = JacksonUtils.toObj(response.getBody()); - Assert.assertEquals(1, json.get("hosts").size()); - + assertEquals(1, json.get("hosts").size()); + instanceDeregister(serviceName, Constants.DEFAULT_NAMESPACE_ID, "33.33.33.33", TEST_PORT2_4_DOM_1); - + namingServiceDelete(serviceName, Constants.DEFAULT_NAMESPACE_ID); } - + /** * @TCDescription : 根据serviceName创建服务,注册持久化实例, 查询实例,注销实例,删除服务 * @TestStep : * @ExpectResult : */ @Test - public void registerInstance_query() throws Exception { + void registerInstance_query() throws Exception { String serviceName = NamingBase.randomDomainName(); namingServiceCreate(serviceName, Constants.DEFAULT_NAMESPACE_ID); - + instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, "33.33.33.33", TEST_PORT2_4_DOM_1); - + List instances = naming.getAllInstances(serviceName); - Assert.assertEquals(1, instances.size()); - Assert.assertEquals("33.33.33.33", instances.get(0).getIp()); - + assertEquals(1, instances.size()); + assertEquals("33.33.33.33", instances.get(0).getIp()); + instanceDeregister(serviceName, Constants.DEFAULT_NAMESPACE_ID, "33.33.33.33", TEST_PORT2_4_DOM_1); - + TimeUnit.SECONDS.sleep(3L); instances = naming.getAllInstances(serviceName); - Assert.assertEquals(0, instances.size()); - + assertEquals(0, instances.size()); + namingServiceDelete(serviceName, Constants.DEFAULT_NAMESPACE_ID); } - + /** * @TCDescription : 根据serviceName创建服务,注册不同group的2个非持久化实例, 注销实例,删除服务 * @TestStep : * @ExpectResult : */ @Test - public void registerInstance_2() throws Exception { + void registerInstance_2() throws Exception { String serviceName = NamingBase.randomDomainName(); namingServiceCreate(serviceName, Constants.DEFAULT_NAMESPACE_ID); namingServiceCreate(serviceName, Constants.DEFAULT_NAMESPACE_ID, TEST_GROUP_1); - + instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, "33.33.33.33", TEST_PORT2_4_DOM_1); instanceRegister(serviceName, Constants.DEFAULT_NAMESPACE_ID, TEST_GROUP_1, "22.22.22.22", TEST_PORT2_4_DOM_1); - + ResponseEntity response = request(NAMING_CONTROLLER_PATH + "/instance/list", - Params.newParams() - .appendParam("serviceName", serviceName) //获取naming中的实例 - .appendParam("namespaceId", Constants.DEFAULT_NAMESPACE_ID) - .done(), - String.class); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例 + .appendParam("namespaceId", Constants.DEFAULT_NAMESPACE_ID).done(), String.class); + assertTrue(response.getStatusCode().is2xxSuccessful()); JsonNode json = JacksonUtils.toObj(response.getBody()); - Assert.assertEquals(1, json.get("hosts").size()); - + assertEquals(1, json.get("hosts").size()); + instanceDeregister(serviceName, Constants.DEFAULT_NAMESPACE_ID, "33.33.33.33", TEST_PORT2_4_DOM_1); - instanceDeregister(serviceName, Constants.DEFAULT_NAMESPACE_ID, TEST_GROUP_1, "22.22.22.22", TEST_PORT2_4_DOM_1); - + instanceDeregister(serviceName, Constants.DEFAULT_NAMESPACE_ID, TEST_GROUP_1, "22.22.22.22", + TEST_PORT2_4_DOM_1); + namingServiceDelete(serviceName, Constants.DEFAULT_NAMESPACE_ID); namingServiceDelete(serviceName, Constants.DEFAULT_NAMESPACE_ID, TEST_GROUP_1); } - + private void instanceDeregister(String serviceName, String namespace, String ip, String port) { instanceDeregister(serviceName, namespace, Constants.DEFAULT_GROUP, ip, port); } - + private void instanceDeregister(String serviceName, String namespace, String groupName, String ip, String port) { ResponseEntity response = request(NamingBase.NAMING_CONTROLLER_PATH + "/instance", - Params.newParams() - .appendParam("serviceName", serviceName) - .appendParam("ip", ip) - .appendParam("port", port) - .appendParam("namespaceId", namespace) - .appendParam("groupName", groupName) - .appendParam("ephemeral", "false") - .done(), - String.class, - HttpMethod.DELETE); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + Params.newParams().appendParam("serviceName", serviceName).appendParam("ip", ip) + .appendParam("port", port).appendParam("namespaceId", namespace) + .appendParam("groupName", groupName).appendParam("ephemeral", "false").done(), String.class, + HttpMethod.DELETE); + assertTrue(response.getStatusCode().is2xxSuccessful()); } - + private void instanceRegister(String serviceName, String namespace, String groupName, String ip, String port) { ResponseEntity response = request(NamingBase.NAMING_CONTROLLER_PATH + "/instance", - Params.newParams() - .appendParam("serviceName", serviceName) - .appendParam("ip", ip) - .appendParam("port", port) - .appendParam("namespaceId", namespace) - .appendParam("groupName", groupName) - .appendParam("ephemeral", "false") - .done(), - String.class, - HttpMethod.POST); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + Params.newParams().appendParam("serviceName", serviceName).appendParam("ip", ip) + .appendParam("port", port).appendParam("namespaceId", namespace) + .appendParam("groupName", groupName).appendParam("ephemeral", "false").done(), String.class, + HttpMethod.POST); + assertTrue(response.getStatusCode().is2xxSuccessful()); } + private void instanceRegister(String serviceName, String namespace, String ip, String port) { instanceRegister(serviceName, namespace, Constants.DEFAULT_GROUP, ip, port); } - + private void namingServiceCreate(String serviceName, String namespace) { namingServiceCreate(serviceName, namespace, Constants.DEFAULT_GROUP); } - + private void namingServiceCreate(String serviceName, String namespace, String groupName) { ResponseEntity response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", - Params.newParams() - .appendParam("serviceName", serviceName) - .appendParam("protectThreshold", "0.3") - .appendParam("namespaceId", namespace) - .appendParam("groupName", groupName) - .done(), - String.class, - HttpMethod.POST); + Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.3") + .appendParam("namespaceId", namespace).appendParam("groupName", groupName).done(), String.class, + HttpMethod.POST); System.out.println(response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - Assert.assertEquals("ok", response.getBody()); + assertTrue(response.getStatusCode().is2xxSuccessful()); + assertEquals("ok", response.getBody()); } - + private void namingServiceDelete(String serviceName, String namespace) { namingServiceDelete(serviceName, namespace, Constants.DEFAULT_GROUP); } - + private void namingServiceDelete(String serviceName, String namespace, String groupName) { //delete service ResponseEntity response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", - Params.newParams() - .appendParam("serviceName", serviceName) - .appendParam("namespaceId", namespace) - .appendParam("groupName", groupName) - .done(), - String.class, - HttpMethod.DELETE); + Params.newParams().appendParam("serviceName", serviceName).appendParam("namespaceId", namespace) + .appendParam("groupName", groupName).done(), String.class, HttpMethod.DELETE); System.out.println(response); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - Assert.assertEquals("ok", response.getBody()); - } - - private ResponseEntity request(String path, MultiValueMap params, Class clazz) { - - HttpHeaders headers = new HttpHeaders(); - - HttpEntity entity = new HttpEntity(headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.base.toString() + path) - .queryParams(params); - - return this.restTemplate.exchange( - builder.toUriString(), HttpMethod.GET, entity, clazz); - } - - private ResponseEntity request(String path, MultiValueMap params, Class clazz, HttpMethod httpMethod) { - - HttpHeaders headers = new HttpHeaders(); - - HttpEntity entity = new HttpEntity(headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.base.toString() + path) - .queryParams(params); - - return this.restTemplate.exchange( - builder.toUriString(), httpMethod, entity, clazz); + assertTrue(response.getStatusCode().is2xxSuccessful()); + assertEquals("ok", response.getBody()); } } diff --git a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/ClientBeat_ITCase.java b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/ClientBeat_ITCase.java index 75d0103db61..b2f7a66f619 100644 --- a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/ClientBeat_ITCase.java +++ b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/ClientBeat_ITCase.java @@ -21,33 +21,33 @@ import com.alibaba.nacos.api.naming.NamingFactory; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; -import com.alibaba.nacos.test.base.Params; import com.alibaba.nacos.common.utils.StringUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import com.alibaba.nacos.test.base.Params; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; import java.net.URL; import java.util.List; import java.util.concurrent.TimeUnit; -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"}, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class ClientBeat_ITCase extends NamingBase { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +@SpringBootTest(classes = Nacos.class, properties = { + "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +class ClientBeat_ITCase extends NamingBase { + private NamingService naming; + @LocalServerPort private int port; - - @Before - public void init() throws Exception { + + @BeforeEach + void init() throws Exception { NamingBase.prepareServer(port); if (naming == null) { naming = NamingFactory.createNamingService("127.0.0.1" + ":" + port); @@ -62,82 +62,74 @@ public void init() throws Exception { String url = String.format("http://localhost:%d/", port); this.base = new URL(url); } - + @Test - public void testLightBeat() throws Exception { - + void testLightBeat() throws Exception { + String serviceName = randomDomainName(); - + naming.registerInstance(serviceName, "1.2.3.4", 81); - + Instance instance = new Instance(); instance.setIp("1.2.3.4"); instance.setPort(80); instance.addMetadata("k1", "v1"); instance.addMetadata("k2", "v2"); naming.registerInstance(serviceName, instance); - + TimeUnit.SECONDS.sleep(2L); - + List list = naming.getAllInstances(serviceName); - Assert.assertEquals(1, list.size()); + assertEquals(1, list.size()); for (Instance instance1 : list) { - Assert.assertEquals("1.2.3.4", instance1.getIp()); - Assert.assertTrue(instance1.getPort() == 80 || instance1.getPort() == 81); + assertEquals("1.2.3.4", instance1.getIp()); + assertTrue(instance1.getPort() == 80 || instance1.getPort() == 81); if (instance1.getPort() == 80) { - Assert.assertEquals("v1", instance1.getMetadata().getOrDefault("k1", StringUtils.EMPTY)); - Assert.assertEquals("v2", instance1.getMetadata().getOrDefault("k2", StringUtils.EMPTY)); + assertEquals("v1", instance1.getMetadata().getOrDefault("k1", StringUtils.EMPTY)); + assertEquals("v2", instance1.getMetadata().getOrDefault("k2", StringUtils.EMPTY)); } } - + // Sleep 35 seconds and see if instance list not changed: TimeUnit.SECONDS.sleep(35L); - + list = naming.getAllInstances(serviceName); - Assert.assertEquals(1, list.size()); + assertEquals(1, list.size()); for (Instance instance1 : list) { - Assert.assertEquals("1.2.3.4", instance1.getIp()); - Assert.assertTrue(instance1.getPort() == 80 || instance1.getPort() == 81); + assertEquals("1.2.3.4", instance1.getIp()); + assertTrue(instance1.getPort() == 80 || instance1.getPort() == 81); if (instance1.getPort() == 80) { - Assert.assertEquals("v1", instance1.getMetadata().getOrDefault("k1", StringUtils.EMPTY)); - Assert.assertEquals("v2", instance1.getMetadata().getOrDefault("k2", StringUtils.EMPTY)); + assertEquals("v1", instance1.getMetadata().getOrDefault("k1", StringUtils.EMPTY)); + assertEquals("v2", instance1.getMetadata().getOrDefault("k2", StringUtils.EMPTY)); } } - + // Change the light beat switch of server: ResponseEntity response = request(NamingBase.NAMING_CONTROLLER_PATH + "/operator/switches", - Params.newParams() - .appendParam("entry", "lightBeatEnabled") - .appendParam("value", "false") - .done(), - String.class, - HttpMethod.PUT); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - + Params.newParams().appendParam("entry", "lightBeatEnabled").appendParam("value", "false").done(), String.class, + HttpMethod.PUT); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + // Sleep 35 seconds and see if instance list not changed: TimeUnit.SECONDS.sleep(35L); - + list = naming.getAllInstances(serviceName); - Assert.assertEquals(1, list.size()); + assertEquals(1, list.size()); for (Instance instance1 : list) { - Assert.assertEquals("1.2.3.4", instance1.getIp()); - Assert.assertTrue(instance1.getPort() == 80 || instance1.getPort() == 81); + assertEquals("1.2.3.4", instance1.getIp()); + assertTrue(instance1.getPort() == 80 || instance1.getPort() == 81); if (instance1.getPort() == 80) { - Assert.assertEquals("v1", instance1.getMetadata().getOrDefault("k1", StringUtils.EMPTY)); - Assert.assertEquals("v2", instance1.getMetadata().getOrDefault("k2", StringUtils.EMPTY)); + assertEquals("v1", instance1.getMetadata().getOrDefault("k1", StringUtils.EMPTY)); + assertEquals("v2", instance1.getMetadata().getOrDefault("k2", StringUtils.EMPTY)); } } - + // Reset the light beat switch of server: response = request(NamingBase.NAMING_CONTROLLER_PATH + "/operator/switches", - Params.newParams() - .appendParam("entry", "lightBeatEnabled") - .appendParam("value", "true") - .done(), - String.class, - HttpMethod.PUT); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + Params.newParams().appendParam("entry", "lightBeatEnabled").appendParam("value", "true").done(), String.class, + HttpMethod.PUT); + + assertTrue(response.getStatusCode().is2xxSuccessful()); } } diff --git a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/InstanceOperate_ITCase.java b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/InstanceOperate_ITCase.java index 82968c3ceed..35a320507b5 100644 --- a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/InstanceOperate_ITCase.java +++ b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/InstanceOperate_ITCase.java @@ -17,9 +17,7 @@ package com.alibaba.nacos.test.naming; import com.alibaba.nacos.Nacos; -import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; /** * Created by wangtong.wt on 2018/6/20. @@ -27,9 +25,8 @@ * @author wangtong.wt * @date 2018/6/20 */ -@RunWith(SpringRunner.class) @SpringBootTest(classes = Nacos.class, properties = { "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) public class InstanceOperate_ITCase extends AbstractInstanceOperate_ITCase { - + } diff --git a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/MultiTenant_ITCase.java b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/MultiTenant_ITCase.java index 4577472ca51..9f9b2d8a89a 100644 --- a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/MultiTenant_ITCase.java +++ b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/MultiTenant_ITCase.java @@ -26,15 +26,11 @@ import com.alibaba.nacos.api.naming.listener.NamingEvent; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; -import com.alibaba.nacos.sys.utils.ApplicationUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.junit4.SpringRunner; import java.util.Arrays; import java.util.Collections; @@ -42,31 +38,44 @@ import java.util.Properties; import java.util.concurrent.TimeUnit; -import static com.alibaba.nacos.test.naming.NamingBase.*; +import static com.alibaba.nacos.test.naming.NamingBase.TEST_GROUP; +import static com.alibaba.nacos.test.naming.NamingBase.TEST_GROUP_1; +import static com.alibaba.nacos.test.naming.NamingBase.TEST_GROUP_2; +import static com.alibaba.nacos.test.naming.NamingBase.TEST_IP_4_DOM_1; +import static com.alibaba.nacos.test.naming.NamingBase.TEST_PORT; +import static com.alibaba.nacos.test.naming.NamingBase.TEST_SERVER_STATUS; +import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName; +import static com.alibaba.nacos.test.naming.NamingBase.verifyInstanceList; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author nkorange */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"}, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class MultiTenant_ITCase { - +@SpringBootTest(classes = Nacos.class, properties = { + "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +class MultiTenant_ITCase { + private NamingService naming; + private NamingService naming1; + private NamingService naming2; + @LocalServerPort private int port; - + private volatile List instances = Collections.emptyList(); - - @Before - public void init() throws Exception { + + @BeforeEach + void init() throws Exception { Thread.sleep(6000L); NamingBase.prepareServer(port); - + naming = NamingFactory.createNamingService("127.0.0.1" + ":" + port); - + while (true) { if (!"UP".equals(naming.getServerStatus())) { Thread.sleep(1000L); @@ -74,587 +83,588 @@ public void init() throws Exception { } break; } - + Properties properties = new Properties(); properties.put(PropertyKeyConst.NAMESPACE, "namespace-1"); properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1" + ":" + port); naming1 = NamingFactory.createNamingService(properties); - - + properties = new Properties(); properties.put(PropertyKeyConst.NAMESPACE, "namespace-2"); properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1" + ":" + port); naming2 = NamingFactory.createNamingService(properties); } - + /** * @TCDescription : 多租户注册IP,port不相同实例 * @TestStep : * @ExpectResult : */ @Test - public void multipleTenant_registerInstance() throws Exception { + void multipleTenant_registerInstance() throws Exception { String serviceName = randomDomainName(); - + naming1.registerInstance(serviceName, "11.11.11.11", 80); - + naming2.registerInstance(serviceName, "22.22.22.22", 80); - + naming.registerInstance(serviceName, "33.33.33.33", 8888); - + TimeUnit.SECONDS.sleep(5L); - + List instances = naming1.getAllInstances(serviceName); - Assert.assertEquals(1, instances.size()); - Assert.assertEquals("11.11.11.11", instances.get(0).getIp()); - Assert.assertEquals(80, instances.get(0).getPort()); - + assertEquals(1, instances.size()); + assertEquals("11.11.11.11", instances.get(0).getIp()); + assertEquals(80, instances.get(0).getPort()); + instances = naming2.getAllInstances(serviceName); - Assert.assertEquals(1, instances.size()); - Assert.assertEquals("22.22.22.22", instances.get(0).getIp()); - Assert.assertEquals(80, instances.get(0).getPort()); - + assertEquals(1, instances.size()); + assertEquals("22.22.22.22", instances.get(0).getIp()); + assertEquals(80, instances.get(0).getPort()); + instances = naming.getAllInstances(serviceName); - Assert.assertEquals(1, instances.size()); + assertEquals(1, instances.size()); } - + /** * @TCDescription : 多Group注册实例 * @TestStep : * @ExpectResult : */ @Test - public void multipleTenant_multiGroup_registerInstance() throws Exception { + void multipleTenant_multiGroup_registerInstance() throws Exception { String serviceName = randomDomainName(); - - naming1.registerInstance(serviceName, TEST_GROUP_1,"11.11.11.11", 80); - - naming2.registerInstance(serviceName, TEST_GROUP_2,"22.22.22.22", 80); - + + naming1.registerInstance(serviceName, TEST_GROUP_1, "11.11.11.11", 80); + + naming2.registerInstance(serviceName, TEST_GROUP_2, "22.22.22.22", 80); + naming.registerInstance(serviceName, "33.33.33.33", 8888); - + TimeUnit.SECONDS.sleep(5L); - + List instances = naming1.getAllInstances(serviceName); - Assert.assertEquals(0, instances.size()); - + assertEquals(0, instances.size()); + instances = naming2.getAllInstances(serviceName, TEST_GROUP_2); - Assert.assertEquals(1, instances.size()); - Assert.assertEquals("22.22.22.22", instances.get(0).getIp()); - Assert.assertEquals(80, instances.get(0).getPort()); - + assertEquals(1, instances.size()); + assertEquals("22.22.22.22", instances.get(0).getIp()); + assertEquals(80, instances.get(0).getPort()); + instances = naming.getAllInstances(serviceName); - Assert.assertEquals(1, instances.size()); - - naming1.deregisterInstance(serviceName, TEST_GROUP_1,"11.11.11.11", 80); - naming1.deregisterInstance(serviceName, TEST_GROUP_2,"22.22.22.22", 80); + assertEquals(1, instances.size()); + + naming1.deregisterInstance(serviceName, TEST_GROUP_1, "11.11.11.11", 80); + naming1.deregisterInstance(serviceName, TEST_GROUP_2, "22.22.22.22", 80); } - + /** * @TCDescription : 多租户注册IP,port相同的实例 * @TestStep : * @ExpectResult : */ @Test - public void multipleTenant_equalIP() throws Exception { + void multipleTenant_equalIP() throws Exception { String serviceName = randomDomainName(); naming1.registerInstance(serviceName, "11.11.11.11", 80); - + naming2.registerInstance(serviceName, "11.11.11.11", 80); - + naming.registerInstance(serviceName, "11.11.11.11", 80); - + TimeUnit.SECONDS.sleep(5L); - + List instances = naming1.getAllInstances(serviceName); - - Assert.assertEquals(1, instances.size()); - Assert.assertEquals("11.11.11.11", instances.get(0).getIp()); - Assert.assertEquals(80, instances.get(0).getPort()); - + + assertEquals(1, instances.size()); + assertEquals("11.11.11.11", instances.get(0).getIp()); + assertEquals(80, instances.get(0).getPort()); + instances = naming2.getAllInstances(serviceName); - - Assert.assertEquals(1, instances.size()); - Assert.assertEquals("11.11.11.11", instances.get(0).getIp()); - Assert.assertEquals(80, instances.get(0).getPort()); - + + assertEquals(1, instances.size()); + assertEquals("11.11.11.11", instances.get(0).getIp()); + assertEquals(80, instances.get(0).getPort()); + instances = naming.getAllInstances(serviceName); - Assert.assertEquals(1, instances.size()); + assertEquals(1, instances.size()); } - + /** * @TCDescription : 多租户注册IP,port相同的实例 * @TestStep : * @ExpectResult : */ @Test - public void multipleTenant_selectInstances() throws Exception { + void multipleTenant_selectInstances() throws Exception { String serviceName = randomDomainName(); naming1.registerInstance(serviceName, TEST_IP_4_DOM_1, TEST_PORT); - + naming2.registerInstance(serviceName, "22.22.22.22", 80); - + naming.registerInstance(serviceName, TEST_IP_4_DOM_1, TEST_PORT); - + TimeUnit.SECONDS.sleep(5L); - + List instances = naming1.selectInstances(serviceName, true); - - Assert.assertEquals(1, instances.size()); - Assert.assertEquals(TEST_IP_4_DOM_1, instances.get(0).getIp()); - Assert.assertEquals(TEST_PORT, instances.get(0).getPort()); - + + assertEquals(1, instances.size()); + assertEquals(TEST_IP_4_DOM_1, instances.get(0).getIp()); + assertEquals(TEST_PORT, instances.get(0).getPort()); + instances = naming2.selectInstances(serviceName, false); - Assert.assertEquals(0, instances.size()); - - + assertEquals(0, instances.size()); + instances = naming.selectInstances(serviceName, true); - Assert.assertEquals(1, instances.size()); + assertEquals(1, instances.size()); } - + /** * @TCDescription : 多租户,多Group注册IP,port相同的实例 * @TestStep : * @ExpectResult : */ @Test - public void multipleTenant_group_equalIP() throws Exception { + void multipleTenant_group_equalIP() throws Exception { String serviceName = randomDomainName(); - naming1.registerInstance(serviceName, TEST_GROUP_1,"11.11.11.11", 80); - - naming2.registerInstance(serviceName, TEST_GROUP_2,"11.11.11.11", 80); - - naming.registerInstance(serviceName, Constants.DEFAULT_GROUP,"11.11.11.11", 80); - + naming1.registerInstance(serviceName, TEST_GROUP_1, "11.11.11.11", 80); + + naming2.registerInstance(serviceName, TEST_GROUP_2, "11.11.11.11", 80); + + naming.registerInstance(serviceName, Constants.DEFAULT_GROUP, "11.11.11.11", 80); + TimeUnit.SECONDS.sleep(5L); - + List instances = naming1.getAllInstances(serviceName); - - Assert.assertEquals(0, instances.size()); - + + assertEquals(0, instances.size()); + instances = naming2.getAllInstances(serviceName, TEST_GROUP_2); - - Assert.assertEquals(1, instances.size()); - Assert.assertEquals("11.11.11.11", instances.get(0).getIp()); - Assert.assertEquals(80, instances.get(0).getPort()); - + + assertEquals(1, instances.size()); + assertEquals("11.11.11.11", instances.get(0).getIp()); + assertEquals(80, instances.get(0).getPort()); + instances = naming.getAllInstances(serviceName); - Assert.assertEquals(1, instances.size()); + assertEquals(1, instances.size()); } - + /** * @TCDescription : 多租户,多Group注册IP,port相同的实例, 通过group获取实例 * @TestStep : * @ExpectResult : */ @Test - public void multipleTenant_group_getInstances() throws Exception { + void multipleTenant_group_getInstances() throws Exception { String serviceName = randomDomainName(); System.out.println(serviceName); - naming1.registerInstance(serviceName, TEST_GROUP_1,"11.11.11.11", 80); + naming1.registerInstance(serviceName, TEST_GROUP_1, "11.11.11.11", 80); // will cover the instance before - naming1.registerInstance(serviceName, TEST_GROUP_2,"11.11.11.11", 80); - - naming.registerInstance(serviceName, Constants.DEFAULT_GROUP,"11.11.11.11", 80); - + naming1.registerInstance(serviceName, TEST_GROUP_2, "11.11.11.11", 80); + + naming.registerInstance(serviceName, Constants.DEFAULT_GROUP, "11.11.11.11", 80); + TimeUnit.SECONDS.sleep(5L); List instances = naming1.getAllInstances(serviceName, TEST_GROUP); - - Assert.assertEquals(0, instances.size()); - + + assertEquals(0, instances.size()); + instances = naming.getAllInstances(serviceName); - Assert.assertEquals(1, instances.size()); - naming1.deregisterInstance(serviceName, TEST_GROUP_1,"11.11.11.11", 80); - naming1.deregisterInstance(serviceName, TEST_GROUP_2,"11.11.11.11", 80); + assertEquals(1, instances.size()); + naming1.deregisterInstance(serviceName, TEST_GROUP_1, "11.11.11.11", 80); + naming1.deregisterInstance(serviceName, TEST_GROUP_2, "11.11.11.11", 80); } - + /** * @TCDescription : 多租户同服务获取实例 * @TestStep : * @ExpectResult : */ @Test - public void multipleTenant_getServicesOfServer() throws Exception { - + void multipleTenant_getServicesOfServer() throws Exception { + String serviceName = randomDomainName(); naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1"); TimeUnit.SECONDS.sleep(5L); - + ListView listView = naming1.getServicesOfServer(1, 200); - + naming2.registerInstance(serviceName, "33.33.33.33", TEST_PORT, "c1"); TimeUnit.SECONDS.sleep(5L); ListView listView1 = naming1.getServicesOfServer(1, 200); - Assert.assertEquals(listView.getCount(), listView1.getCount()); + assertEquals(listView.getCount(), listView1.getCount()); } - + /** * @TCDescription : 多租户, 多group,同服务获取实例 * @TestStep : * @ExpectResult : */ @Test - public void multipleTenant_group_getServicesOfServer() throws Exception { - + void multipleTenant_group_getServicesOfServer() throws Exception { + String serviceName = randomDomainName(); - naming1.registerInstance(serviceName, TEST_GROUP_1, "11.11.11.11", TEST_PORT, "c1"); + naming1.registerInstance(serviceName, TEST_GROUP_1, "11.11.11.11", TEST_PORT, "c1"); // will cover the instance before - naming1.registerInstance(serviceName, TEST_GROUP_2, "22.22.22.22", TEST_PORT, "c1"); + naming1.registerInstance(serviceName, TEST_GROUP_2, "22.22.22.22", TEST_PORT, "c1"); TimeUnit.SECONDS.sleep(5L); - + //服务不会删除,实例会注销 ListView listView = naming1.getServicesOfServer(1, 20, TEST_GROUP_1); - + naming2.registerInstance(serviceName, "33.33.33.33", TEST_PORT, "c1"); TimeUnit.SECONDS.sleep(5L); ListView listView1 = naming1.getServicesOfServer(1, 20, TEST_GROUP_1); - Assert.assertEquals(listView.getCount(), listView1.getCount()); - Assert.assertNotEquals(0, listView1.getCount()); + assertEquals(listView.getCount(), listView1.getCount()); + assertNotEquals(0, listView1.getCount()); } - + /** * @TCDescription : 多租户订阅服务 * @TestStep : * @ExpectResult : */ @Test - public void multipleTenant_subscribe() throws Exception { - + void multipleTenant_subscribe() throws Exception { + String serviceName = randomDomainName(); - + naming1.subscribe(serviceName, new EventListener() { @Override public void onEvent(Event event) { instances = ((NamingEvent) event).getInstances(); } }); - + naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1"); naming2.registerInstance(serviceName, "33.33.33.33", TEST_PORT, "c1"); - + while (instances.size() == 0) { TimeUnit.SECONDS.sleep(1L); } - Assert.assertEquals(1, instances.size()); - + assertEquals(1, instances.size()); + TimeUnit.SECONDS.sleep(2L); - Assert.assertTrue(verifyInstanceList(instances, naming1.getAllInstances(serviceName))); + assertTrue(verifyInstanceList(instances, naming1.getAllInstances(serviceName))); } - + /** * @TCDescription : 多租户多group订阅服务 * @TestStep : * @ExpectResult : */ @Test - public void multipleTenant_group_subscribe() throws Exception { - + void multipleTenant_group_subscribe() throws Exception { + String serviceName = randomDomainName(); - + naming1.subscribe(serviceName, TEST_GROUP_1, new EventListener() { @Override public void onEvent(Event event) { instances = ((NamingEvent) event).getInstances(); } }); - + naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1"); - naming1.registerInstance(serviceName, TEST_GROUP_1,"33.33.33.33", TEST_PORT, "c1"); - + naming1.registerInstance(serviceName, TEST_GROUP_1, "33.33.33.33", TEST_PORT, "c1"); + while (instances.size() == 0) { TimeUnit.SECONDS.sleep(1L); } TimeUnit.SECONDS.sleep(2L); - Assert.assertEquals(1, instances.size()); - + assertEquals(1, instances.size()); + TimeUnit.SECONDS.sleep(2L); - Assert.assertTrue(verifyInstanceList(instances, naming1.getAllInstances(serviceName, TEST_GROUP_1))); - + assertTrue(verifyInstanceList(instances, naming1.getAllInstances(serviceName, TEST_GROUP_1))); + naming1.deregisterInstance(serviceName, "11.11.11.11", TEST_PORT, "c1"); - naming1.deregisterInstance(serviceName, TEST_GROUP_1,"33.33.33.33", TEST_PORT, "c1"); + naming1.deregisterInstance(serviceName, TEST_GROUP_1, "33.33.33.33", TEST_PORT, "c1"); } - + /** * @TCDescription : 多租户取消订阅服务 * @TestStep : * @ExpectResult : */ @Test - public void multipleTenant_unSubscribe() throws Exception { - + void multipleTenant_unSubscribe() throws Exception { + String serviceName = randomDomainName(); EventListener listener = new EventListener() { @Override public void onEvent(Event event) { - System.out.println(((NamingEvent)event).getServiceName()); - instances = ((NamingEvent)event).getInstances(); + System.out.println(((NamingEvent) event).getServiceName()); + instances = ((NamingEvent) event).getInstances(); } }; - + naming1.subscribe(serviceName, listener); naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1"); naming2.registerInstance(serviceName, "33.33.33.33", TEST_PORT, "c1"); - + while (instances.size() == 0) { TimeUnit.SECONDS.sleep(1L); } - Assert.assertEquals(serviceName, naming1.getSubscribeServices().get(0).getName()); - Assert.assertEquals(0, naming2.getSubscribeServices().size()); - + assertEquals(serviceName, naming1.getSubscribeServices().get(0).getName()); + assertEquals(0, naming2.getSubscribeServices().size()); + naming1.unsubscribe(serviceName, listener); - + TimeUnit.SECONDS.sleep(5L); - Assert.assertEquals(0, naming1.getSubscribeServices().size()); - Assert.assertEquals(0, naming2.getSubscribeServices().size()); + assertEquals(0, naming1.getSubscribeServices().size()); + assertEquals(0, naming2.getSubscribeServices().size()); } - + /** * @TCDescription : 多租户,多group下, 没有对应的group订阅,取消订阅服务 * @TestStep : * @ExpectResult : */ @Test - public void multipleTenant_group_nosubscribe_unSubscribe() throws Exception { - + void multipleTenant_group_nosubscribe_unSubscribe() throws Exception { + String serviceName = randomDomainName(); EventListener listener = new EventListener() { @Override public void onEvent(Event event) { - System.out.println(((NamingEvent)event).getServiceName()); - instances = ((NamingEvent)event).getInstances(); + System.out.println(((NamingEvent) event).getServiceName()); + instances = ((NamingEvent) event).getInstances(); } }; - + naming1.subscribe(serviceName, TEST_GROUP_1, listener); naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1"); - naming1.registerInstance(serviceName, TEST_GROUP_2,"33.33.33.33", TEST_PORT, "c1"); - + naming1.registerInstance(serviceName, TEST_GROUP_2, "33.33.33.33", TEST_PORT, "c1"); + TimeUnit.SECONDS.sleep(3L); - Assert.assertEquals(serviceName, naming1.getSubscribeServices().get(0).getName()); - Assert.assertEquals(0, naming2.getSubscribeServices().size()); - + assertEquals(serviceName, naming1.getSubscribeServices().get(0).getName()); + assertEquals(0, naming2.getSubscribeServices().size()); + naming1.unsubscribe(serviceName, listener); //取消订阅服务,没有订阅group TimeUnit.SECONDS.sleep(3L); - Assert.assertEquals(1, naming1.getSubscribeServices().size()); - + assertEquals(1, naming1.getSubscribeServices().size()); + naming1.unsubscribe(serviceName, TEST_GROUP_1, listener); //取消订阅服务,有订阅group TimeUnit.SECONDS.sleep(3L); - Assert.assertEquals(0, naming1.getSubscribeServices().size()); - - Assert.assertEquals(0, naming2.getSubscribeServices().size()); + assertEquals(0, naming1.getSubscribeServices().size()); + + assertEquals(0, naming2.getSubscribeServices().size()); } - + /** * @TCDescription : 多租户,多group下, 多个group订阅,查看服务的个数 * @TestStep : * @ExpectResult : */ @Test - public void multipleTenant_group_unSubscribe() throws Exception { - + void multipleTenant_group_unSubscribe() throws Exception { + String serviceName = randomDomainName(); EventListener listener = new EventListener() { @Override public void onEvent(Event event) { - System.out.println(((NamingEvent)event).getServiceName()); - instances = ((NamingEvent)event).getInstances(); + System.out.println(((NamingEvent) event).getServiceName()); + instances = ((NamingEvent) event).getInstances(); } }; - + naming1.subscribe(serviceName, Constants.DEFAULT_GROUP, listener); naming1.subscribe(serviceName, TEST_GROUP_2, listener); naming1.subscribe(serviceName, TEST_GROUP_1, listener); - + naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1"); - naming1.registerInstance(serviceName, TEST_GROUP_2,"33.33.33.33", TEST_PORT, "c1"); - + naming1.registerInstance(serviceName, TEST_GROUP_2, "33.33.33.33", TEST_PORT, "c1"); + while (instances.size() == 0) { TimeUnit.SECONDS.sleep(1L); } TimeUnit.SECONDS.sleep(2L); - Assert.assertEquals(serviceName, naming1.getSubscribeServices().get(0).getName()); - Assert.assertEquals(3, naming1.getSubscribeServices().size()); - + assertEquals(serviceName, naming1.getSubscribeServices().get(0).getName()); + assertEquals(3, naming1.getSubscribeServices().size()); + naming1.unsubscribe(serviceName, listener); naming1.unsubscribe(serviceName, TEST_GROUP_2, listener); TimeUnit.SECONDS.sleep(3L); - Assert.assertEquals(1, naming1.getSubscribeServices().size()); - Assert.assertEquals(TEST_GROUP_1, naming1.getSubscribeServices().get(0).getGroupName()); - + assertEquals(1, naming1.getSubscribeServices().size()); + assertEquals(TEST_GROUP_1, naming1.getSubscribeServices().get(0).getGroupName()); + naming1.unsubscribe(serviceName, TEST_GROUP_1, listener); } - + /** * @TCDescription : 多租户获取server状态 * @TestStep : * @ExpectResult : */ @Test - public void multipleTenant_serverStatus() throws Exception { - Assert.assertEquals(TEST_SERVER_STATUS, naming1.getServerStatus()); - Assert.assertEquals(TEST_SERVER_STATUS, naming2.getServerStatus()); + void multipleTenant_serverStatus() throws Exception { + assertEquals(TEST_SERVER_STATUS, naming1.getServerStatus()); + assertEquals(TEST_SERVER_STATUS, naming2.getServerStatus()); } - + /** * @TCDescription : 多租户删除实例 * @TestStep : * @ExpectResult : */ @Test - public void multipleTenant_deregisterInstance() throws Exception { - + void multipleTenant_deregisterInstance() throws Exception { + String serviceName = randomDomainName(); - + naming1.registerInstance(serviceName, "22.22.22.22", TEST_PORT, "c1"); naming2.registerInstance(serviceName, "22.22.22.22", TEST_PORT, "c1"); - + List instances = naming1.getAllInstances(serviceName); verifyInstanceListForNaming(naming1, 1, serviceName); - - Assert.assertEquals(1, naming1.getAllInstances(serviceName).size()); - + + assertEquals(1, naming1.getAllInstances(serviceName).size()); + naming1.deregisterInstance(serviceName, "22.22.22.22", TEST_PORT, "c1"); TimeUnit.SECONDS.sleep(12); - - Assert.assertEquals(0, naming1.getAllInstances(serviceName).size()); - Assert.assertEquals(1, naming2.getAllInstances(serviceName).size()); + + assertEquals(0, naming1.getAllInstances(serviceName).size()); + assertEquals(1, naming2.getAllInstances(serviceName).size()); } - - + + /** * @TCDescription : 多租户, 多group,删除group不存在的实例 * @TestStep : * @ExpectResult : */ @Test - @Ignore("nacos 2.0 deregister only judged by client and service") - public void multipleTenant_group_deregisterInstance() throws Exception { - + @Disabled("nacos 2.0 deregister only judged by client and service") + void multipleTenant_group_deregisterInstance() throws Exception { + String serviceName = randomDomainName(); - + naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1"); naming1.registerInstance(serviceName, "22.22.22.22", TEST_PORT, "c2"); - + List instances = naming1.getAllInstances(serviceName); verifyInstanceListForNaming(naming1, 2, serviceName); - - Assert.assertEquals(2, naming1.getAllInstances(serviceName).size()); - - naming1.deregisterInstance(serviceName, TEST_GROUP_2,"22.22.22.22", TEST_PORT, "c1"); + + assertEquals(2, naming1.getAllInstances(serviceName).size()); + + naming1.deregisterInstance(serviceName, TEST_GROUP_2, "22.22.22.22", TEST_PORT, "c1"); TimeUnit.SECONDS.sleep(12); - - Assert.assertEquals(2, naming1.getAllInstances(serviceName).size()); + + assertEquals(2, naming1.getAllInstances(serviceName).size()); } - + /** * @TCDescription : 多租户, 多group,删除clusterName不存在的实例 * @TestStep : * @ExpectResult : */ @Test - @Ignore("nacos 2.0 deregister only judged by client and service") - public void multipleTenant_group_cluster_deregisterInstance() throws Exception { - + @Disabled("nacos 2.0 deregister only judged by client and service") + void multipleTenant_group_cluster_deregisterInstance() throws Exception { + String serviceName = randomDomainName(); - + naming1.registerInstance(serviceName, "11.11.11.11", TEST_PORT, "c1"); naming1.registerInstance(serviceName, "22.22.22.22", TEST_PORT, "c2"); - + List instances = naming1.getAllInstances(serviceName); verifyInstanceListForNaming(naming1, 2, serviceName); - - Assert.assertEquals(2, naming1.getAllInstances(serviceName).size()); - + + assertEquals(2, naming1.getAllInstances(serviceName).size()); + naming1.deregisterInstance(serviceName, "22.22.22.22", TEST_PORT); TimeUnit.SECONDS.sleep(3L); - Assert.assertEquals(2, naming1.getAllInstances(serviceName).size()); - + assertEquals(2, naming1.getAllInstances(serviceName).size()); + naming1.deregisterInstance(serviceName, "11.11.11.11", TEST_PORT, "c1"); naming1.deregisterInstance(serviceName, "22.22.22.22", TEST_PORT, "c2"); } - + /** * @TCDescription : 多租户下,选择一个健康的实例 * @TestStep : * @ExpectResult : */ @Test - public void multipleTenant_selectOneHealthyInstance() throws Exception { - + void multipleTenant_selectOneHealthyInstance() throws Exception { + String serviceName = randomDomainName(); naming1.registerInstance(serviceName, "22.22.22.22", TEST_PORT, "c2"); naming2.registerInstance(serviceName, "22.22.22.22", TEST_PORT, "c3"); - + List instances = naming1.getAllInstances(serviceName); verifyInstanceListForNaming(naming1, 1, serviceName); - - Assert.assertEquals(1, naming1.getAllInstances(serviceName).size()); - + + assertEquals(1, naming1.getAllInstances(serviceName).size()); + Instance instance = naming1.selectOneHealthyInstance(serviceName, Arrays.asList("c2")); - Assert.assertEquals("22.22.22.22", instance.getIp()); - + assertEquals("22.22.22.22", instance.getIp()); + naming2.deregisterInstance(serviceName, "22.22.22.22", TEST_PORT, "c3"); TimeUnit.SECONDS.sleep(5); instance = naming1.selectOneHealthyInstance(serviceName); - Assert.assertEquals("22.22.22.22", instance.getIp()); + assertEquals("22.22.22.22", instance.getIp()); } - + /** * @TCDescription : 多租户下,多group下,选择一个健康的实例 * @TestStep : * @ExpectResult : */ @Test - public void multipleTenant_group_selectOneHealthyInstance() throws Exception { - + void multipleTenant_group_selectOneHealthyInstance() throws Exception { + String serviceName = randomDomainName(); naming1.registerInstance(serviceName, TEST_GROUP, "11.11.11.11", TEST_PORT, "c1"); - naming1.registerInstance(serviceName, TEST_GROUP_1,"22.22.22.22", TEST_PORT, "c2"); - naming1.registerInstance(serviceName, TEST_GROUP_2,"33.33.33.33", TEST_PORT, "c3"); - + naming1.registerInstance(serviceName, TEST_GROUP_1, "22.22.22.22", TEST_PORT, "c2"); + naming1.registerInstance(serviceName, TEST_GROUP_2, "33.33.33.33", TEST_PORT, "c3"); + List instances = naming1.getAllInstances(serviceName, TEST_GROUP); verifyInstanceListForNaming(naming1, 0, serviceName); - - Assert.assertEquals(0, naming1.getAllInstances(serviceName).size()); //defalut group - + + assertEquals(0, naming1.getAllInstances(serviceName).size()); //defalut group + Instance instance = naming1.selectOneHealthyInstance(serviceName, TEST_GROUP, Arrays.asList("c1")); - Assert.assertEquals("11.11.11.11", instance.getIp()); - + assertEquals("11.11.11.11", instance.getIp()); + instance = naming1.selectOneHealthyInstance(serviceName, TEST_GROUP_1); - Assert.assertEquals("22.22.22.22", instance.getIp()); - + assertEquals("22.22.22.22", instance.getIp()); + naming1.deregisterInstance(serviceName, TEST_GROUP, "11.11.11.11", TEST_PORT, "c1"); - naming1.deregisterInstance(serviceName, TEST_GROUP_1,"22.22.22.22", TEST_PORT, "c2"); - naming1.deregisterInstance(serviceName, TEST_GROUP_2,"33.33.33.33", TEST_PORT, "c3"); - + naming1.deregisterInstance(serviceName, TEST_GROUP_1, "22.22.22.22", TEST_PORT, "c2"); + naming1.deregisterInstance(serviceName, TEST_GROUP_2, "33.33.33.33", TEST_PORT, "c3"); + } - + /** * @TCDescription : 多租户下,多group下,选择group不存在,一个健康的实例 * @TestStep : * @ExpectResult : */ - @Test(expected = IllegalStateException.class) - public void multipleTenant_noGroup_selectOneHealthyInstance() throws Exception { - - String serviceName = randomDomainName(); - naming1.registerInstance(serviceName, TEST_GROUP, "11.11.11.11", TEST_PORT, "c1"); - naming1.registerInstance(serviceName, TEST_GROUP_1,"22.22.22.22", TEST_PORT, "c2"); - - List instances = naming1.getAllInstances(serviceName, TEST_GROUP); - verifyInstanceListForNaming(naming1, 0, serviceName); - - Instance instance = naming1.selectOneHealthyInstance(serviceName, Arrays.asList("c1")); - - naming1.deregisterInstance(serviceName, TEST_GROUP, "11.11.11.11", TEST_PORT, "c1"); - naming1.deregisterInstance(serviceName, TEST_GROUP_1,"22.22.22.22", TEST_PORT, "c2"); - + @Test + void multipleTenant_noGroup_selectOneHealthyInstance() throws Exception { + assertThrows(IllegalStateException.class, () -> { + + String serviceName = randomDomainName(); + naming1.registerInstance(serviceName, TEST_GROUP, "11.11.11.11", TEST_PORT, "c1"); + naming1.registerInstance(serviceName, TEST_GROUP_1, "22.22.22.22", TEST_PORT, "c2"); + + List instances = naming1.getAllInstances(serviceName, TEST_GROUP); + verifyInstanceListForNaming(naming1, 0, serviceName); + + Instance instance = naming1.selectOneHealthyInstance(serviceName, Arrays.asList("c1")); + + naming1.deregisterInstance(serviceName, TEST_GROUP, "11.11.11.11", TEST_PORT, "c1"); + naming1.deregisterInstance(serviceName, TEST_GROUP_1, "22.22.22.22", TEST_PORT, "c2"); + + }); + } - + private void verifyInstanceListForNaming(NamingService naming, int size, String serviceName) throws Exception { int i = 0; - while ( i < 20 ) { + while (i < 20) { List instances = naming.getAllInstances(serviceName); if (instances.size() == size) { break; diff --git a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/MultiTenant_InstanceAPI_ITCase.java b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/MultiTenant_InstanceAPI_ITCase.java index 5012c37ea6c..7336f0f5b48 100644 --- a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/MultiTenant_InstanceAPI_ITCase.java +++ b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/MultiTenant_InstanceAPI_ITCase.java @@ -24,10 +24,8 @@ import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.test.base.Params; import com.fasterxml.jackson.databind.JsonNode; -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.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; @@ -37,7 +35,6 @@ import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.MultiValueMap; import org.springframework.web.util.UriComponentsBuilder; @@ -50,14 +47,17 @@ import static com.alibaba.nacos.test.naming.NamingBase.TEST_GROUP_1; import static com.alibaba.nacos.test.naming.NamingBase.TEST_GROUP_2; import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author nkorange */ -@RunWith(SpringRunner.class) @SpringBootTest(classes = Nacos.class, properties = { "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class MultiTenant_InstanceAPI_ITCase { +class MultiTenant_InstanceAPI_ITCase { + + private final List instances = Collections.emptyList(); private NamingService naming; @@ -73,10 +73,8 @@ public class MultiTenant_InstanceAPI_ITCase { private URL base; - private final List instances = Collections.emptyList(); - - @Before - public void init() throws Exception { + @BeforeEach + void init() throws Exception { NamingBase.prepareServer(port); @@ -110,7 +108,7 @@ public void init() throws Exception { * @ExpectResult : */ @Test - public void multipleTenant_listInstance() throws Exception { + void multipleTenant_listInstance() throws Exception { String serviceName = randomDomainName(); naming1.registerInstance(serviceName, "11.11.11.11", 80); @@ -123,18 +121,17 @@ public void multipleTenant_listInstance() throws Exception { String url = "/nacos/v1/ns/instance/list"; ResponseEntity response = request(url, - Params.newParams().appendParam("serviceName", serviceName).appendParam("namespaceId", "namespace-1") - .done(), String.class); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + Params.newParams().appendParam("serviceName", serviceName).appendParam("namespaceId", "namespace-1").done(), String.class); + assertTrue(response.getStatusCode().is2xxSuccessful()); JsonNode json = JacksonUtils.toObj(response.getBody()); - Assert.assertEquals("11.11.11.11", json.get("hosts").get(0).get("ip").asText()); + assertEquals("11.11.11.11", json.get("hosts").get(0).get("ip").asText()); response = request(url, Params.newParams().appendParam("serviceName", serviceName).done(), String.class); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); json = JacksonUtils.toObj(response.getBody()); - Assert.assertEquals(1, json.get("hosts").size()); + assertEquals(1, json.get("hosts").size()); } /** @@ -143,7 +140,7 @@ public void multipleTenant_listInstance() throws Exception { * @ExpectResult : */ @Test - public void multipleTenant_group_listInstance() throws Exception { + void multipleTenant_group_listInstance() throws Exception { String serviceName = randomDomainName(); naming1.registerInstance(serviceName, TEST_GROUP_1, "11.11.11.11", 80); @@ -159,19 +156,18 @@ public void multipleTenant_group_listInstance() throws Exception { ResponseEntity response = request(url, Params.newParams().appendParam("serviceName", serviceName).appendParam("namespaceId", "namespace-1") .appendParam("groupName", TEST_GROUP_1).done(), String.class); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); JsonNode json = JacksonUtils.toObj(response.getBody()); - Assert.assertEquals("11.11.11.11", json.get("hosts").get(0).get("ip").asText()); + assertEquals("11.11.11.11", json.get("hosts").get(0).get("ip").asText()); - response = request(url, - Params.newParams().appendParam("serviceName", serviceName).appendParam("groupName", TEST_GROUP_1) - .done(), String.class); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + response = request(url, Params.newParams().appendParam("serviceName", serviceName).appendParam("groupName", TEST_GROUP_1).done(), + String.class); + assertTrue(response.getStatusCode().is2xxSuccessful()); json = JacksonUtils.toObj(response.getBody()); - Assert.assertEquals(1, json.get("hosts").size()); - Assert.assertEquals("33.33.33.33", json.get("hosts").get(0).get("ip").asText()); + assertEquals(1, json.get("hosts").size()); + assertEquals("33.33.33.33", json.get("hosts").get(0).get("ip").asText()); } /** @@ -180,7 +176,7 @@ public void multipleTenant_group_listInstance() throws Exception { * @ExpectResult : */ @Test - public void multipleTenant_getInstance() throws Exception { + void multipleTenant_getInstance() throws Exception { String serviceName = randomDomainName(); naming1.registerInstance(serviceName, "11.11.11.11", 80); @@ -192,18 +188,17 @@ public void multipleTenant_getInstance() throws Exception { TimeUnit.SECONDS.sleep(5L); ResponseEntity response = request("/nacos/v1/ns/instance", - Params.newParams().appendParam("serviceName", serviceName) - .appendParam("ip", "33.33.33.33") //错误的IP,隔离验证 + Params.newParams().appendParam("serviceName", serviceName).appendParam("ip", "33.33.33.33") //错误的IP,隔离验证 .appendParam("port", "8888").appendParam("namespaceId", "namespace-2").done(), String.class); - Assert.assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); + assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); response = request("/nacos/v1/ns/instance/list", - Params.newParams().appendParam("serviceName", serviceName).appendParam("clusters", "c1") - .appendParam("healthyOnly", "true").done(), String.class); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + Params.newParams().appendParam("serviceName", serviceName).appendParam("clusters", "c1").appendParam("healthyOnly", "true") + .done(), String.class); + assertTrue(response.getStatusCode().is2xxSuccessful()); JsonNode json = JacksonUtils.toObj(response.getBody()); - Assert.assertEquals(1, json.get("hosts").size()); - Assert.assertEquals("33.33.33.33", json.get("hosts").get(0).get("ip").asText()); + assertEquals(1, json.get("hosts").size()); + assertEquals("33.33.33.33", json.get("hosts").get(0).get("ip").asText()); } /** @@ -212,7 +207,7 @@ public void multipleTenant_getInstance() throws Exception { * @ExpectResult : */ @Test - public void multipleTenant_group_getInstance() throws Exception { + void multipleTenant_group_getInstance() throws Exception { String serviceName = randomDomainName(); naming1.registerInstance(serviceName, "11.11.11.11", 80); @@ -228,15 +223,15 @@ public void multipleTenant_group_getInstance() throws Exception { Params.newParams().appendParam("serviceName", serviceName).appendParam("groupName", TEST_GROUP_1) .appendParam("ip", "33.33.33.33") //不存在的IP,隔离验证 .appendParam("port", "8888").appendParam("namespaceId", "namespace-2").done(), String.class); - Assert.assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); + assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); response = request("/nacos/v1/ns/instance/list", - Params.newParams().appendParam("serviceName", serviceName).appendParam("clusters", "c2") - .appendParam("healthyOnly", "true").done(), String.class); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + Params.newParams().appendParam("serviceName", serviceName).appendParam("clusters", "c2").appendParam("healthyOnly", "true") + .done(), String.class); + assertTrue(response.getStatusCode().is2xxSuccessful()); JsonNode json = JacksonUtils.toObj(response.getBody()); - Assert.assertEquals(1, json.get("hosts").size()); - Assert.assertEquals("44.44.44.44", json.get("hosts").get(0).get("ip").asText()); + assertEquals(1, json.get("hosts").size()); + assertEquals("44.44.44.44", json.get("hosts").get(0).get("ip").asText()); } /** @@ -245,7 +240,7 @@ public void multipleTenant_group_getInstance() throws Exception { * @ExpectResult : */ @Test - public void multipleTenant_putInstance() throws Exception { + void multipleTenant_putInstance() throws Exception { String serviceName = randomDomainName(); naming1.registerInstance(serviceName, "11.11.11.11", 80); @@ -258,25 +253,23 @@ public void multipleTenant_putInstance() throws Exception { TimeUnit.SECONDS.sleep(5L); ResponseEntity response = request("/nacos/v1/ns/instance", - Params.newParams().appendParam("serviceName", serviceName).appendParam("ip", "33.33.33.33") - .appendParam("port", "8888").done(), String.class, HttpMethod.PUT); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + Params.newParams().appendParam("serviceName", serviceName).appendParam("ip", "33.33.33.33").appendParam("port", "8888") + .done(), String.class, HttpMethod.PUT); + assertTrue(response.getStatusCode().is2xxSuccessful()); - response = request("/nacos/v1/ns/instance/list", - Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例 - .appendParam("namespaceId", "namespace-1").done(), String.class); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + response = request("/nacos/v1/ns/instance/list", Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例 + .appendParam("namespaceId", "namespace-1").done(), String.class); + assertTrue(response.getStatusCode().is2xxSuccessful()); JsonNode json = JacksonUtils.toObj(response.getBody()); - Assert.assertEquals(1, json.get("hosts").size()); + assertEquals(1, json.get("hosts").size()); //namespace-2个数 - response = request("/nacos/v1/ns/instance/list", - Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例 - .appendParam("namespaceId", "namespace-2").done(), String.class); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + response = request("/nacos/v1/ns/instance/list", Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例 + .appendParam("namespaceId", "namespace-2").done(), String.class); + assertTrue(response.getStatusCode().is2xxSuccessful()); json = JacksonUtils.toObj(response.getBody()); System.out.println(json); - Assert.assertEquals(1, json.get("hosts").size()); + assertEquals(1, json.get("hosts").size()); } /** @@ -285,7 +278,7 @@ public void multipleTenant_putInstance() throws Exception { * @ExpectResult : */ @Test - public void multipleTenant_group_putInstance() throws Exception { + void multipleTenant_group_putInstance() throws Exception { String serviceName = randomDomainName(); naming1.registerInstance(serviceName, "11.11.11.11", 80); @@ -293,20 +286,17 @@ public void multipleTenant_group_putInstance() throws Exception { ResponseEntity response = request("/nacos/v1/ns/instance", Params.newParams().appendParam("serviceName", serviceName).appendParam("groupName", TEST_GROUP_2) - .appendParam("ip", "22.22.22.22").appendParam("port", "80") - .appendParam("namespaceId", "namespace-2").appendParam("weight", "8.0").done(), String.class, - HttpMethod.PUT); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + .appendParam("ip", "22.22.22.22").appendParam("port", "80").appendParam("namespaceId", "namespace-2") + .appendParam("weight", "8.0").done(), String.class, HttpMethod.PUT); + assertTrue(response.getStatusCode().is2xxSuccessful()); TimeUnit.SECONDS.sleep(5L); - response = request("/nacos/v1/ns/instance/list", - Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例 - .appendParam("namespaceId", "namespace-2").appendParam("groupName", TEST_GROUP_2).done(), - String.class); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + response = request("/nacos/v1/ns/instance/list", Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例 + .appendParam("namespaceId", "namespace-2").appendParam("groupName", TEST_GROUP_2).done(), String.class); + assertTrue(response.getStatusCode().is2xxSuccessful()); JsonNode json = JacksonUtils.toObj(response.getBody()); - Assert.assertEquals(1, json.get("hosts").size()); - Assert.assertEquals("8.0", json.get("hosts").get(0).get("weight").asText()); + assertEquals(1, json.get("hosts").size()); + assertEquals("8.0", json.get("hosts").get(0).get("weight").asText()); } /** @@ -315,7 +305,7 @@ public void multipleTenant_group_putInstance() throws Exception { * @ExpectResult : */ @Test - public void multipleTenant_group_patchInstance() throws Exception { + void multipleTenant_group_patchInstance() throws Exception { String serviceName = randomDomainName(); naming1.registerInstance(serviceName, "11.11.11.11", 80); @@ -325,27 +315,24 @@ public void multipleTenant_group_patchInstance() throws Exception { ResponseEntity response = request("/nacos/v1/ns/instance", Params.newParams().appendParam("serviceName", serviceName).appendParam("groupName", TEST_GROUP_2) - .appendParam("ip", "22.22.22.22").appendParam("port", "80") - .appendParam("namespaceId", "namespace-2").appendParam("weight", "8.0").done(), String.class, - HttpMethod.PUT); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + .appendParam("ip", "22.22.22.22").appendParam("port", "80").appendParam("namespaceId", "namespace-2") + .appendParam("weight", "8.0").done(), String.class, HttpMethod.PUT); + assertTrue(response.getStatusCode().is2xxSuccessful()); response = request("/nacos/v1/ns/instance", Params.newParams().appendParam("serviceName", serviceName).appendParam("groupName", TEST_GROUP_2) - .appendParam("ip", "22.22.22.22").appendParam("port", "80") - .appendParam("namespaceId", "namespace-2").done(), String.class, HttpMethod.PATCH); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + .appendParam("ip", "22.22.22.22").appendParam("port", "80").appendParam("namespaceId", "namespace-2").done(), + String.class, HttpMethod.PATCH); + assertTrue(response.getStatusCode().is2xxSuccessful()); TimeUnit.SECONDS.sleep(3L); - response = request("/nacos/v1/ns/instance/list", - Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例 - .appendParam("namespaceId", "namespace-2").appendParam("groupName", TEST_GROUP_2).done(), - String.class); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + response = request("/nacos/v1/ns/instance/list", Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例 + .appendParam("namespaceId", "namespace-2").appendParam("groupName", TEST_GROUP_2).done(), String.class); + assertTrue(response.getStatusCode().is2xxSuccessful()); JsonNode json = JacksonUtils.toObj(response.getBody()); - Assert.assertEquals(1, json.get("hosts").size()); - Assert.assertEquals("8.0", json.get("hosts").get(0).get("weight").asText()); + assertEquals(1, json.get("hosts").size()); + assertEquals("8.0", json.get("hosts").get(0).get("weight").asText()); } /** @@ -354,7 +341,7 @@ public void multipleTenant_group_patchInstance() throws Exception { * @ExpectResult : */ @Test - public void multipleTenant_updateInstance_notExsitInstance() throws Exception { + void multipleTenant_updateInstance_notExsitInstance() throws Exception { String serviceName = randomDomainName(); naming1.registerInstance(serviceName, "11.11.11.11", 80); @@ -365,26 +352,24 @@ public void multipleTenant_updateInstance_notExsitInstance() throws Exception { naming.registerInstance(serviceName, "44.44.44.44", 8888); ResponseEntity response = request("/nacos/v1/ns/instance", - Params.newParams().appendParam("serviceName", serviceName).appendParam("ip", "33.33.33.33") - .appendParam("port", "8888").appendParam("namespaceId", "namespace-1") //新增 + Params.newParams().appendParam("serviceName", serviceName).appendParam("ip", "33.33.33.33").appendParam("port", "8888") + .appendParam("namespaceId", "namespace-1") //新增 .done(), String.class, HttpMethod.POST); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); TimeUnit.SECONDS.sleep(5L); - response = request("/nacos/v1/ns/instance/list", - Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例 - .appendParam("namespaceId", "namespace-1").done(), String.class); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + response = request("/nacos/v1/ns/instance/list", Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例 + .appendParam("namespaceId", "namespace-1").done(), String.class); + assertTrue(response.getStatusCode().is2xxSuccessful()); JsonNode json = JacksonUtils.toObj(response.getBody()); - Assert.assertEquals(2, json.get("hosts").size()); + assertEquals(2, json.get("hosts").size()); //namespace-2个数 - response = request("/nacos/v1/ns/instance/list", - Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例 - .appendParam("namespaceId", "namespace-2").done(), String.class); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + response = request("/nacos/v1/ns/instance/list", Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例 + .appendParam("namespaceId", "namespace-2").done(), String.class); + assertTrue(response.getStatusCode().is2xxSuccessful()); json = JacksonUtils.toObj(response.getBody()); - Assert.assertEquals(1, json.get("hosts").size()); + assertEquals(1, json.get("hosts").size()); } /** @@ -393,7 +378,7 @@ public void multipleTenant_updateInstance_notExsitInstance() throws Exception { * @ExpectResult : */ @Test - public void multipleTenant_group_updateInstance_notExsitInstance() throws Exception { + void multipleTenant_group_updateInstance_notExsitInstance() throws Exception { String serviceName = randomDomainName(); naming1.registerInstance(serviceName, "11.11.11.11", 80); @@ -401,20 +386,18 @@ public void multipleTenant_group_updateInstance_notExsitInstance() throws Except TimeUnit.SECONDS.sleep(5L); ResponseEntity response = request("/nacos/v1/ns/instance", - Params.newParams().appendParam("serviceName", serviceName).appendParam("ip", "33.33.33.33") - .appendParam("port", "8888").appendParam("namespaceId", "namespace-1") //新增 + Params.newParams().appendParam("serviceName", serviceName).appendParam("ip", "33.33.33.33").appendParam("port", "8888") + .appendParam("namespaceId", "namespace-1") //新增 .appendParam("groupName", TEST_GROUP_1).done(), String.class, HttpMethod.POST); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); - response = request("/nacos/v1/ns/instance/list", - Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例 - .appendParam("namespaceId", "namespace-1").appendParam("groupName", TEST_GROUP_1).done(), - String.class); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + response = request("/nacos/v1/ns/instance/list", Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例 + .appendParam("namespaceId", "namespace-1").appendParam("groupName", TEST_GROUP_1).done(), String.class); + assertTrue(response.getStatusCode().is2xxSuccessful()); String body = response.getBody(); System.out.println("multipleTenant_group_updateInstance_notExsitInstance received body: " + body); JsonNode json = JacksonUtils.toObj(body); - Assert.assertEquals("33.33.33.33", json.get("hosts").get(0).get("ip").asText()); + assertEquals("33.33.33.33", json.get("hosts").get(0).get("ip").asText()); } /** @@ -423,7 +406,7 @@ public void multipleTenant_group_updateInstance_notExsitInstance() throws Except * @ExpectResult : */ @Test - public void multipleTenant_updateInstance() throws Exception { + void multipleTenant_updateInstance() throws Exception { String serviceName = randomDomainName(); naming2.registerInstance(serviceName, "22.22.22.22", 80); @@ -434,25 +417,23 @@ public void multipleTenant_updateInstance() throws Exception { TimeUnit.SECONDS.sleep(5L); ResponseEntity response = request("/nacos/v1/ns/instance", - Params.newParams().appendParam("serviceName", serviceName).appendParam("ip", "11.11.11.11") - .appendParam("port", "80").appendParam("namespaceId", "namespace-1") //新增 + Params.newParams().appendParam("serviceName", serviceName).appendParam("ip", "11.11.11.11").appendParam("port", "80") + .appendParam("namespaceId", "namespace-1") //新增 .done(), String.class, HttpMethod.POST); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + assertTrue(response.getStatusCode().is2xxSuccessful()); - response = request("/nacos/v1/ns/instance/list", - Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例 - .appendParam("namespaceId", "namespace-1").done(), String.class); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + response = request("/nacos/v1/ns/instance/list", Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例 + .appendParam("namespaceId", "namespace-1").done(), String.class); + assertTrue(response.getStatusCode().is2xxSuccessful()); JsonNode json = JacksonUtils.toObj(response.getBody()); - Assert.assertEquals(1, json.get("hosts").size()); + assertEquals(1, json.get("hosts").size()); //namespace-2个数 - response = request("/nacos/v1/ns/instance/list", - Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例 - .appendParam("namespaceId", "namespace-2").done(), String.class); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + response = request("/nacos/v1/ns/instance/list", Params.newParams().appendParam("serviceName", serviceName) //获取naming中的实例 + .appendParam("namespaceId", "namespace-2").done(), String.class); + assertTrue(response.getStatusCode().is2xxSuccessful()); json = JacksonUtils.toObj(response.getBody()); - Assert.assertEquals(1, json.get("hosts").size()); + assertEquals(1, json.get("hosts").size()); } private void verifyInstanceListForNaming(NamingService naming, int size, String serviceName) throws Exception { @@ -472,15 +453,13 @@ private ResponseEntity request(String path, MultiValueMap return request(path, params, clazz, HttpMethod.GET); } - private ResponseEntity request(String path, MultiValueMap params, Class clazz, - HttpMethod httpMethod) { + private ResponseEntity request(String path, MultiValueMap params, Class clazz, HttpMethod httpMethod) { HttpHeaders headers = new HttpHeaders(); HttpEntity entity = new HttpEntity(headers); - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.base.toString() + path) - .queryParams(params); + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.base.toString() + path).queryParams(params); return this.restTemplate.exchange(builder.toUriString(), httpMethod, entity, clazz); } diff --git a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/NamingBase.java b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/NamingBase.java index 8ee8edf894d..d9d8592c4b9 100644 --- a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/NamingBase.java +++ b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/NamingBase.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.test.naming; import com.alibaba.nacos.api.naming.pojo.Instance; @@ -23,47 +24,64 @@ import com.alibaba.nacos.common.http.param.Header; import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.test.base.HttpClient4Test; +import com.alibaba.nacos.test.base.Params; import org.apache.http.HttpStatus; -import org.junit.Assert; +import org.springframework.http.ResponseEntity; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author nkorange */ public class NamingBase extends HttpClient4Test { - - private static final NacosRestTemplate nacosRestTemplate = NamingHttpClientManager.getInstance().getNacosRestTemplate(); - + public static final String TEST_DOM_1 = "nacos.test.1"; + public static final String TEST_IP_4_DOM_1 = "127.0.0.1"; + public static final String TEST_PORT_4_DOM_1 = "8080"; + public static final String TEST_PORT2_4_DOM_1 = "8888"; + public static final String TEST_PORT3_4_DOM_1 = "80"; + public static final String TEST_TOKEN_4_DOM_1 = "abc"; + public static final String TEST_NEW_CLUSTER_4_DOM_1 = "TEST1"; - + public static final String TEST_DOM_2 = "nacos.test.2"; + public static final String TEST_IP_4_DOM_2 = "127.0.0.2"; + public static final String TEST_PORT_4_DOM_2 = "7070"; + public static final String TETS_TOKEN_4_DOM_2 = "xyz"; + public static final String TEST_SERVER_STATUS = "UP"; - + public static final String TEST_GROUP = "group"; + public static final String TEST_GROUP_1 = "group1"; + public static final String TEST_GROUP_2 = "group2"; - + public static final String TEST_NAMESPACE_1 = "namespace-1"; + public static final String TEST_NAMESPACE_2 = "namespace-2"; - - static final String NAMING_CONTROLLER_PATH = "/nacos/v1/ns"; - + public static final int TEST_PORT = 8080; - + public static final int TIME_OUT = 3000; - + + static final String NAMING_CONTROLLER_PATH = "/nacos/v1/ns"; + + private static final NacosRestTemplate nacosRestTemplate = NamingHttpClientManager.getInstance().getNacosRestTemplate(); + public static String randomDomainName() { StringBuilder sb = new StringBuilder(); sb.append("jinhan"); @@ -79,7 +97,7 @@ public static String randomDomainName() { } return sb.toString(); } - + public static Instance getInstance(String serviceName) { Instance instance = new Instance(); instance.setIp("127.0.0.1"); @@ -89,21 +107,20 @@ public static Instance getInstance(String serviceName) { Map instanceMeta = new HashMap(); instanceMeta.put("site", "et2"); instance.setMetadata(instanceMeta); - + instance.setServiceName(serviceName); instance.setClusterName("c1"); - + return instance; } - + public static boolean verifyInstance(Instance i1, Instance i2) { - - if (!i1.getIp().equals(i2.getIp()) || i1.getPort() != i2.getPort() || - i1.getWeight() != i2.getWeight() || i1.isHealthy() != i2.isHealthy() || - !i1.getMetadata().equals(i2.getMetadata())) { + + if (!i1.getIp().equals(i2.getIp()) || i1.getPort() != i2.getPort() || i1.getWeight() != i2.getWeight() + || i1.isHealthy() != i2.isHealthy() || !i1.getMetadata().equals(i2.getMetadata())) { return false; } - + //Service service1 = i1.getService(); //Service service2 = i2.getService(); // @@ -114,7 +131,7 @@ public static boolean verifyInstance(Instance i1, Instance i2) { // service1.isEnableHealthCheck() != service2.isEnableHealthCheck()) { // return false; //} - + //Cluster cluster1 = i1.getCluster(); //Cluster cluster2 = i2.getCluster(); // @@ -145,22 +162,22 @@ public static boolean verifyInstance(Instance i1, Instance i2) { // return false; // } //} - + return true; - + } - + public static boolean verifyInstanceList(List instanceList1, List instanceList2) { Map instanceMap = new HashMap(); for (Instance instance : instanceList1) { instanceMap.put(instance.getIp(), instance); } - + Map instanceGetMap = new HashMap(); for (Instance instance : instanceList2) { instanceGetMap.put(instance.getIp(), instance); } - + for (String ip : instanceMap.keySet()) { if (!instanceGetMap.containsKey(ip)) { return false; @@ -171,42 +188,45 @@ public static boolean verifyInstanceList(List instanceList1, List result = nacosRestTemplate.putForm(url, header, new HashMap<>(), String.class); System.out.println(result); - Assert.assertEquals(HttpStatus.SC_OK, result.getCode()); - - url = "http://127.0.0.1:" + localPort + normalizeContextPath(contextPath) + "/v1/ns/operator/switches?entry=autoChangeHealthCheckEnabled&value=" + false; - + assertEquals(HttpStatus.SC_OK, result.getCode()); + + url = "http://127.0.0.1:" + localPort + normalizeContextPath(contextPath) + + "/v1/ns/operator/switches?entry=autoChangeHealthCheckEnabled&value=" + false; + result = nacosRestTemplate.putForm(url, header, new HashMap<>(), String.class); System.out.println(result); - Assert.assertEquals(HttpStatus.SC_OK, result.getCode()); + assertEquals(HttpStatus.SC_OK, result.getCode()); } - public static void destoryServer(int localPort) throws Exception{ + public static void destoryServer(int localPort) throws Exception { destoryServer(localPort, "/nacos"); } - public static void destoryServer(int localPort, String contextPath) throws Exception{ - String url = "http://127.0.0.1:" + localPort + normalizeContextPath(contextPath) + "/v1/ns/operator/switches?entry=autoChangeHealthCheckEnabled&value=" + true; + public static void destoryServer(int localPort, String contextPath) throws Exception { + String url = "http://127.0.0.1:" + localPort + normalizeContextPath(contextPath) + + "/v1/ns/operator/switches?entry=autoChangeHealthCheckEnabled&value=" + true; Header header = Header.newInstance(); header.addParam(HttpHeaderConsts.USER_AGENT_HEADER, "Nacos-Server"); - + HttpRestResult result = nacosRestTemplate.putForm(url, header, new HashMap<>(), String.class); System.out.println(result); - Assert.assertEquals(HttpStatus.SC_OK, result.getCode()); + assertEquals(HttpStatus.SC_OK, result.getCode()); } public static String normalizeContextPath(String contextPath) { @@ -215,4 +235,17 @@ public static String normalizeContextPath(String contextPath) { } return contextPath.startsWith("/") ? contextPath : "/" + contextPath; } + + protected void isNamingServerReady() throws InterruptedException { + int retry = 0; + while (retry < 3) { + ResponseEntity response = request("/nacos/v1/ns/operator/metrics", Params.newParams().done(), + String.class); + if (response.getStatusCode().is2xxSuccessful() && response.getBody().contains("UP")) { + break; + } + retry++; + TimeUnit.SECONDS.sleep(5); + } + } } diff --git a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/NamingCompatibilityServiceTls_ITCase.java b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/NamingCompatibilityServiceTls_ITCase.java index 1379445f621..31b6ac9378f 100644 --- a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/NamingCompatibilityServiceTls_ITCase.java +++ b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/NamingCompatibilityServiceTls_ITCase.java @@ -27,15 +27,12 @@ import com.alibaba.nacos.api.naming.pojo.Service; import com.alibaba.nacos.api.selector.ExpressionSelector; import com.alibaba.nacos.api.selector.NoneSelector; -import com.alibaba.nacos.core.remote.tls.RpcServerTlsConfig; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import com.alibaba.nacos.common.remote.client.RpcConstants; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.junit4.SpringRunner; import java.util.HashMap; import java.util.List; @@ -43,45 +40,47 @@ import java.util.concurrent.TimeUnit; import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** + * NamingCompatibilityServiceTls_ITCase. + * * @author githucheng2978. * @date . **/ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Nacos.class, properties = { - "server.servlet.context-path=/nacos", - RpcServerTlsConfig.PREFIX+".enableTls=true", - RpcServerTlsConfig.PREFIX+".compatibility=true", - RpcServerTlsConfig.PREFIX+".certChainFile=test-server-cert.pem", - RpcServerTlsConfig.PREFIX+".certPrivateKey=test-server-key.pem", -}, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class NamingCompatibilityServiceTls_ITCase { - +@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos", + RpcConstants.NACOS_SERVER_RPC + ".enableTls=true", RpcConstants.NACOS_SERVER_RPC + ".compatibility=true", + RpcConstants.NACOS_SERVER_RPC + ".certChainFile=test-server-cert.pem", + RpcConstants.NACOS_SERVER_RPC + ".certPrivateKey=test-server-key.pem"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +class NamingCompatibilityServiceTls_ITCase { + private NamingMaintainService namingMaintainService; + private NamingService namingService; + private Instance instance; + private String serviceName; - + @LocalServerPort private int port; - - @Before - public void init() throws Exception { - + + @BeforeEach + void init() throws Exception { + NamingBase.prepareServer(port); - + if (namingMaintainService == null) { TimeUnit.SECONDS.sleep(10); namingMaintainService = NamingMaintainFactory.createMaintainService("127.0.0.1" + ":" + port); } - + if (namingService == null) { TimeUnit.SECONDS.sleep(10); namingService = NamingFactory.createNamingService("127.0.0.1" + ":" + port); } - + instance = new Instance(); instance.setIp("127.0.0.1"); instance.setPort(8081); @@ -91,13 +90,13 @@ public void init() throws Exception { map.put("netType", "external"); map.put("version", "1.0"); instance.setMetadata(map); - + serviceName = randomDomainName(); - + } - + @Test - public void updateInstance() throws NacosException, InterruptedException { + void updateInstance() throws NacosException, InterruptedException { Map map = new HashMap(); map.put("netType", "external-update"); map.put("version", "2.0"); @@ -106,13 +105,13 @@ public void updateInstance() throws NacosException, InterruptedException { namingMaintainService.updateInstance(serviceName, instance); TimeUnit.SECONDS.sleep(3L); List instances = namingService.getAllInstances(serviceName, false); - Assert.assertEquals(instances.size(), 1); - Assert.assertEquals("2.0", instances.get(0).getMetadata().get("version")); + assertEquals(1, instances.size()); + assertEquals("2.0", instances.get(0).getMetadata().get("version")); System.out.println(instances.get(0)); } - + @Test - public void updateInstanceWithDisable() throws NacosException, InterruptedException { + void updateInstanceWithDisable() throws NacosException, InterruptedException { Map map = new HashMap(); map.put("netType", "external-update"); map.put("version", "2.0"); @@ -122,11 +121,11 @@ public void updateInstanceWithDisable() throws NacosException, InterruptedExcept namingMaintainService.updateInstance(serviceName, instance); TimeUnit.SECONDS.sleep(3L); List instances = namingService.getAllInstances(serviceName, false); - Assert.assertEquals(0, instances.size()); + assertEquals(0, instances.size()); } - + @Test - public void createAndUpdateService() throws NacosException { + void createAndUpdateService() throws NacosException { String serviceName = randomDomainName(); // register service Service preService = new Service(); @@ -138,13 +137,13 @@ public void createAndUpdateService() throws NacosException { preService.setMetadata(metadata); ExpressionSelector selector = new ExpressionSelector(); selector.setExpression("CONSUMER.label.A=PROVIDER.label.A &CONSUMER.label.B=PROVIDER.label.B"); - + System.out.println("service info : " + preService); namingMaintainService.createService(preService, selector); Service remoteService = namingMaintainService.queryService(serviceName); System.out.println("remote service info : " + remoteService); - Assert.assertEquals(preService.toString(), remoteService.toString()); - + assertEquals(preService.toString(), remoteService.toString()); + // update service Service nowService = new Service(); nowService.setName(serviceName); @@ -153,26 +152,26 @@ public void createAndUpdateService() throws NacosException { metadata.clear(); metadata.put(serviceName, "this is a update metadata"); nowService.setMetadata(metadata); - + namingMaintainService.updateService(nowService, new NoneSelector()); remoteService = namingMaintainService.queryService(serviceName); System.out.println("remote service info : " + remoteService); - Assert.assertEquals(nowService.toString(), remoteService.toString()); + assertEquals(nowService.toString(), remoteService.toString()); } - + @Test - public void deleteService() throws NacosException { + void deleteService() throws NacosException { String serviceName = randomDomainName(); Service preService = new Service(); preService.setName(serviceName); System.out.println("service info : " + preService); namingMaintainService.createService(preService, new NoneSelector()); - - Assert.assertTrue(namingMaintainService.deleteService(serviceName)); + + assertTrue(namingMaintainService.deleteService(serviceName)); } - @After - public void tearDown() throws NacosException { + @AfterEach + void tearDown() throws NacosException { namingMaintainService.shutDown(); namingService.shutDown(); } diff --git a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/NamingMaintainService_ITCase.java b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/NamingMaintainService_ITCase.java index 7d5a21c6540..3a9c3780999 100644 --- a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/NamingMaintainService_ITCase.java +++ b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/NamingMaintainService_ITCase.java @@ -27,14 +27,11 @@ import com.alibaba.nacos.api.naming.pojo.Service; import com.alibaba.nacos.api.selector.ExpressionSelector; import com.alibaba.nacos.api.selector.NoneSelector; -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.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.junit4.SpringRunner; import java.util.HashMap; import java.util.List; @@ -42,39 +39,43 @@ import java.util.concurrent.TimeUnit; import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author liaochuntao * @date 2019-05-07 10:13 **/ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"}, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class NamingMaintainService_ITCase { - +@SpringBootTest(classes = Nacos.class, properties = { + "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +class NamingMaintainService_ITCase { + private NamingMaintainService namingMaintainService; + private NamingService namingService; + private Instance instance; + private String serviceName; - + @LocalServerPort private int port; - - @Before - public void init() throws Exception { - + + @BeforeEach + void init() throws Exception { + NamingBase.prepareServer(port); - + if (namingMaintainService == null) { TimeUnit.SECONDS.sleep(10); namingMaintainService = NamingMaintainFactory.createMaintainService("127.0.0.1" + ":" + port); } - + if (namingService == null) { TimeUnit.SECONDS.sleep(10); namingService = NamingFactory.createNamingService("127.0.0.1" + ":" + port); } - + instance = new Instance(); instance.setIp("127.0.0.1"); instance.setPort(8081); @@ -84,13 +85,13 @@ public void init() throws Exception { map.put("netType", "external"); map.put("version", "1.0"); instance.setMetadata(map); - + serviceName = randomDomainName(); - + } - + @Test - public void updateInstance() throws NacosException, InterruptedException { + void updateInstance() throws NacosException, InterruptedException { Map map = new HashMap(); map.put("netType", "external-update"); map.put("version", "2.0"); @@ -99,13 +100,13 @@ public void updateInstance() throws NacosException, InterruptedException { namingMaintainService.updateInstance(serviceName, instance); TimeUnit.SECONDS.sleep(3L); List instances = namingService.getAllInstances(serviceName, false); - Assert.assertEquals(instances.size(), 1); - Assert.assertEquals("2.0", instances.get(0).getMetadata().get("version")); + assertEquals(1, instances.size()); + assertEquals("2.0", instances.get(0).getMetadata().get("version")); System.out.println(instances.get(0)); } - + @Test - public void updateInstanceWithDisable() throws NacosException, InterruptedException { + void updateInstanceWithDisable() throws NacosException, InterruptedException { Map map = new HashMap(); map.put("netType", "external-update"); map.put("version", "2.0"); @@ -115,11 +116,11 @@ public void updateInstanceWithDisable() throws NacosException, InterruptedExcept namingMaintainService.updateInstance(serviceName, instance); TimeUnit.SECONDS.sleep(3L); List instances = namingService.getAllInstances(serviceName, false); - Assert.assertEquals(0, instances.size()); + assertEquals(0, instances.size()); } - + @Test - public void createAndUpdateService() throws NacosException { + void createAndUpdateService() throws NacosException { String serviceName = randomDomainName(); // register service Service preService = new Service(); @@ -131,13 +132,13 @@ public void createAndUpdateService() throws NacosException { preService.setMetadata(metadata); ExpressionSelector selector = new ExpressionSelector(); selector.setExpression("CONSUMER.label.A=PROVIDER.label.A &CONSUMER.label.B=PROVIDER.label.B"); - + System.out.println("service info : " + preService); namingMaintainService.createService(preService, selector); Service remoteService = namingMaintainService.queryService(serviceName); System.out.println("remote service info : " + remoteService); - Assert.assertEquals(preService.toString(), remoteService.toString()); - + assertEquals(preService.toString(), remoteService.toString()); + // update service Service nowService = new Service(); nowService.setName(serviceName); @@ -146,26 +147,26 @@ public void createAndUpdateService() throws NacosException { metadata.clear(); metadata.put(serviceName, "this is a update metadata"); nowService.setMetadata(metadata); - + namingMaintainService.updateService(nowService, new NoneSelector()); remoteService = namingMaintainService.queryService(serviceName); System.out.println("remote service info : " + remoteService); - Assert.assertEquals(nowService.toString(), remoteService.toString()); + assertEquals(nowService.toString(), remoteService.toString()); } - + @Test - public void deleteService() throws NacosException { + void deleteService() throws NacosException { String serviceName = randomDomainName(); Service preService = new Service(); preService.setName(serviceName); System.out.println("service info : " + preService); namingMaintainService.createService(preService, new NoneSelector()); - - Assert.assertTrue(namingMaintainService.deleteService(serviceName)); + + assertTrue(namingMaintainService.deleteService(serviceName)); } - @After - public void tearDown() throws NacosException { + @AfterEach + void tearDown() throws NacosException { namingMaintainService.shutDown(); namingService.shutDown(); } diff --git a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/NamingRaft_DITCase.java b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/NamingRaft_DITCase.java index 909c1addc03..501ee9711a3 100644 --- a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/NamingRaft_DITCase.java +++ b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/NamingRaft_DITCase.java @@ -19,47 +19,49 @@ import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.utils.NamingUtils; import com.alibaba.nacos.test.base.BaseClusterTest; -import org.junit.Assert; -import org.junit.FixMethodOrder; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + /** * @author liaochuntao */ -@Ignore -@FixMethodOrder(value = MethodSorters.NAME_ASCENDING) -public class NamingRaft_DITCase extends BaseClusterTest { - - @Test - public void test_register_instance() throws Exception { - String serviceName = NamingBase.randomDomainName(); - Instance instance = new Instance(); - instance.setEphemeral(true); //是否临时实例 - instance.setServiceName(serviceName); - instance.setClusterName("c1"); - instance.setIp("11.11.11.11"); - instance.setPort(80); - - try { - inaming7.registerInstance(serviceName, instance); - } catch (Throwable ex) { - ex.printStackTrace(); - Assert.fail(ex.getMessage()); - return; - } - List list = inaming8.getAllInstances(serviceName); - Assert.assertEquals(1, list.size()); - - Instance host = list.get(0); - - Assert.assertEquals(host.getIp(), instance.getIp()); - Assert.assertEquals(host.getPort(), instance.getPort()); - Assert.assertEquals(host.getServiceName(), NamingUtils.getGroupedName(instance.getServiceName(), "DEFAULT_GROUP")); - Assert.assertEquals(host.getClusterName(), instance.getClusterName()); - } - +@Disabled +@TestMethodOrder(MethodName.class) +class NamingRaft_DITCase extends BaseClusterTest { + + @Test + void test_register_instance() throws Exception { + String serviceName = NamingBase.randomDomainName(); + Instance instance = new Instance(); + instance.setEphemeral(true); //是否临时实例 + instance.setServiceName(serviceName); + instance.setClusterName("c1"); + instance.setIp("11.11.11.11"); + instance.setPort(80); + + try { + inaming7.registerInstance(serviceName, instance); + } catch (Throwable ex) { + ex.printStackTrace(); + fail(ex.getMessage()); + return; + } + List list = inaming8.getAllInstances(serviceName); + assertEquals(1, list.size()); + + Instance host = list.get(0); + + assertEquals(host.getIp(), instance.getIp()); + assertEquals(host.getPort(), instance.getPort()); + assertEquals(host.getServiceName(), NamingUtils.getGroupedName(instance.getServiceName(), "DEFAULT_GROUP")); + assertEquals(host.getClusterName(), instance.getClusterName()); + } + } diff --git a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/NamingTlsServiceAndMutualAuth_ITCase.java b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/NamingTlsServiceAndMutualAuth_ITCase.java index 2b598cdd294..3abe2568fd5 100644 --- a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/NamingTlsServiceAndMutualAuth_ITCase.java +++ b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/NamingTlsServiceAndMutualAuth_ITCase.java @@ -23,17 +23,13 @@ import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.common.remote.client.RpcConstants; -import com.alibaba.nacos.core.remote.tls.RpcServerTlsConfig; -import org.junit.After; -import org.junit.Assert; -import org.junit.FixMethodOrder; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.junit4.SpringRunner; import java.util.HashMap; import java.util.List; @@ -41,40 +37,37 @@ import java.util.concurrent.TimeUnit; import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; /** + * NamingTlsServiceAndMutualAuth_ITCase. + * * @author githucheng2978. * @date . **/ -@RunWith(SpringRunner.class) -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@SpringBootTest(classes = Nacos.class, properties = { - "server.servlet.context-path=/nacos", - RpcServerTlsConfig.PREFIX+".enableTls=true", - RpcServerTlsConfig.PREFIX+".mutualAuthEnable=true", - RpcServerTlsConfig.PREFIX+".compatibility=false", - RpcServerTlsConfig.PREFIX+".certChainFile=test-server-cert.pem", - RpcServerTlsConfig.PREFIX+".certPrivateKey=test-server-key.pem", - RpcServerTlsConfig.PREFIX+".trustCollectionCertFile=test-ca-cert.pem", - -}, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -@Ignore("TODO, Fix cert expired problem") -public class NamingTlsServiceAndMutualAuth_ITCase { - - +@TestMethodOrder(MethodName.class) +@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos", + RpcConstants.NACOS_SERVER_RPC + ".enableTls=true", RpcConstants.NACOS_SERVER_RPC + ".mutualAuthEnable=true", + RpcConstants.NACOS_SERVER_RPC + ".compatibility=false", RpcConstants.NACOS_SERVER_RPC + ".certChainFile=test-server-cert.pem", + RpcConstants.NACOS_SERVER_RPC + ".certPrivateKey=test-server-key.pem", RpcConstants.NACOS_SERVER_RPC + + ".trustCollectionCertFile=test-ca-cert.pem"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +@Disabled("TODO, Fix cert expired problem") +class NamingTlsServiceAndMutualAuth_ITCase { + + @LocalServerPort private int port; - + @Test - public void test_a_MutualAuth() throws NacosException { + void test_a_MutualAuth() throws NacosException { String serviceName = randomDomainName(); - System.setProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE,"true"); - System.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH,"test-ca-cert.pem"); - System.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_CHAIN_PATH,"test-client-cert.pem"); - System.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_KEY,"test-client-key.pem"); - System.setProperty(RpcConstants.RPC_CLIENT_MUTUAL_AUTH,"true"); - Instance instance = new Instance(); + System.setProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE, "true"); + System.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH, "test-ca-cert.pem"); + System.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_CHAIN_PATH, "test-client-cert.pem"); + System.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_KEY, "test-client-key.pem"); + System.setProperty(RpcConstants.RPC_CLIENT_MUTUAL_AUTH, "true"); + Instance instance = new Instance(); instance.setIp("127.0.0.1"); instance.setPort(8081); instance.setWeight(2); @@ -91,60 +84,65 @@ public void test_a_MutualAuth() throws NacosException { throw new RuntimeException(e); } List instances = namingService.getAllInstances(serviceName, false); - Assert.assertEquals(instances.size(), 1); - Assert.assertEquals("2.0", instances.get(0).getMetadata().get("version")); + assertEquals(1, instances.size()); + assertEquals("2.0", instances.get(0).getMetadata().get("version")); namingService.shutDown(); - + } - - - @Test(expected = NacosException.class) - public void test_b_MutualAuthClientTrustCa() throws NacosException { - String serviceName = randomDomainName(); - System.setProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE,"true"); - System.setProperty(RpcConstants.RPC_CLIENT_MUTUAL_AUTH,"true"); - System.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_CHAIN_PATH,""); - System.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_KEY,""); - System.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH,"test-ca-cert.pem"); - Instance instance = new Instance(); - instance.setIp("127.0.0.1"); - instance.setPort(8081); - instance.setWeight(2); - instance.setClusterName(Constants.DEFAULT_CLUSTER_NAME); - NamingService namingService = NamingFactory.createNamingService("127.0.0.1" + ":" + port); - Map map = new HashMap(); - map.put("netType", "external-update"); - map.put("version", "2.0"); - instance.setMetadata(map); - namingService.registerInstance(serviceName, instance); - namingService.shutDown(); - + + + @Test + void test_b_MutualAuthClientTrustCa() throws NacosException { + assertThrows(NacosException.class, () -> { + String serviceName = randomDomainName(); + System.setProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE, "true"); + System.setProperty(RpcConstants.RPC_CLIENT_MUTUAL_AUTH, "true"); + System.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_CHAIN_PATH, ""); + System.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_KEY, ""); + System.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH, "test-ca-cert.pem"); + Instance instance = new Instance(); + instance.setIp("127.0.0.1"); + instance.setPort(8081); + instance.setWeight(2); + instance.setClusterName(Constants.DEFAULT_CLUSTER_NAME); + NamingService namingService = NamingFactory.createNamingService("127.0.0.1" + ":" + port); + Map map = new HashMap(); + map.put("netType", "external-update"); + map.put("version", "2.0"); + instance.setMetadata(map); + namingService.registerInstance(serviceName, instance); + namingService.shutDown(); + + }); + } - - @Test(expected = NacosException.class) - public void test_c_MutualAuthClientTrustALl() throws NacosException { - String serviceName = randomDomainName(); - System.setProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE,"true"); - System.setProperty(RpcConstants.RPC_CLIENT_MUTUAL_AUTH,"true"); - System.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_CHAIN_PATH,""); - System.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_KEY,""); - System.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_ALL,"true"); - Instance instance = new Instance(); - instance.setIp("127.0.0.1"); - instance.setPort(8081); - instance.setWeight(2); - instance.setClusterName(Constants.DEFAULT_CLUSTER_NAME); - NamingService namingService = NamingFactory.createNamingService("127.0.0.1" + ":" + port); - Map map = new HashMap(); - map.put("netType", "external-update"); - map.put("version", "2.0"); - instance.setMetadata(map); - namingService.registerInstance(serviceName, instance); - namingService.shutDown(); + + @Test + void test_c_MutualAuthClientTrustALl() throws NacosException { + assertThrows(NacosException.class, () -> { + String serviceName = randomDomainName(); + System.setProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE, "true"); + System.setProperty(RpcConstants.RPC_CLIENT_MUTUAL_AUTH, "true"); + System.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_CHAIN_PATH, ""); + System.setProperty(RpcConstants.RPC_CLIENT_TLS_CERT_KEY, ""); + System.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_ALL, "true"); + Instance instance = new Instance(); + instance.setIp("127.0.0.1"); + instance.setPort(8081); + instance.setWeight(2); + instance.setClusterName(Constants.DEFAULT_CLUSTER_NAME); + NamingService namingService = NamingFactory.createNamingService("127.0.0.1" + ":" + port); + Map map = new HashMap(); + map.put("netType", "external-update"); + map.put("version", "2.0"); + instance.setMetadata(map); + namingService.registerInstance(serviceName, instance); + namingService.shutDown(); + }); } - - @After - public void after(){ - System.setProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE,""); + + @AfterEach + void after() { + System.setProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE, ""); } } diff --git a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/NamingTlsServiceTls_ITCase.java b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/NamingTlsServiceTls_ITCase.java index 8597a1aad2b..ab6b8a29e4c 100644 --- a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/NamingTlsServiceTls_ITCase.java +++ b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/NamingTlsServiceTls_ITCase.java @@ -23,16 +23,12 @@ import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.common.remote.client.RpcConstants; -import com.alibaba.nacos.core.remote.tls.RpcServerTlsConfig; -import org.junit.Assert; -import org.junit.FixMethodOrder; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.junit4.SpringRunner; import java.util.HashMap; import java.util.List; @@ -40,56 +36,58 @@ import java.util.concurrent.TimeUnit; import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; /** + * NamingTlsServiceTls_ITCase. + * * @author githucheng2978. * @date . **/ -@RunWith(SpringRunner.class) -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@SpringBootTest(classes = Nacos.class, properties = { - "server.servlet.context-path=/nacos", - RpcServerTlsConfig.PREFIX+".enableTls=true", - RpcServerTlsConfig.PREFIX+".compatibility=false", - RpcServerTlsConfig.PREFIX+".certChainFile=test-server-cert.pem", - RpcServerTlsConfig.PREFIX+".certPrivateKey=test-server-key.pem", -}, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -@Ignore("TODO, Fix cert expired problem") -public class NamingTlsServiceTls_ITCase { - - +@TestMethodOrder(MethodName.class) +@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos", + RpcConstants.NACOS_SERVER_RPC + ".enableTls=true", RpcConstants.NACOS_SERVER_RPC + ".compatibility=false", + RpcConstants.NACOS_SERVER_RPC + ".certChainFile=test-server-cert.pem", + RpcConstants.NACOS_SERVER_RPC + ".certPrivateKey=test-server-key.pem"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +@Disabled("TODO, Fix cert expired problem") +class NamingTlsServiceTls_ITCase { + + @LocalServerPort private int port; - - @Test(expected = NacosException.class) - public void Tls_a_ServerAndPlainClient() throws NacosException { - - Instance instance = new Instance(); - instance.setIp("127.0.0.1"); - instance.setPort(8081); - instance.setWeight(2); - instance.setClusterName(Constants.DEFAULT_CLUSTER_NAME); - NamingService namingService = NamingFactory.createNamingService("127.0.0.1" + ":" + port); - Map map = new HashMap(); - map.put("netType", "external-update"); - map.put("version", "2.0"); - namingService.registerInstance(randomDomainName(), instance); - namingService.shutDown(); - + + @Test + void Tls_a_ServerAndPlainClient() throws NacosException { + assertThrows(NacosException.class, () -> { + + Instance instance = new Instance(); + instance.setIp("127.0.0.1"); + instance.setPort(8081); + instance.setWeight(2); + instance.setClusterName(Constants.DEFAULT_CLUSTER_NAME); + NamingService namingService = NamingFactory.createNamingService("127.0.0.1" + ":" + port); + Map map = new HashMap(); + map.put("netType", "external-update"); + map.put("version", "2.0"); + namingService.registerInstance(randomDomainName(), instance); + namingService.shutDown(); + + }); + } - + @Test - public void Tls_b_ServerAndTlsClientTrustCa() throws NacosException { + void Tls_b_ServerAndTlsClientTrustCa() throws NacosException { String serviceName = randomDomainName(); - System.setProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE,"true"); - System.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH,"test-ca-cert.pem"); - Instance instance = new Instance(); + System.setProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE, "true"); + System.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_COLLECTION_CHAIN_PATH, "test-ca-cert.pem"); + Instance instance = new Instance(); instance.setIp("127.0.0.1"); instance.setPort(8081); instance.setWeight(2); instance.setClusterName(Constants.DEFAULT_CLUSTER_NAME); - NamingService namingService = NamingFactory.createNamingService("127.0.0.1" + ":" + port); + NamingService namingService = NamingFactory.createNamingService("127.0.0.1" + ":" + port); Map map = new HashMap(); map.put("netType", "external-update"); map.put("version", "2.0"); @@ -102,23 +100,23 @@ public void Tls_b_ServerAndTlsClientTrustCa() throws NacosException { throw new RuntimeException(e); } List instances = namingService.getAllInstances(serviceName, false); - Assert.assertEquals(instances.size(), 1); - Assert.assertEquals("2.0", instances.get(0).getMetadata().get("version")); + assertEquals(1, instances.size()); + assertEquals("2.0", instances.get(0).getMetadata().get("version")); namingService.shutDown(); - + } - + @Test - public void Tls_c_ServerAndTlsClientAll() throws NacosException { + void Tls_c_ServerAndTlsClientAll() throws NacosException { String serviceName = randomDomainName(); - System.setProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE,"true"); - System.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_ALL,"true"); - Instance instance = new Instance(); + System.setProperty(RpcConstants.RPC_CLIENT_TLS_ENABLE, "true"); + System.setProperty(RpcConstants.RPC_CLIENT_TLS_TRUST_ALL, "true"); + Instance instance = new Instance(); instance.setIp("127.0.0.1"); instance.setPort(8081); instance.setWeight(2); instance.setClusterName(Constants.DEFAULT_CLUSTER_NAME); - NamingService namingService = NamingFactory.createNamingService("127.0.0.1" + ":" + port); + NamingService namingService = NamingFactory.createNamingService("127.0.0.1" + ":" + port); Map map = new HashMap(); map.put("netType", "external-update"); map.put("version", "2.0"); @@ -130,8 +128,8 @@ public void Tls_c_ServerAndTlsClientAll() throws NacosException { throw new RuntimeException(e); } List instances = namingService.getAllInstances(serviceName, false); - Assert.assertEquals(instances.size(), 1); - Assert.assertEquals("2.0", instances.get(0).getMetadata().get("version")); + assertEquals(1, instances.size()); + assertEquals("2.0", instances.get(0).getMetadata().get("version")); System.out.println(instances.get(0)); namingService.shutDown(); } diff --git a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/RandomUtils.java b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/RandomUtils.java index cc2079e109e..b3ea81ff5ff 100644 --- a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/RandomUtils.java +++ b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/RandomUtils.java @@ -13,9 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.test.naming; -import java.util.*; +import java.util.Collection; +import java.util.HashSet; +import java.util.Random; +import java.util.Set; +import java.util.UUID; /** * Created by wangtong.wt on 2018/6/20. @@ -24,39 +29,43 @@ * @date 2018/6/20 */ public class RandomUtils { + + private static final String STRING_POOL = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + private static Random rd = new Random(); + private static int UNICODE_START = 19968; + private static int UNICODE_END = 40864; - private static final String STRING_POOL = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; - + private RandomUtils() { } - + public static long getLong() { return rd.nextLong(); } - + public static long getLongMoreThanZero() { long res; - for(res = rd.nextLong(); res <= 0L; res = rd.nextLong()) { + for (res = rd.nextLong(); res <= 0L; res = rd.nextLong()) { } - + return res; } - + public static long getLongLessThan(long n) { long res = rd.nextLong(); return res % n; } - + public static long getLongMoreThanZeroLessThan(long n) { long res; - for(res = getLongLessThan(n); res <= 0L; res = getLongLessThan(n)) { + for (res = getLongLessThan(n); res <= 0L; res = getLongLessThan(n)) { } - + return res; } - + public static long getLongBetween(long n, long m) { if (m <= n) { return n; @@ -65,32 +74,32 @@ public static long getLongBetween(long n, long m) { return n + res % (m - n); } } - + public static int getInteger() { return rd.nextInt(); } - + public static int getIntegerMoreThanZero() { int res; - for(res = rd.nextInt(); res <= 0; res = rd.nextInt()) { + for (res = rd.nextInt(); res <= 0; res = rd.nextInt()) { } - + return res; } - + public static int getIntegerLessThan(int n) { int res = rd.nextInt(); return res % n; } - + public static int getIntegerMoreThanZeroLessThan(int n) { int res; - for(res = rd.nextInt(n); res == 0; res = rd.nextInt(n)) { + for (res = rd.nextInt(n); res == 0; res = rd.nextInt(n)) { } - + return res; } - + public static int getIntegerBetween(int n, int m) { if (m == n) { return n; @@ -99,71 +108,71 @@ public static int getIntegerBetween(int n, int m) { return n + res % (m - n); } } - + private static char getChar(int[] arg) { int size = arg.length; int c = rd.nextInt(size / 2); c *= 2; - return (char)getIntegerBetween(arg[c], arg[c + 1]); + return (char) getIntegerBetween(arg[c], arg[c + 1]); } - + private static String getString(int n, int[] arg) { StringBuilder res = new StringBuilder(); - - for(int i = 0; i < n; ++i) { + + for (int i = 0; i < n; ++i) { res.append(getChar(arg)); } - + return res.toString(); } - + public static String getStringWithCharacter(int n) { - int[] arg = new int[]{97, 123, 65, 91}; + int[] arg = new int[] {97, 123, 65, 91}; return getString(n, arg); } - + public static String getStringWithNumber(int n) { - int[] arg = new int[]{48, 58}; + int[] arg = new int[] {48, 58}; return getString(n, arg); } - + public static String getStringWithNumAndCha(int n) { - int[] arg = new int[]{97, 123, 65, 91, 48, 58}; + int[] arg = new int[] {97, 123, 65, 91, 48, 58}; return getString(n, arg); } - + public static String getRandomString(int length) { StringBuilder sb = new StringBuilder(); Random random = new Random(); int range = STRING_POOL.length(); - - for(int i = 0; i < length; ++i) { + + for (int i = 0; i < length; ++i) { sb.append(STRING_POOL.charAt(random.nextInt(range))); } - + return sb.toString(); } - + public static String getStringShortenThan(int n) { int len = getIntegerMoreThanZeroLessThan(n); return getStringWithCharacter(len); } - + public static String getStringWithNumAndChaShortenThan(int n) { int len = getIntegerMoreThanZeroLessThan(n); return getStringWithNumAndCha(len); } - + public static String getStringBetween(int n, int m) { int len = getIntegerBetween(n, m); return getStringWithCharacter(len); } - + public static String getStringWithNumAndChaBetween(int n, int m) { int len = getIntegerBetween(n, m); return getStringWithNumAndCha(len); } - + public static String getStringWithPrefix(int n, String prefix) { int len = prefix.length(); if (n <= len) { @@ -175,7 +184,7 @@ public static String getStringWithPrefix(int n, String prefix) { return res.toString(); } } - + public static String getStringWithSuffix(int n, String suffix) { int len = suffix.length(); if (n <= len) { @@ -188,7 +197,7 @@ public static String getStringWithSuffix(int n, String suffix) { return res.toString(); } } - + public static String getStringWithBoth(int n, String prefix, String suffix) { int len = prefix.length() + suffix.length(); StringBuilder res = new StringBuilder(prefix); @@ -201,7 +210,7 @@ public static String getStringWithBoth(int n, String prefix, String suffix) { return res.toString(); } } - + public static String getCheseWordWithPrifix(int n, String prefix) { int len = prefix.length(); if (n <= len) { @@ -213,7 +222,7 @@ public static String getCheseWordWithPrifix(int n, String prefix) { return res.toString(); } } - + public static String getCheseWordWithSuffix(int n, String suffix) { int len = suffix.length(); if (n <= len) { @@ -226,7 +235,7 @@ public static String getCheseWordWithSuffix(int n, String suffix) { return res.toString(); } } - + public static String getCheseWordWithBoth(int n, String prefix, String suffix) { int len = prefix.length() + suffix.length(); StringBuilder res = new StringBuilder(prefix); @@ -239,89 +248,89 @@ public static String getCheseWordWithBoth(int n, String prefix, String suffix) { return res.toString(); } } - + public static String getCheseWord(int len) { StringBuilder res = new StringBuilder(); - - for(int i = 0; i < len; ++i) { + + for (int i = 0; i < len; ++i) { char str = getCheseChar(); res.append(str); } - + return res.toString(); } - + private static char getCheseChar() { - return (char)(UNICODE_START + rd.nextInt(UNICODE_END - UNICODE_START)); + return (char) (UNICODE_START + rd.nextInt(UNICODE_END - UNICODE_START)); } - + public static boolean getBoolean() { return getIntegerMoreThanZeroLessThan(3) == 1; } - + public static String getStringByUUID() { return UUID.randomUUID().toString(); } - + public static int[] getRandomArray(int min, int max, int n) { int len = max - min + 1; if (max >= min && n <= len) { int[] source = new int[len]; - - for(int i = min; i < min + len; source[i - min] = i++) { + + for (int i = min; i < min + len; source[i - min] = i++) { } - + int[] result = new int[n]; Random rd = new Random(); - - for(int i = 0; i < result.length; ++i) { + + for (int i = 0; i < result.length; ++i) { int index = Math.abs(rd.nextInt() % len--); result[i] = source[index]; source[index] = source[len]; } - + return result; } else { return null; } } - + public static Collection getRandomCollection(int min, int max, int n) { Set res = new HashSet(); int mx = max; int mn = min; int i; if (n == max + 1 - min) { - for(i = 1; i <= n; ++i) { + for (i = 1; i <= n; ++i) { res.add(i); } - + return res; } else { - for(i = 0; i < n; ++i) { + for (i = 0; i < n; ++i) { int v = getIntegerBetween(mn, mx); if (v == mx) { --mx; } - + if (v == mn) { ++mn; } - - while(res.contains(v)) { + + while (res.contains(v)) { v = getIntegerBetween(mn, mx); if (v == mx) { mx = v; } - + if (v == mn) { mn = v; } } - + res.add(v); } - + return res; } } diff --git a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/RestAPI_ITCase.java b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/RestAPI_ITCase.java index 62a7db7e129..0ba1a0e2f1d 100644 --- a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/RestAPI_ITCase.java +++ b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/RestAPI_ITCase.java @@ -13,253 +13,208 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.test.naming; import com.alibaba.nacos.Nacos; import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.test.base.Params; import com.fasterxml.jackson.databind.JsonNode; - -import org.junit.*; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; import java.net.URL; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author nkorange */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"}, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class RestAPI_ITCase extends NamingBase { - +@SpringBootTest(classes = Nacos.class, properties = { + "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +class RestAPI_ITCase extends NamingBase { + @LocalServerPort private int port; - - @Before - public void setUp() throws Exception { + + @BeforeEach + void setUp() throws Exception { String url = String.format("http://localhost:%d/", port); this.base = new URL(url); + isNamingServerReady(); //prepareData(); } - - @After - public void cleanup() throws Exception { + + @AfterEach + void cleanup() throws Exception { //removeData(); } - + @Test - public void metrics() throws Exception { - + void metrics() throws Exception { + ResponseEntity response = request("/nacos/v1/ns/operator/metrics", - Params.newParams().appendParam("onlyStatus", "false").done(), - String.class); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - + Params.newParams().appendParam("onlyStatus", "false").done(), String.class); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + JsonNode json = JacksonUtils.toObj(response.getBody()); - Assert.assertNotNull(json.get("serviceCount")); - Assert.assertNotNull(json.get("instanceCount")); - Assert.assertNotNull(json.get("responsibleInstanceCount")); - Assert.assertNotNull(json.get("clientCount")); - Assert.assertNotNull(json.get("connectionBasedClientCount")); - Assert.assertNotNull(json.get("ephemeralIpPortClientCount")); - Assert.assertNotNull(json.get("persistentIpPortClientCount")); - Assert.assertNotNull(json.get("responsibleClientCount")); + assertNotNull(json.get("serviceCount")); + assertNotNull(json.get("instanceCount")); + assertNotNull(json.get("responsibleInstanceCount")); + assertNotNull(json.get("clientCount")); + assertNotNull(json.get("connectionBasedClientCount")); + assertNotNull(json.get("ephemeralIpPortClientCount")); + assertNotNull(json.get("persistentIpPortClientCount")); + assertNotNull(json.get("responsibleClientCount")); } - + /** * @TCDescription : 根据serviceName创建服务 * @TestStep : * @ExpectResult : */ @Test - public void createService() throws Exception { + void createService() throws Exception { String serviceName = NamingBase.randomDomainName(); ResponseEntity response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", - Params.newParams() - .appendParam("serviceName", serviceName) - .appendParam("protectThreshold", "0.3") - .done(), - String.class, - HttpMethod.POST); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - Assert.assertEquals("ok", response.getBody()); - + Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.3") + .done(), String.class, HttpMethod.POST); + assertTrue(response.getStatusCode().is2xxSuccessful()); + assertEquals("ok", response.getBody()); + namingServiceDelete(serviceName); } - + /** * @TCDescription : 根据serviceName获取服务信息 * @TestStep : * @ExpectResult : */ @Test - public void getService() throws Exception { + void getService() throws Exception { String serviceName = NamingBase.randomDomainName(); ResponseEntity response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", - Params.newParams() - .appendParam("serviceName", serviceName) - .appendParam("protectThreshold", "0.3") - .done(), - String.class, - HttpMethod.POST); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - Assert.assertEquals("ok", response.getBody()); - + Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.3") + .done(), String.class, HttpMethod.POST); + assertTrue(response.getStatusCode().is2xxSuccessful()); + assertEquals("ok", response.getBody()); + //get service response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", - Params.newParams() - .appendParam("serviceName", serviceName) - .appendParam("protectThreshold", "0.3") - .done(), - String.class); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - + Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.3") + .done(), String.class); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + JsonNode json = JacksonUtils.toObj(response.getBody()); - Assert.assertEquals(serviceName, json.get("name").asText()); - + assertEquals(serviceName, json.get("name").asText()); + namingServiceDelete(serviceName); } - + /** * @TCDescription : 获取服务list信息 * @TestStep : * @ExpectResult : */ @Test - public void listService() throws Exception { + void listService() throws Exception { String serviceName = NamingBase.randomDomainName(); //get service ResponseEntity response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service/list", - Params.newParams() - .appendParam("serviceName", serviceName) - .appendParam("pageNo", "1") - .appendParam("pageSize", "150") - .done(), - String.class); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + Params.newParams().appendParam("serviceName", serviceName).appendParam("pageNo", "1") + .appendParam("pageSize", "150").done(), String.class); + + assertTrue(response.getStatusCode().is2xxSuccessful()); JsonNode json = JacksonUtils.toObj(response.getBody()); int count = json.get("count").asInt(); - Assert.assertTrue(count >= 0); - + assertTrue(count >= 0); + response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", - Params.newParams() - .appendParam("serviceName", serviceName) - .appendParam("protectThreshold", "0.3") - .done(), - String.class, - HttpMethod.POST); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - Assert.assertEquals("ok", response.getBody()); - + Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.3") + .done(), String.class, HttpMethod.POST); + assertTrue(response.getStatusCode().is2xxSuccessful()); + assertEquals("ok", response.getBody()); + response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service/list", - Params.newParams() - .appendParam("serviceName", serviceName) - .appendParam("pageNo", "1") - .appendParam("pageSize", "150") - .done(), - String.class); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + Params.newParams().appendParam("serviceName", serviceName).appendParam("pageNo", "1") + .appendParam("pageSize", "150").done(), String.class); + + assertTrue(response.getStatusCode().is2xxSuccessful()); json = JacksonUtils.toObj(response.getBody()); - Assert.assertEquals(count + 1, json.get("count").asInt()); - + assertEquals(count + 1, json.get("count").asInt()); + namingServiceDelete(serviceName); } - + /** * @TCDescription : 更新serviceName获取服务信息 * @TestStep : * @ExpectResult : */ @Test - public void updateService() throws Exception { + void updateService() throws Exception { String serviceName = NamingBase.randomDomainName(); ResponseEntity response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", - Params.newParams() - .appendParam("serviceName", serviceName) - .appendParam("protectThreshold", "0.6") - .done(), - String.class, - HttpMethod.POST); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - Assert.assertEquals("ok", response.getBody()); - + Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.6") + .done(), String.class, HttpMethod.POST); + assertTrue(response.getStatusCode().is2xxSuccessful()); + assertEquals("ok", response.getBody()); + //update service response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", - Params.newParams() - .appendParam("serviceName", serviceName) - .appendParam("healthCheckMode", "server") - .appendParam("protectThreshold", "0.3") - .done(), - String.class, - HttpMethod.PUT); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - Assert.assertEquals("ok", response.getBody()); - + Params.newParams().appendParam("serviceName", serviceName).appendParam("healthCheckMode", "server") + .appendParam("protectThreshold", "0.3").done(), String.class, HttpMethod.PUT); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + assertEquals("ok", response.getBody()); + //get service response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", - Params.newParams() - .appendParam("serviceName", serviceName) - .done(), - String.class); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); + Params.newParams().appendParam("serviceName", serviceName).done(), String.class); + + assertTrue(response.getStatusCode().is2xxSuccessful()); JsonNode json = JacksonUtils.toObj(response.getBody()); System.out.println(json); - Assert.assertEquals(0.3f, json.get("protectThreshold").floatValue(), 0.0f); - + assertEquals(0.3f, json.get("protectThreshold").floatValue(), 0.0f); + namingServiceDelete(serviceName); } - + @Test - @Ignore - public void testInvalidNamespace() { - + @Disabled + void testInvalidNamespace() { + String serviceName = NamingBase.randomDomainName(); ResponseEntity response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", - Params.newParams() - .appendParam("serviceName", serviceName) - .appendParam("protectThreshold", "0.6") - .appendParam("namespaceId", "..invalid-namespace") - .done(), - String.class, - HttpMethod.POST); - Assert.assertTrue(response.getStatusCode().is4xxClientError()); - + Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.6") + .appendParam("namespaceId", "..invalid-namespace").done(), String.class, HttpMethod.POST); + assertTrue(response.getStatusCode().is4xxClientError()); + response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", - Params.newParams() - .appendParam("serviceName", serviceName) - .appendParam("protectThreshold", "0.6") - .appendParam("namespaceId", "/invalid-namespace") - .done(), - String.class, - HttpMethod.POST); - Assert.assertTrue(response.getStatusCode().is4xxClientError()); - + Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.6") + .appendParam("namespaceId", "/invalid-namespace").done(), String.class, HttpMethod.POST); + assertTrue(response.getStatusCode().is4xxClientError()); + } - + private void namingServiceDelete(String serviceName) { //delete service ResponseEntity response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", - Params.newParams() - .appendParam("serviceName", serviceName) - .appendParam("protectThreshold", "0.3") - .done(), - String.class, - HttpMethod.DELETE); - - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - Assert.assertEquals("ok", response.getBody()); + Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.3") + .done(), String.class, HttpMethod.DELETE); + + assertTrue(response.getStatusCode().is2xxSuccessful()); + assertEquals("ok", response.getBody()); } - + } diff --git a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/SelectInstances_ITCase.java b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/SelectInstances_ITCase.java index 842cb6c198e..d3518efaa25 100644 --- a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/SelectInstances_ITCase.java +++ b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/SelectInstances_ITCase.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.test.naming; import com.alibaba.nacos.Nacos; @@ -22,15 +23,12 @@ import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; import com.alibaba.nacos.api.selector.ExpressionSelector; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.junit4.SpringRunner; import java.util.Arrays; import java.util.HashMap; @@ -38,7 +36,11 @@ import java.util.Map; import java.util.concurrent.TimeUnit; -import static com.alibaba.nacos.test.naming.NamingBase.*; +import static com.alibaba.nacos.test.naming.NamingBase.TEST_PORT; +import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName; +import static com.alibaba.nacos.test.naming.NamingBase.verifyInstanceList; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Created by wangtong.wt on 2018/6/20. @@ -46,19 +48,29 @@ * @author wangtong.wt * @date 2018/6/20 */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"}, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class SelectInstances_ITCase { - +@SpringBootTest(classes = Nacos.class, properties = { + "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +class SelectInstances_ITCase { + private static NamingService naming; private static NamingService naming1; + @LocalServerPort private int port; - - @Before - public void init() throws Exception { + + @AfterAll + static void tearDown() throws NacosException { + if (null != naming) { + naming.shutDown(); + } + if (null != naming1) { + naming1.shutDown(); + } + } + + @BeforeEach + void init() throws Exception { NamingBase.prepareServer(port); if (naming == null) { //TimeUnit.SECONDS.sleep(10); @@ -67,7 +79,7 @@ public void init() throws Exception { } int i = 5; while (i >= 0) { - i --; + i--; if (!"UP".equals(naming.getServerStatus())) { Thread.sleep(1000L); continue; @@ -76,33 +88,23 @@ public void init() throws Exception { } } - @AfterClass - public static void tearDown() throws NacosException { - if (null != naming) { - naming.shutDown(); - } - if (null != naming1) { - naming1.shutDown(); - } - } - /** * 获取所有健康的Instance * * @throws Exception */ @Test - public void selectHealthyInstances() throws Exception { + void selectHealthyInstances() throws Exception { String serviceName = randomDomainName(); naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT); naming1.registerInstance(serviceName, "1.1.1.1", 9090); - + TimeUnit.SECONDS.sleep(10); - + List instances = naming.selectInstances(serviceName, true); - - Assert.assertEquals(2, instances.size()); - + + assertEquals(2, instances.size()); + Instance instanceNotH = null; List instancesGet = naming.getAllInstances(serviceName); for (Instance instance : instancesGet) { @@ -110,316 +112,316 @@ public void selectHealthyInstances() throws Exception { instanceNotH = instance; } } - + instancesGet.remove(instanceNotH); - - Assert.assertTrue(verifyInstanceList(instances, instancesGet)); + + assertTrue(verifyInstanceList(instances, instancesGet)); } - + /** * 获取所有不健康的Instance * * @throws Exception */ @Test - public void selectUnhealthyInstances() throws Exception { + void selectUnhealthyInstances() throws Exception { String serviceName = randomDomainName(); naming.registerInstance(serviceName, "1.1.1.1", TEST_PORT); naming1.registerInstance(serviceName, "1.1.1.2", TEST_PORT); - + TimeUnit.SECONDS.sleep(8); List instances = naming.selectInstances(serviceName, false); - + TimeUnit.SECONDS.sleep(2); - Assert.assertEquals(0, instances.size()); - + assertEquals(0, instances.size()); + List instancesGet = naming.getAllInstances(serviceName); - - Assert.assertTrue(verifyInstanceList(instances, instancesGet)); + + assertTrue(verifyInstanceList(instances, instancesGet)); } - + /** * 获取指定cluster中(单个、多个)所有健康的Instance * * @throws Exception */ @Test - public void selectHealthyInstancesClusters() throws Exception { + void selectHealthyInstancesClusters() throws Exception { String serviceName = randomDomainName(); naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1"); naming1.registerInstance(serviceName, "127.0.0.2", 9090, "c2"); - + TimeUnit.SECONDS.sleep(8); List instances = naming.selectInstances(serviceName, Arrays.asList("c1", "c2"), true); TimeUnit.SECONDS.sleep(2); - Assert.assertEquals(instances.size(), 2); - + assertEquals(2, instances.size()); + List instancesGet = naming.getAllInstances(serviceName); - - Assert.assertTrue(verifyInstanceList(instances, instancesGet)); + + assertTrue(verifyInstanceList(instances, instancesGet)); } - + /** * 获取指定cluster中(单个、多个)不所有健康的Instance * * @throws Exception */ @Test - public void selectUnhealthyInstancesClusters() throws Exception { + void selectUnhealthyInstancesClusters() throws Exception { String serviceName = randomDomainName(); naming.registerInstance(serviceName, "1.1.1.1", TEST_PORT, "c1"); naming1.registerInstance(serviceName, "1.1.1.2", TEST_PORT, "c2"); - + TimeUnit.SECONDS.sleep(8); List instances = naming.selectInstances(serviceName, Arrays.asList("c1", "c2"), false); TimeUnit.SECONDS.sleep(2); - Assert.assertEquals(0, instances.size()); - + assertEquals(0, instances.size()); + List instancesGet = naming.getAllInstances(serviceName); - - Assert.assertTrue(verifyInstanceList(instances, instancesGet)); + + assertTrue(verifyInstanceList(instances, instancesGet)); } - + @Test - public void selectInstancesCheckClusterName() throws Exception { - + void selectInstancesCheckClusterName() throws Exception { + String serviceName = randomDomainName(); naming.registerInstance(serviceName, "1.1.1.1", TEST_PORT, "c1"); naming1.registerInstance(serviceName, "1.1.1.2", TEST_PORT, "c2"); - + TimeUnit.SECONDS.sleep(8); - + List instancesGet = naming.getAllInstances(serviceName); - - Assert.assertEquals(2, instancesGet.size()); - + + assertEquals(2, instancesGet.size()); + for (Instance instance : instancesGet) { if (instance.getIp().equals("1.1.1.1")) { - Assert.assertEquals(instance.getClusterName(), "c1"); + assertEquals("c1", instance.getClusterName()); } if (instance.getIp().equals("2.2.2.2")) { - Assert.assertEquals(instance.getClusterName(), "c2"); + assertEquals("c2", instance.getClusterName()); } } } - - + + /** * 获取权重不为0的Instance * * @throws Exception */ @Test - public void selectAllWeightedInstances() throws Exception { + void selectAllWeightedInstances() throws Exception { String serviceName = randomDomainName(); naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT); naming1.registerInstance(serviceName, "1.1.1.1", 9090); - + TimeUnit.SECONDS.sleep(10); - + List instances = naming.getAllInstances(serviceName); - - Assert.assertEquals(instances.size(), 2); - + + assertEquals(2, instances.size()); + instances = naming.selectInstances(serviceName, true); - - Assert.assertEquals(2, instances.size()); - + + assertEquals(2, instances.size()); + instances.get(0).setWeight(0); - + instances = naming.selectInstances(serviceName, true); - - Assert.assertEquals(1, instances.size()); - + + assertEquals(1, instances.size()); + Instance instanceNotH = null; List instancesGet = naming.getAllInstances(serviceName); - + for (Instance instance : instancesGet) { if (!instance.isHealthy() || !instance.isEnabled() || instance.getWeight() <= 0) { - + instanceNotH = instance; } } - + instancesGet.remove(instanceNotH); - - Assert.assertTrue(verifyInstanceList(instances, instancesGet)); + + assertTrue(verifyInstanceList(instances, instancesGet)); } - - + + /** * 获取指定cluster中(单个、多个)所有权重不为0的Instance * * @throws Exception */ @Test - public void selectAllWeightedInstancesClusters() throws Exception { + void selectAllWeightedInstancesClusters() throws Exception { String serviceName = randomDomainName(); naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1"); naming1.registerInstance(serviceName, "1.1.1.1", 9090, "c2"); - + TimeUnit.SECONDS.sleep(10); - + List instances = naming.getAllInstances(serviceName); - - Assert.assertEquals(instances.size(), 2); - + + assertEquals(2, instances.size()); + instances = naming.selectInstances(serviceName, Arrays.asList("c1", "c2"), true); - - Assert.assertEquals(2, instances.size()); - + + assertEquals(2, instances.size()); + instances.get(0).setWeight(0); - + instances = naming.selectInstances(serviceName, Arrays.asList("c1", "c2"), true); - - Assert.assertEquals(1, instances.size()); - + + assertEquals(1, instances.size()); + Instance instanceNotH = null; List instancesGet = naming.getAllInstances(serviceName); - + for (Instance instance : instancesGet) { if (!instance.isHealthy() || !instance.isEnabled() || instance.getWeight() <= 0) { - + instanceNotH = instance; } } - + instancesGet.remove(instanceNotH); - - Assert.assertTrue(verifyInstanceList(instances, instancesGet)); + + assertTrue(verifyInstanceList(instances, instancesGet)); } - - + + /** * 获取所有Enable的Instance * * @throws Exception */ @Test - public void selectAllEnabledInstances() throws Exception { + void selectAllEnabledInstances() throws Exception { String serviceName = randomDomainName(); naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT); naming1.registerInstance(serviceName, "1.1.1.1", 9090); - + TimeUnit.SECONDS.sleep(10); - + List instances = naming.getAllInstances(serviceName); - - Assert.assertEquals(instances.size(), 2); - + + assertEquals(2, instances.size()); + instances = naming.selectInstances(serviceName, true); - - Assert.assertEquals(2, instances.size()); - + + assertEquals(2, instances.size()); + instances.get(0).setEnabled(false); - + instances = naming.selectInstances(serviceName, true); - - Assert.assertEquals(1, instances.size()); - + + assertEquals(1, instances.size()); + Instance instanceNotH = null; List instancesGet = naming.getAllInstances(serviceName); - + for (Instance instance : instancesGet) { if (!instance.isHealthy() || !instance.isEnabled() || instance.getWeight() <= 0) { - + instanceNotH = instance; } } - + instancesGet.remove(instanceNotH); - - Assert.assertTrue(verifyInstanceList(instances, instancesGet)); + + assertTrue(verifyInstanceList(instances, instancesGet)); } - - + + /** * 获取指定cluster中(单个、多个)所有Enabled的Instance * * @throws Exception */ @Test - public void selectAllEnabledInstancesClusters() throws Exception { + void selectAllEnabledInstancesClusters() throws Exception { String serviceName = randomDomainName(); System.out.println(serviceName); naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1"); naming1.registerInstance(serviceName, "1.1.1.1", 9090, "c2"); - + TimeUnit.SECONDS.sleep(5); - + List instances = naming.getAllInstances(serviceName); - - Assert.assertEquals(instances.size(), 2); - + + assertEquals(2, instances.size()); + instances = naming.selectInstances(serviceName, Arrays.asList("c1", "c2"), true); - - Assert.assertEquals(2, instances.size()); - + + assertEquals(2, instances.size()); + instances.get(0).setEnabled(false); - + instances = naming.selectInstances(serviceName, Arrays.asList("c1", "c2"), true); - + TimeUnit.SECONDS.sleep(5); - - Assert.assertEquals(1, instances.size()); - + + assertEquals(1, instances.size()); + Instance instanceNotH = null; List instancesGet = naming.getAllInstances(serviceName); - + for (Instance instance : instancesGet) { if (!instance.isHealthy() || !instance.isEnabled() || instance.getWeight() <= 0) { - + instanceNotH = instance; } } - + instancesGet.remove(instanceNotH); - - Assert.assertTrue(verifyInstanceList(instances, instancesGet)); + + assertTrue(verifyInstanceList(instances, instancesGet)); } - + @Test - @Ignore("TODO nacos 2.0 can't support selector for now") - public void getServiceListWithSelector() throws NacosException, InterruptedException { - + @Disabled("TODO nacos 2.0 can't support selector for now") + void getServiceListWithSelector() throws NacosException, InterruptedException { + String serviceName = randomDomainName(); Instance instance = new Instance(); instance.setIp("128.0.0.1"); instance.setPort(999); instance.setServiceName(serviceName); - + Map metadata = new HashMap(); metadata.put("registerSource", "dubbo"); instance.setMetadata(metadata); - + naming.registerInstance(serviceName, instance); naming.registerInstance(serviceName, "127.0.0.1", 80, "c1"); naming.registerInstance(serviceName, "127.0.0.2", 80, "c2"); - + TimeUnit.SECONDS.sleep(10); - + ExpressionSelector expressionSelector = new ExpressionSelector(); expressionSelector.setExpression("INSTANCE.label.registerSource = 'dubbo'"); ListView serviceList = naming.getServicesOfServer(1, 10, expressionSelector); - - Assert.assertTrue(serviceList.getData().contains(serviceName)); - + + assertTrue(serviceList.getData().contains(serviceName)); + serviceName = randomDomainName(); - + instance.setServiceName(serviceName); metadata.put("registerSource", "spring"); instance.setMetadata(metadata); - + naming.registerInstance(serviceName, instance); - + TimeUnit.SECONDS.sleep(10); - + expressionSelector.setExpression("INSTANCE.label.registerSource = 'spring'"); serviceList = naming.getServicesOfServer(1, 10, expressionSelector); - - Assert.assertTrue(serviceList.getData().contains(serviceName)); - + + assertTrue(serviceList.getData().contains(serviceName)); + } - - + + } diff --git a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/SelectOneHealthyInstance_ITCase.java b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/SelectOneHealthyInstance_ITCase.java index 5be26cde12e..36a7512f407 100644 --- a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/SelectOneHealthyInstance_ITCase.java +++ b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/SelectOneHealthyInstance_ITCase.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.test.naming; import com.alibaba.nacos.Nacos; @@ -20,20 +21,22 @@ import com.alibaba.nacos.api.naming.NamingFactory; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.junit4.SpringRunner; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; -import static com.alibaba.nacos.test.naming.NamingBase.*; +import static com.alibaba.nacos.test.naming.NamingBase.TEST_PORT; +import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName; +import static com.alibaba.nacos.test.naming.NamingBase.verifyInstance; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * Created by wangtong.wt on 2018/6/20. @@ -41,32 +44,25 @@ * @author wangtong.wt * @date 2018/6/20 */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"}, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class SelectOneHealthyInstance_ITCase { - +@SpringBootTest(classes = Nacos.class, properties = { + "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +class SelectOneHealthyInstance_ITCase { + private static NamingService naming; + private static NamingService naming1; + private static NamingService naming2; + private static NamingService naming3; + private static NamingService naming4; + @LocalServerPort private int port; - @Before - public void init() throws Exception{ - if (naming == null) { - //TimeUnit.SECONDS.sleep(10); - naming = NamingFactory.createNamingService("127.0.0.1"+":"+port); - naming1 = NamingFactory.createNamingService("127.0.0.1"+":"+port); - naming2 = NamingFactory.createNamingService("127.0.0.1"+":"+port); - naming3 = NamingFactory.createNamingService("127.0.0.1"+":"+port); - naming4 = NamingFactory.createNamingService("127.0.0.1"+":"+port); - } - } - @AfterClass - public static void tearDown() throws NacosException { + @AfterAll + static void tearDown() throws NacosException { if (null != naming) { naming.shutDown(); } @@ -83,94 +79,106 @@ public static void tearDown() throws NacosException { naming4.shutDown(); } } - + + @BeforeEach + void init() throws Exception { + if (naming == null) { + //TimeUnit.SECONDS.sleep(10); + naming = NamingFactory.createNamingService("127.0.0.1" + ":" + port); + naming1 = NamingFactory.createNamingService("127.0.0.1" + ":" + port); + naming2 = NamingFactory.createNamingService("127.0.0.1" + ":" + port); + naming3 = NamingFactory.createNamingService("127.0.0.1" + ":" + port); + naming4 = NamingFactory.createNamingService("127.0.0.1" + ":" + port); + } + } + /** * 获取一个健康的Instance + * * @throws Exception */ @Test - public void selectOneHealthyInstances() throws Exception { + void selectOneHealthyInstances() throws Exception { String serviceName = randomDomainName(); naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT); naming1.registerInstance(serviceName, "127.0.0.1", 60000); - + TimeUnit.SECONDS.sleep(2); Instance instance = naming.selectOneHealthyInstance(serviceName); - + List instancesGet = naming.getAllInstances(serviceName); - + for (Instance instance1 : instancesGet) { - if (instance1.getIp().equals(instance.getIp())&& - instance1.getPort() == instance.getPort()) { - Assert.assertTrue(instance.isHealthy()); - Assert.assertTrue(verifyInstance(instance1, instance)); + if (instance1.getIp().equals(instance.getIp()) && instance1.getPort() == instance.getPort()) { + assertTrue(instance.isHealthy()); + assertTrue(verifyInstance(instance1, instance)); return; } } - - Assert.fail(); + + fail(); } - + /** * 获取指定单个cluster中一个健康的Instance + * * @throws Exception */ @Test - public void selectOneHealthyInstancesCluster() throws Exception { + void selectOneHealthyInstancesCluster() throws Exception { String serviceName = randomDomainName(); naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1"); naming1.registerInstance(serviceName, "127.0.0.1", 60000, "c1"); naming2.registerInstance(serviceName, "1.1.1.1", TEST_PORT, "c1"); naming3.registerInstance(serviceName, "127.0.0.1", 60001, "c1"); naming4.registerInstance(serviceName, "127.0.0.1", 60002, "c2"); - + TimeUnit.SECONDS.sleep(2); Instance instance = naming.selectOneHealthyInstance(serviceName, Arrays.asList("c1")); - - Assert.assertNotSame("1.1.1.1", instance.getIp()); - Assert.assertTrue(instance.getPort() != 60002); - + + assertNotSame("1.1.1.1", instance.getIp()); + assertTrue(instance.getPort() != 60002); + List instancesGet = naming.getAllInstances(serviceName); - + for (Instance instance1 : instancesGet) { - if (instance1.getIp().equals(instance.getIp())&& - instance1.getPort() == instance.getPort()) { - Assert.assertTrue(instance.isHealthy()); - Assert.assertTrue(verifyInstance(instance1, instance)); + if (instance1.getIp().equals(instance.getIp()) && instance1.getPort() == instance.getPort()) { + assertTrue(instance.isHealthy()); + assertTrue(verifyInstance(instance1, instance)); return; } } - - Assert.fail(); + + fail(); } - + /** * 获取指定多个cluster中一个健康的Instance + * * @throws Exception */ @Test - public void selectOneHealthyInstancesClusters() throws Exception { + void selectOneHealthyInstancesClusters() throws Exception { String serviceName = randomDomainName(); naming.registerInstance(serviceName, "1.1.1.1", TEST_PORT, "c1"); naming1.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1"); naming2.registerInstance(serviceName, "127.0.0.1", 60000, "c1"); naming3.registerInstance(serviceName, "127.0.0.1", 60001, "c2"); - + TimeUnit.SECONDS.sleep(2); Instance instance = naming.selectOneHealthyInstance(serviceName, Arrays.asList("c1", "c2")); - Assert.assertNotSame("1.1.1.1", instance.getIp()); - + assertNotSame("1.1.1.1", instance.getIp()); + List instancesGet = naming.getAllInstances(serviceName); - + for (Instance instance1 : instancesGet) { - if (instance1.getIp().equals(instance.getIp()) && - instance1.getPort() == instance.getPort()) { - Assert.assertTrue(instance.isHealthy()); - Assert.assertTrue(verifyInstance(instance1, instance)); + if (instance1.getIp().equals(instance.getIp()) && instance1.getPort() == instance.getPort()) { + assertTrue(instance.isHealthy()); + assertTrue(verifyInstance(instance1, instance)); return; } } - - Assert.fail(); + + fail(); } } diff --git a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/ServiceListTest_ITCase.java b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/ServiceListTest_ITCase.java index 4a02b23d893..7280bf8382b 100644 --- a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/ServiceListTest_ITCase.java +++ b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/ServiceListTest_ITCase.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.test.naming; import com.alibaba.nacos.Nacos; @@ -25,84 +26,80 @@ import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; import com.alibaba.nacos.api.naming.pojo.ServiceInfo; -import com.alibaba.nacos.sys.utils.ApplicationUtils; -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.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.junit4.SpringRunner; import java.util.Collections; import java.util.List; import static com.alibaba.nacos.test.naming.NamingBase.TEST_PORT; import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author nkorange */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"}, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class ServiceListTest_ITCase { - +@SpringBootTest(classes = Nacos.class, properties = { + "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +class ServiceListTest_ITCase { + + private static int listenseCount = 0; + private NamingService naming; - + private volatile List instances = Collections.emptyList(); - - private static int listenseCount = 0; - + @LocalServerPort private int port; - - @Before - public void init() throws Exception { + + @BeforeEach + void init() throws Exception { if (naming == null) { naming = NamingFactory.createNamingService("127.0.0.1" + ":" + port); } } - + @Test - public void serviceList() throws NacosException { + void serviceList() throws NacosException { naming.getServicesOfServer(1, 10); } - + /** * @throws NacosException * @description 获取当前订阅的所有服务 */ @Test - public void getSubscribeServices() throws NacosException, InterruptedException { - + void getSubscribeServices() throws NacosException, InterruptedException { + ListView listView = naming.getServicesOfServer(1, 10); if (listView != null && listView.getCount() > 0) { naming.getAllInstances(listView.getData().get(0)); } List serviceInfoList = naming.getSubscribeServices(); int count = serviceInfoList.size(); - + String serviceName = randomDomainName(); naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1"); - + naming.subscribe(serviceName, new EventListener() { @Override public void onEvent(Event event) { - + } }); - + serviceInfoList = naming.getSubscribeServices(); - Assert.assertEquals(count + 1, serviceInfoList.size()); + assertEquals(count + 1, serviceInfoList.size()); } - + /** * @throws NacosException * @description 删除注册,获取当前订阅的所有服务 */ @Test - public void getSubscribeServices_deregisterInstance() throws NacosException, InterruptedException { + void getSubscribeServices_deregisterInstance() throws NacosException, InterruptedException { listenseCount = 0; EventListener listener = new EventListener() { @Override @@ -112,21 +109,21 @@ public void onEvent(Event event) { listenseCount++; } }; - + List serviceInfoList = naming.getSubscribeServices(); int count = serviceInfoList.size(); - + String serviceName = randomDomainName(); naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1"); - + naming.subscribe(serviceName, listener); - + serviceInfoList = naming.getSubscribeServices(); - - Assert.assertEquals(count + 1, serviceInfoList.size()); - + + assertEquals(count + 1, serviceInfoList.size()); + naming.deregisterInstance(serviceName, "127.0.0.1", TEST_PORT, "c1"); - - Assert.assertEquals(count + 1, serviceInfoList.size()); + + assertEquals(count + 1, serviceInfoList.size()); } } diff --git a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/Starter_ITCase.java b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/Starter_ITCase.java index 74c816879c5..c285499ffbb 100644 --- a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/Starter_ITCase.java +++ b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/Starter_ITCase.java @@ -13,10 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.test.naming; /** * @author nkorange */ public class Starter_ITCase { + } diff --git a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/SubscribeCluster_ITCase.java b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/SubscribeCluster_ITCase.java index ed2c04145d8..866628b4a79 100644 --- a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/SubscribeCluster_ITCase.java +++ b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/SubscribeCluster_ITCase.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.test.naming; import com.alibaba.nacos.Nacos; @@ -22,21 +23,22 @@ import com.alibaba.nacos.api.naming.listener.EventListener; import com.alibaba.nacos.api.naming.listener.NamingEvent; import com.alibaba.nacos.api.naming.pojo.Instance; -import com.alibaba.nacos.sys.utils.ApplicationUtils; -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.Timeout; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.junit4.SpringRunner; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; -import static com.alibaba.nacos.test.naming.NamingBase.*; +import static com.alibaba.nacos.test.naming.NamingBase.TEST_PORT; +import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName; +import static com.alibaba.nacos.test.naming.NamingBase.verifyInstanceList; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * Created by wangtong.wt on 2018/6/20. @@ -44,35 +46,36 @@ * @author wangtong.wt * @date 2018/6/20 */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"}, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class SubscribeCluster_ITCase { - +@SpringBootTest(classes = Nacos.class, properties = { + "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +class SubscribeCluster_ITCase { + private NamingService naming; + @LocalServerPort private int port; - - @Before - public void init() throws Exception { + + private volatile List instances = Collections.emptyList(); + + @BeforeEach + void init() throws Exception { instances.clear(); if (naming == null) { //TimeUnit.SECONDS.sleep(10); naming = NamingFactory.createNamingService("127.0.0.1" + ":" + port); } } - - private volatile List instances = Collections.emptyList(); - + /** * 添加IP,收到通知 * * @throws Exception */ - @Test(timeout = 10000L) - public void subscribeAdd() throws Exception { + @Test + @Timeout(value = 10000L, unit = TimeUnit.MILLISECONDS) + void subscribeAdd() throws Exception { String serviceName = randomDomainName(); - + naming.subscribe(serviceName, Arrays.asList("c1"), new EventListener() { @Override public void onEvent(Event event) { @@ -81,31 +84,32 @@ public void onEvent(Event event) { instances = ((NamingEvent) event).getInstances(); } }); - + naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1"); - + while (instances.isEmpty()) { Thread.sleep(1000L); } - - Assert.assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName))); + + assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName))); } - + /** * 删除IP,收到通知 * * @throws Exception */ - @Test(timeout = 10000L) - public void subscribeDelete() throws Exception { + @Test + @Timeout(value = 10000L, unit = TimeUnit.MILLISECONDS) + void subscribeDelete() throws Exception { String serviceName = randomDomainName(); naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1"); - + TimeUnit.SECONDS.sleep(3); - + naming.subscribe(serviceName, Arrays.asList("c1"), new EventListener() { int index = 0; - + @Override public void onEvent(Event event) { if (index == 0) { @@ -117,27 +121,28 @@ public void onEvent(Event event) { instances = ((NamingEvent) event).getInstances(); } }); - + TimeUnit.SECONDS.sleep(1); - + naming.deregisterInstance(serviceName, "127.0.0.1", TEST_PORT, "c1"); - + while (!instances.isEmpty()) { Thread.sleep(1000L); } - - Assert.assertTrue(instances.isEmpty()); + + assertTrue(instances.isEmpty()); } - + /** * 添加不可用IP,收到通知 * * @throws Exception */ - @Test(timeout = 10000L) - public void subscribeUnhealthy() throws Exception { + @Test + @Timeout(value = 10000L, unit = TimeUnit.MILLISECONDS) + void subscribeUnhealthy() throws Exception { String serviceName = randomDomainName(); - + naming.subscribe(serviceName, Arrays.asList("c1"), new EventListener() { @Override public void onEvent(Event event) { @@ -146,28 +151,28 @@ public void onEvent(Event event) { instances = ((NamingEvent) event).getInstances(); } }); - + naming.registerInstance(serviceName, "1.1.1.1", TEST_PORT, "c1"); - + while (instances.isEmpty()) { Thread.sleep(1000L); } - - Assert.assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName))); + + assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName))); } - + /** * 新增其他cluster IP,不会收到通知 * * @throws Exception */ @Test - public void subscribeOtherCluster() throws Exception { + void subscribeOtherCluster() throws Exception { String serviceName = randomDomainName(); - + naming.subscribe(serviceName, Arrays.asList("c2"), new EventListener() { int index = 0; - + @Override public void onEvent(Event event) { if (index == 0) { @@ -179,9 +184,9 @@ public void onEvent(Event event) { instances = ((NamingEvent) event).getInstances(); } }); - + naming.registerInstance(serviceName, "1.1.1.1", TEST_PORT, "c1"); - + int i = 0; while (instances.isEmpty()) { Thread.sleep(1000L); @@ -189,7 +194,7 @@ public void onEvent(Event event) { return; } } - - Assert.fail(); + + fail(); } } diff --git a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/SubscribeSelector_ITCase.java b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/SubscribeSelector_ITCase.java new file mode 100644 index 00000000000..23894acceac --- /dev/null +++ b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/SubscribeSelector_ITCase.java @@ -0,0 +1,168 @@ +/* + * Copyright 1999-2023 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.test.naming; + +import com.alibaba.nacos.Nacos; +import com.alibaba.nacos.api.naming.NamingFactory; +import com.alibaba.nacos.api.naming.NamingService; +import com.alibaba.nacos.api.naming.listener.Event; +import com.alibaba.nacos.api.naming.listener.EventListener; +import com.alibaba.nacos.api.naming.listener.NamingEvent; +import com.alibaba.nacos.api.naming.pojo.Instance; +import com.alibaba.nacos.api.naming.selector.NamingSelector; +import com.alibaba.nacos.client.naming.selector.DefaultNamingSelector; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort; + +import java.util.Collections; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * @author lideyou + */ +@SpringBootTest(classes = Nacos.class, properties = { + "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +class SubscribeSelector_ITCase extends NamingBase { + + private NamingService naming; + + private NamingSelector selector = new DefaultNamingSelector(instance -> instance.getIp().startsWith("172.18.137")); + + @LocalServerPort + private int port; + + private volatile List instances = Collections.emptyList(); + + @BeforeEach + void init() throws Exception { + instances.clear(); + if (naming == null) { + naming = NamingFactory.createNamingService("127.0.0.1" + ":" + port); + } + } + + /** + * Add IP and receive notification. + * + * @throws Exception + */ + @Test + @Timeout(value = 10000L, unit = TimeUnit.MILLISECONDS) + void subscribeAdd() throws Exception { + String serviceName = randomDomainName(); + + naming.subscribe(serviceName, selector, new EventListener() { + @Override + public void onEvent(Event event) { + System.out.println(((NamingEvent) event).getServiceName()); + System.out.println(((NamingEvent) event).getInstances()); + instances = ((NamingEvent) event).getInstances(); + } + }); + + naming.registerInstance(serviceName, "172.18.137.1", TEST_PORT); + + while (instances.isEmpty()) { + Thread.sleep(1000L); + } + + assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName))); + } + + /** + * Delete IP and receive notification. + * + * @throws Exception + */ + @Test + @Timeout(value = 10000L, unit = TimeUnit.MILLISECONDS) + void subscribeDelete() throws Exception { + String serviceName = randomDomainName(); + naming.registerInstance(serviceName, "172.18.137.1", TEST_PORT, "c1"); + + TimeUnit.SECONDS.sleep(3); + + naming.subscribe(serviceName, selector, new EventListener() { + int index = 0; + + @Override + public void onEvent(Event event) { + instances = ((NamingEvent) event).getInstances(); + if (index == 0) { + index++; + return; + } + System.out.println(((NamingEvent) event).getServiceName()); + System.out.println(((NamingEvent) event).getInstances()); + } + }); + + TimeUnit.SECONDS.sleep(1); + + naming.deregisterInstance(serviceName, "172.18.137.1", TEST_PORT, "c1"); + + while (!instances.isEmpty()) { + Thread.sleep(1000L); + } + + assertTrue(instances.isEmpty()); + } + + /** + * Add non target IP and do not receive notification. + * + * @throws Exception + */ + @Test + void subscribeOtherIp() throws Exception { + String serviceName = randomDomainName(); + + naming.subscribe(serviceName, selector, new EventListener() { + int index = 0; + + @Override + public void onEvent(Event event) { + instances = ((NamingEvent) event).getInstances(); + if (index == 0) { + index++; + return; + } + System.out.println(((NamingEvent) event).getServiceName()); + System.out.println(((NamingEvent) event).getInstances()); + } + }); + + naming.registerInstance(serviceName, "1.1.1.1", TEST_PORT, "c1"); + + int i = 0; + while (instances.isEmpty()) { + Thread.sleep(1000L); + if (i++ > 10) { + return; + } + } + + fail(); + } +} diff --git a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/Subscribe_ITCase.java b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/Subscribe_ITCase.java index e97eb66f056..f88334411dc 100644 --- a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/Subscribe_ITCase.java +++ b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/Subscribe_ITCase.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.test.naming; import com.alibaba.nacos.Nacos; @@ -22,26 +23,30 @@ import com.alibaba.nacos.api.naming.listener.EventListener; import com.alibaba.nacos.api.naming.listener.NamingEvent; import com.alibaba.nacos.api.naming.pojo.Instance; +import com.alibaba.nacos.client.naming.listener.AbstractNamingChangeListener; +import com.alibaba.nacos.client.naming.listener.NamingChangeEvent; import com.alibaba.nacos.common.utils.ConcurrentHashSet; import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.test.base.Params; import com.fasterxml.jackson.databind.JsonNode; - -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.Timeout; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.Properties; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * Created by wangtong.wt on 2018/6/20. @@ -49,17 +54,19 @@ * @author wangtong.wt * @date 2018/6/20 */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"}, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class Subscribe_ITCase extends NamingBase { - +@SpringBootTest(classes = Nacos.class, properties = { + "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +class Subscribe_ITCase extends NamingBase { + private NamingService naming; + @LocalServerPort private int port; - - @Before - public void init() throws Exception { + + private volatile List instances = Collections.emptyList(); + + @BeforeEach + void init() throws Exception { instances.clear(); if (naming == null) { //TimeUnit.SECONDS.sleep(10); @@ -71,18 +78,17 @@ public void init() throws Exception { String url = String.format("http://localhost:%d/", port); this.base = new URL(url); } - - private volatile List instances = Collections.emptyList(); - + /** * 添加IP,收到通知 * * @throws Exception */ - @Test(timeout = 4 * TIME_OUT) - public void subscribeAdd() throws Exception { + @Test + @Timeout(value = 4 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + void subscribeAdd() throws Exception { String serviceName = randomDomainName(); - + naming.subscribe(serviceName, new EventListener() { @Override public void onEvent(Event event) { @@ -91,31 +97,32 @@ public void onEvent(Event event) { instances = ((NamingEvent) event).getInstances(); } }); - + naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1"); - + while (instances.isEmpty()) { Thread.sleep(1000L); } - - Assert.assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName))); + + assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName))); } - + /** * 删除IP,收到通知 * * @throws Exception */ - @Test(timeout = 4 * TIME_OUT) - public void subscribeDelete() throws Exception { + @Test + @Timeout(value = 4 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + void subscribeDelete() throws Exception { String serviceName = randomDomainName(); naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1"); - + TimeUnit.SECONDS.sleep(3); - + naming.subscribe(serviceName, new EventListener() { int index = 0; - + @Override public void onEvent(Event event) { if (index == 0) { @@ -127,27 +134,28 @@ public void onEvent(Event event) { instances = ((NamingEvent) event).getInstances(); } }); - + TimeUnit.SECONDS.sleep(1); - + naming.deregisterInstance(serviceName, "127.0.0.1", TEST_PORT, "c1"); - + while (!instances.isEmpty()) { Thread.sleep(1000L); } - - Assert.assertTrue(instances.isEmpty()); + + assertTrue(instances.isEmpty()); } - + /** * 添加不可用IP,收到通知 * * @throws Exception */ - @Test(timeout = 4 * TIME_OUT) - public void subscribeUnhealthy() throws Exception { + @Test + @Timeout(value = 4 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + void subscribeUnhealthy() throws Exception { String serviceName = randomDomainName(); - + naming.subscribe(serviceName, new EventListener() { @Override public void onEvent(Event event) { @@ -156,21 +164,22 @@ public void onEvent(Event event) { instances = ((NamingEvent) event).getInstances(); } }); - + naming.registerInstance(serviceName, "1.1.1.1", TEST_PORT, "c1"); - + while (instances.isEmpty()) { Thread.sleep(1000L); } - - Assert.assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName))); + + assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName))); } - @Test(timeout = 4 * TIME_OUT) - public void subscribeEmpty() throws Exception { - + @Test + @Timeout(value = 4 * TIME_OUT, unit = TimeUnit.MILLISECONDS) + void subscribeEmpty() throws Exception { + String serviceName = randomDomainName(); - + naming.subscribe(serviceName, new EventListener() { @Override public void onEvent(Event event) { @@ -179,32 +188,32 @@ public void onEvent(Event event) { instances = ((NamingEvent) event).getInstances(); } }); - + naming.registerInstance(serviceName, "1.1.1.1", TEST_PORT, "c1"); - + while (instances.isEmpty()) { Thread.sleep(1000L); } - - Assert.assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName))); - + + assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName))); + naming.deregisterInstance(serviceName, "1.1.1.1", TEST_PORT, "c1"); - + while (!instances.isEmpty()) { Thread.sleep(1000L); } - - Assert.assertEquals(0, instances.size()); - Assert.assertEquals(0, naming.getAllInstances(serviceName).size()); + + assertEquals(0, instances.size()); + assertEquals(0, naming.getAllInstances(serviceName).size()); } - + @Test - public void querySubscribers() throws Exception { - + void querySubscribers() throws Exception { + String serviceName = randomDomainName(); - + naming.registerInstance(serviceName, "1.1.1.1", TEST_PORT, "c1"); - + EventListener listener = new EventListener() { @Override public void onEvent(Event event) { @@ -213,30 +222,25 @@ public void onEvent(Event event) { instances = ((NamingEvent) event).getInstances(); } }; - + naming.subscribe(serviceName, listener); - + TimeUnit.SECONDS.sleep(3); - + ResponseEntity response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service/subscribers", - Params.newParams() - .appendParam("serviceName", serviceName) - .appendParam("pageNo", "1") - .appendParam("pageSize", "10") - .done(), - String.class, - HttpMethod.GET); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - + Params.newParams().appendParam("serviceName", serviceName).appendParam("pageNo", "1").appendParam("pageSize", "10").done(), + String.class, HttpMethod.GET); + assertTrue(response.getStatusCode().is2xxSuccessful()); + JsonNode body = JacksonUtils.toObj(response.getBody()); - - Assert.assertEquals(1, body.get("subscribers").size()); - + + assertEquals(1, body.get("subscribers").size()); + Properties properties = new Properties(); properties.setProperty("namingRequestTimeout", "300000"); properties.setProperty("serverAddr", "127.0.0.1" + ":" + port); NamingService naming2 = NamingFactory.createNamingService(properties); - + naming2.subscribe(serviceName, new EventListener() { @Override public void onEvent(Event event) { @@ -245,27 +249,22 @@ public void onEvent(Event event) { instances = ((NamingEvent) event).getInstances(); } }); - + TimeUnit.SECONDS.sleep(3); - + response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service/subscribers", - Params.newParams() - .appendParam("serviceName", serviceName) - .appendParam("pageNo", "1") - .appendParam("pageSize", "10") - .done(), - String.class, - HttpMethod.GET); - Assert.assertTrue(response.getStatusCode().is2xxSuccessful()); - + Params.newParams().appendParam("serviceName", serviceName).appendParam("pageNo", "1").appendParam("pageSize", "10").done(), + String.class, HttpMethod.GET); + assertTrue(response.getStatusCode().is2xxSuccessful()); + body = JacksonUtils.toObj(response.getBody()); - + // server will remove duplicate subscriber by ip port service app and so on - Assert.assertEquals(1, body.get("subscribers").size()); + assertEquals(1, body.get("subscribers").size()); } @Test - public void subscribeSameServiceForTwoNamingService() throws Exception { + void subscribeSameServiceForTwoNamingService() throws Exception { Properties properties1 = new Properties(); properties1.setProperty("serverAddr", "127.0.0.1" + ":" + port); properties1.setProperty("namespace", "ns-001"); @@ -294,7 +293,7 @@ public void onEvent(Event event) { concurrentHashSet1.addAll(((NamingEvent) event).getInstances()); } }); - + naming1.registerInstance(serviceName, "1.1.1.1", TEST_PORT, "c1"); while (instances.isEmpty()) { @@ -302,11 +301,73 @@ public void onEvent(Event event) { } try { - Assert.assertTrue(verifyInstanceList(instances, naming1.getAllInstances(serviceName))); - Assert.assertEquals(0, concurrentHashSet1.size()); + assertTrue(verifyInstanceList(instances, naming1.getAllInstances(serviceName))); + assertEquals(0, concurrentHashSet1.size()); } finally { naming1.shutDown(); naming2.shutDown(); } } + + @Test + void subscribeUsingAbstractNamingChangeListener() throws Exception { + String serviceName = randomDomainName(); + + naming.subscribe(serviceName, new AbstractNamingChangeListener() { + @Override + public void onChange(NamingChangeEvent event) { + System.out.println(event.getServiceName()); + System.out.println(event.getInstances()); + instances = event.getInstances(); + assertTrue(event.isAdded()); + } + }); + + naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1"); + + while (instances.isEmpty()) { + Thread.sleep(1000L); + } + + assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName))); + } + + @Test + void testListenerFirstCallback() throws Exception { + String serviceName = randomDomainName(); + AtomicInteger count = new AtomicInteger(0); + naming.subscribe(serviceName, new EventListener() { + @Override + public void onEvent(Event event) { + System.out.println(((NamingEvent) event).getServiceName()); + System.out.println(((NamingEvent) event).getInstances()); + instances = ((NamingEvent) event).getInstances(); + count.incrementAndGet(); + } + }); + + naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1"); + + while (instances.isEmpty()) { + Thread.sleep(1000L); + } + + naming.subscribe(serviceName, new EventListener() { + @Override + public void onEvent(Event event) { + System.out.println(((NamingEvent) event).getServiceName()); + System.out.println(((NamingEvent) event).getInstances()); + instances = ((NamingEvent) event).getInstances(); + count.incrementAndGet(); + } + }); + + int i = 0; + while (count.get() < 2) { + Thread.sleep(1000L); + if (i++ > 10) { + fail(); + } + } + } } diff --git a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/Unsubscribe_ITCase.java b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/Unsubscribe_ITCase.java index 993e2d21a7c..74819fc1c20 100644 --- a/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/Unsubscribe_ITCase.java +++ b/test/naming-test/src/test/java/com/alibaba/nacos/test/naming/Unsubscribe_ITCase.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.test.naming; import com.alibaba.nacos.Nacos; @@ -22,20 +23,22 @@ import com.alibaba.nacos.api.naming.listener.EventListener; import com.alibaba.nacos.api.naming.listener.NamingEvent; import com.alibaba.nacos.api.naming.pojo.Instance; -import com.alibaba.nacos.sys.utils.ApplicationUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import com.alibaba.nacos.api.naming.selector.NamingSelector; +import com.alibaba.nacos.client.naming.selector.DefaultNamingSelector; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.junit4.SpringRunner; import java.util.Arrays; import java.util.Collections; import java.util.List; -import static com.alibaba.nacos.test.naming.NamingBase.*; +import static com.alibaba.nacos.test.naming.NamingBase.TEST_PORT; +import static com.alibaba.nacos.test.naming.NamingBase.randomDomainName; +import static com.alibaba.nacos.test.naming.NamingBase.verifyInstanceList; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * Created by wangtong.wt on 2018/6/20. @@ -43,58 +46,59 @@ * @author wangtong.wt * @date 2018/6/20 */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"}, - webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class Unsubscribe_ITCase { - +@SpringBootTest(classes = Nacos.class, properties = { + "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +class Unsubscribe_ITCase { + private NamingService naming; + @LocalServerPort private int port; - - @Before - public void init() throws Exception { + + private volatile List instances = Collections.emptyList(); + + @BeforeEach + void init() throws Exception { instances = Collections.emptyList(); if (naming == null) { //TimeUnit.SECONDS.sleep(10); - naming = NamingFactory.createNamingService("127.0.0.1"+":"+port); + naming = NamingFactory.createNamingService("127.0.0.1" + ":" + port); } } - - private volatile List instances = Collections.emptyList(); - + /** * 取消订阅,添加IP,不会收到通知 + * * @throws Exception */ @Test - public void unsubscribe() throws Exception { + void unsubscribe() throws Exception { String serviceName = randomDomainName(); - + EventListener listener = new EventListener() { @Override public void onEvent(Event event) { - System.out.println(((NamingEvent)event).getServiceName()); - System.out.println(((NamingEvent)event).getInstances()); - instances = ((NamingEvent)event).getInstances(); + System.out.println(((NamingEvent) event).getServiceName()); + System.out.println(((NamingEvent) event).getInstances()); + instances = ((NamingEvent) event).getInstances(); } }; - + naming.subscribe(serviceName, listener); - + naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1"); - + while (instances.isEmpty()) { Thread.sleep(1000L); } - - Assert.assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName))); - + + assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName))); + naming.unsubscribe(serviceName, listener); - + instances = Collections.emptyList(); naming.registerInstance(serviceName, "127.0.0.2", TEST_PORT, "c1"); - + int i = 0; while (instances.isEmpty()) { Thread.sleep(1000L); @@ -102,42 +106,43 @@ public void onEvent(Event event) { return; } } - - Assert.fail(); + + fail(); } - + /** * 取消订阅,在指定cluster添加IP,不会收到通知 + * * @throws Exception */ @Test - public void unsubscribeCluster() throws Exception { + void unsubscribeCluster() throws Exception { String serviceName = randomDomainName(); - + EventListener listener = new EventListener() { @Override public void onEvent(Event event) { - System.out.println(((NamingEvent)event).getServiceName()); - System.out.println(((NamingEvent)event).getInstances()); - instances = ((NamingEvent)event).getInstances(); + System.out.println(((NamingEvent) event).getServiceName()); + System.out.println(((NamingEvent) event).getInstances()); + instances = ((NamingEvent) event).getInstances(); } }; - + naming.subscribe(serviceName, Arrays.asList("c1"), listener); - + naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1"); - + while (instances.isEmpty()) { Thread.sleep(1000L); } - - Assert.assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName))); - + + assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName))); + naming.unsubscribe(serviceName, Arrays.asList("c1"), listener); - + instances = Collections.emptyList(); naming.registerInstance(serviceName, "127.0.0.2", TEST_PORT, "c1"); - + int i = 0; while (instances.isEmpty()) { Thread.sleep(1000L); @@ -145,8 +150,54 @@ public void onEvent(Event event) { return; } } - - Assert.fail(); + + fail(); } - + + /** + * 取消订阅,添加选择器范围 IP,不会收到通知 + * + * @throws Exception + */ + @Test + void unsubscribeSelector() throws Exception { + String serviceName = randomDomainName(); + + EventListener listener = new EventListener() { + @Override + public void onEvent(Event event) { + System.out.println(((NamingEvent) event).getServiceName()); + System.out.println(((NamingEvent) event).getInstances()); + instances = ((NamingEvent) event).getInstances(); + } + }; + + NamingSelector selector = new DefaultNamingSelector(instance -> instance.getIp().startsWith("127.0.0")); + + naming.subscribe(serviceName, selector, listener); + + naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT); + + while (instances.isEmpty()) { + Thread.sleep(1000L); + } + + assertTrue(verifyInstanceList(instances, naming.getAllInstances(serviceName))); + + naming.unsubscribe(serviceName, selector, listener); + + instances = Collections.emptyList(); + naming.registerInstance(serviceName, "127.0.0.2", TEST_PORT); + + int i = 0; + while (instances.isEmpty()) { + Thread.sleep(1000L); + if (i++ > 10) { + return; + } + } + + fail(); + } + }