From 3124f0ae9fcfccac3bb8f7ad0878f0abf8a49d6e Mon Sep 17 00:00:00 2001 From: onewe Date: Thu, 7 Jul 2022 11:36:47 +0800 Subject: [PATCH] [Enhance] add some unit tests and some integration tests for address module (#8643) * [Enhance] add some unit tests and some integration tests for address module - add spring-boot-starter-test dependency - use constructor injection instead of field injection * add teardown method * default replace with nacos --- address/pom.xml | 5 + .../AddressServerClusterController.java | 20 +- .../controller/ServerListController.java | 13 +- .../address/AddressServerControllerTests.java | 263 ++++++++++-------- .../nacos/address/SimpleHttpTestUtils.java | 176 ------------ .../AddressServerGeneratorManagerTest.java | 110 ++++++++ .../component/AddressServerManagerTests.java | 19 ++ .../AddressServerClusterControllerTest.java | 163 +++++++++++ .../controller/ServerListControllerTest.java | 110 ++++++++ 9 files changed, 571 insertions(+), 308 deletions(-) delete mode 100644 address/src/test/java/com/alibaba/nacos/address/SimpleHttpTestUtils.java create mode 100644 address/src/test/java/com/alibaba/nacos/address/component/AddressServerGeneratorManagerTest.java create mode 100644 address/src/test/java/com/alibaba/nacos/address/controller/AddressServerClusterControllerTest.java create mode 100644 address/src/test/java/com/alibaba/nacos/address/controller/ServerListControllerTest.java diff --git a/address/pom.xml b/address/pom.xml index 004dca0a308..8b0185e5dd8 100644 --- a/address/pom.xml +++ b/address/pom.xml @@ -46,6 +46,11 @@ + + org.springframework.boot + spring-boot-starter-test + test + diff --git a/address/src/main/java/com/alibaba/nacos/address/controller/AddressServerClusterController.java b/address/src/main/java/com/alibaba/nacos/address/controller/AddressServerClusterController.java index fef68f10c56..6ec2425d43d 100644 --- a/address/src/main/java/com/alibaba/nacos/address/controller/AddressServerClusterController.java +++ b/address/src/main/java/com/alibaba/nacos/address/controller/AddressServerClusterController.java @@ -28,7 +28,6 @@ import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.core.ServiceManager; import com.alibaba.nacos.common.utils.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; @@ -48,14 +47,19 @@ @RequestMapping({AddressServerConstants.ADDRESS_SERVER_REQUEST_URL + "/nodes"}) public class AddressServerClusterController { - @Autowired - private ServiceManager serviceManager; + private final ServiceManager serviceManager; - @Autowired - private AddressServerManager addressServerManager; + private final AddressServerManager addressServerManager; + + private final AddressServerGeneratorManager addressServerGeneratorManager; + + public AddressServerClusterController(ServiceManager serviceManager, AddressServerManager addressServerManager, + AddressServerGeneratorManager addressServerGeneratorManager) { + this.serviceManager = serviceManager; + this.addressServerManager = addressServerManager; + this.addressServerGeneratorManager = addressServerGeneratorManager; + } - @Autowired - private AddressServerGeneratorManager addressServerGeneratorManager; /** * Create new cluster. @@ -146,7 +150,7 @@ public ResponseEntity deleteCluster(@RequestParam(required = false) Stri List instanceList = addressServerGeneratorManager .generateInstancesByIps(serviceName, rawProductName, clusterName, ipArray); serviceManager.removeInstance(Constants.DEFAULT_NAMESPACE_ID, serviceName, false, - instanceList.toArray(new Instance[instanceList.size()])); + instanceList.toArray(new Instance[0])); } else { responseEntity = ResponseEntity.status(HttpStatus.BAD_REQUEST).body(checkResult); } diff --git a/address/src/main/java/com/alibaba/nacos/address/controller/ServerListController.java b/address/src/main/java/com/alibaba/nacos/address/controller/ServerListController.java index c310ecb9c9c..0fc03b0fd1a 100644 --- a/address/src/main/java/com/alibaba/nacos/address/controller/ServerListController.java +++ b/address/src/main/java/com/alibaba/nacos/address/controller/ServerListController.java @@ -21,7 +21,6 @@ import com.alibaba.nacos.naming.core.Cluster; import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.core.ServiceManager; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; @@ -38,11 +37,15 @@ @RestController public class ServerListController { - @Autowired - private ServiceManager serviceManager; + private final ServiceManager serviceManager; - @Autowired - private AddressServerGeneratorManager addressServerBuilderManager; + private final AddressServerGeneratorManager addressServerBuilderManager; + + public ServerListController(ServiceManager serviceManager, + AddressServerGeneratorManager addressServerBuilderManager) { + this.serviceManager = serviceManager; + this.addressServerBuilderManager = addressServerBuilderManager; + } /** * Get cluster. diff --git a/address/src/test/java/com/alibaba/nacos/address/AddressServerControllerTests.java b/address/src/test/java/com/alibaba/nacos/address/AddressServerControllerTests.java index 03ae0c9a556..f3ceff70e69 100644 --- a/address/src/test/java/com/alibaba/nacos/address/AddressServerControllerTests.java +++ b/address/src/test/java/com/alibaba/nacos/address/AddressServerControllerTests.java @@ -16,167 +16,192 @@ package com.alibaba.nacos.address; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; +import org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration; +import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.RequestEntity; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.util.LinkedMultiValueMap; -import java.util.HashMap; +import java.util.concurrent.TimeUnit; +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +@ImportAutoConfiguration(exclude = {SecurityAutoConfiguration.class, SecurityFilterAutoConfiguration.class, + ManagementWebSecurityAutoConfiguration.class, UserDetailsServiceAutoConfiguration.class}) public class AddressServerControllerTests { - private static final String PRODUCT_NACOS = "nacos"; - private static final String PRODUCT_CONFIG = "config"; private static final String PRODUCT_NAMING = "naming"; - private static final String DEFAULT_URL_CLUSTER = "serverlist"; - - private static final String GET_SERVERLIST_URL_FORMART = "http://127.0.0.1:8080/%s/%s"; + @Autowired + private TestRestTemplate restTemplate; - //-----------------product=nacos,cluster=DEFAULT -------------------// + @BeforeClass + public static void before() { + System.setProperty("nacos.standalone", "true"); + System.setProperty("embeddedStorage", "true"); + } @Test - public void postCluster() { + public void postCluster() throws InterruptedException { String ips = "127.0.0.100,127.0.0.102,127.0.0.104"; - HashMap params = new HashMap<>(); - params.put("ips", ips); - String response = SimpleHttpTestUtils.doPost("http://127.0.0.1:8080/nacos/v1/as/nodes", params, "UTF-8"); - System.err.println(response); - } - - @Test - public void getCluster() { + LinkedMultiValueMap params = new LinkedMultiValueMap<>(1); + params.add("ips", ips); - String getUrl = String.format(GET_SERVERLIST_URL_FORMART, PRODUCT_NACOS, DEFAULT_URL_CLUSTER); - String response = SimpleHttpTestUtils.doGet(getUrl, new HashMap<>(), "UTF-8"); - System.err.println(response); - } + final ResponseEntity postClusterResponseEntity = restTemplate.exchange( + RequestEntity.post("/nacos/v1/as/nodes").body(params), String.class); + + Assert.assertNotNull(postClusterResponseEntity); + Assert.assertEquals(HttpStatus.OK.value(), postClusterResponseEntity.getStatusCodeValue()); - @Test - public void deleteCluster() { - HashMap deleteIp = new HashMap<>(); - deleteIp.put("ips", "127.0.0.104"); - String response = SimpleHttpTestUtils.doDelete("http://127.0.0.1:8080/nacos/v1/as/nodes", deleteIp, "UTF-8"); - System.err.println(response); + TimeUnit.MILLISECONDS.sleep(500L); + + final ResponseEntity getClusterResponseEntity = restTemplate.exchange( + RequestEntity.get("/nacos/serverlist").build(), String.class); + + Assert.assertNotNull(getClusterResponseEntity); + Assert.assertEquals(HttpStatus.OK.value(), getClusterResponseEntity.getStatusCodeValue()); + } @Test - public void deleteClusterWithSpecIp() { - HashMap params = new HashMap<>(); - params.put("ips", "127.0.0.103"); - String response = SimpleHttpTestUtils.doDelete("http://127.0.0.1:8080/nacos/v1/as/nodes", params, "UTF-8"); - System.err.println(response); - } + public void deleteCluster() throws InterruptedException { + + LinkedMultiValueMap params = new LinkedMultiValueMap<>(1); + params.add("ips", "127.0.0.104"); + + final ResponseEntity postClusterResponseEntity = restTemplate.exchange( + RequestEntity.post("/nacos/v1/as/nodes").body(params), String.class); + + Assert.assertNotNull(postClusterResponseEntity); + Assert.assertEquals(HttpStatus.OK.value(), postClusterResponseEntity.getStatusCodeValue()); - @Test - public void putCluster() { + TimeUnit.MILLISECONDS.sleep(500L); - String ips = "127.0.0.114"; - HashMap params = new HashMap<>(); - params.put("ips", ips); - String response = SimpleHttpTestUtils.doPut("http://127.0.0.1:8080/nacos/v1/as/nodes", params, "UTF-8"); - System.err.println(response); + final ResponseEntity deleteClusterResponseEntity = restTemplate.exchange( + RequestEntity.delete("/nacos/v1/as/nodes?ips={ips}", "127.0.0.104").build(), String.class); + + Assert.assertNotNull(deleteClusterResponseEntity); + Assert.assertEquals(HttpStatus.OK.value(), deleteClusterResponseEntity.getStatusCodeValue()); } - //-----------------product=config,cluster=cluster01 -------------------// - @Test - public void postClusterWithProduct() { + public void postClusterWithProduct() throws InterruptedException { + + LinkedMultiValueMap params = new LinkedMultiValueMap<>(2); String ips = "127.0.0.101,127.0.0.102,127.0.0.103"; - HashMap params = new HashMap<>(); - params.put("ips", ips); - params.put("product", PRODUCT_CONFIG); - String response = SimpleHttpTestUtils.doPost("http://127.0.0.1:8080/nacos/v1/as/nodes", params, "UTF-8"); - System.err.println(response); - } - - @Test - public void getClusterWithProduct() { - HashMap params = new HashMap<>(); - String getUrl = String.format(GET_SERVERLIST_URL_FORMART, PRODUCT_CONFIG, DEFAULT_URL_CLUSTER); - String response = SimpleHttpTestUtils.doGet(getUrl, params, "UTF-8"); - System.err.println(response); - } + params.add("ips", ips); + params.add("product", PRODUCT_CONFIG); + + final ResponseEntity postClusterResponseEntity = restTemplate.exchange( + RequestEntity.post("/nacos/v1/as/nodes").body(params), String.class); + Assert.assertNotNull(postClusterResponseEntity); + Assert.assertEquals(HttpStatus.OK.value(), postClusterResponseEntity.getStatusCodeValue()); - @Test - public void deleteClusterWithProduct() { - HashMap params = new HashMap<>(); - params.put("product", PRODUCT_CONFIG); - String response = SimpleHttpTestUtils.doDelete("http://127.0.0.1:8080/nacos/v1/as/nodes", params, "UTF-8"); - System.err.println(response); + TimeUnit.MILLISECONDS.sleep(500L); + + final ResponseEntity getClusterResponseEntity = restTemplate.exchange( + RequestEntity.get("/{product}/serverlist", PRODUCT_CONFIG).build(), String.class); + + Assert.assertNotNull(getClusterResponseEntity); + Assert.assertEquals(HttpStatus.OK.value(), getClusterResponseEntity.getStatusCodeValue()); + + final String body = getClusterResponseEntity.getBody(); + Assert.assertNotNull(body); } @Test - public void deleteClusterWithProductAndIp() { - HashMap params = new HashMap<>(); - params.put("product", PRODUCT_CONFIG); - params.put("ips", "127.0.0.196"); - String response = SimpleHttpTestUtils.doDelete("http://127.0.0.1:8080/nacos/v1/as/nodes", params, "UTF-8"); - System.err.println(response); - } + public void deleteClusterWithProduct() throws InterruptedException { + + LinkedMultiValueMap params = new LinkedMultiValueMap<>(1); + params.add("ips", "127.0.0.104"); + params.add("product", PRODUCT_CONFIG); + + final ResponseEntity postClusterResponseEntity = restTemplate.exchange( + RequestEntity.post("/nacos/v1/as/nodes").body(params), String.class); + Assert.assertNotNull(postClusterResponseEntity); + Assert.assertEquals(HttpStatus.OK.value(), postClusterResponseEntity.getStatusCodeValue()); - @Test - public void putClusterWithProduct() { - - String ips = "127.0.0.196"; - HashMap params = new HashMap<>(); - params.put("ips", ips); - params.put("product", PRODUCT_CONFIG); - String response = SimpleHttpTestUtils.doPut("http://127.0.0.1:8080/nacos/v1/as/nodes", params, "UTF-8"); - System.err.println(response); + TimeUnit.MILLISECONDS.sleep(500L); + + final ResponseEntity deleteClusterResponseEntity = restTemplate.exchange( + RequestEntity.delete("/nacos/v1/as/nodes?product={product}&ips={ips}", PRODUCT_CONFIG, "127.0.0.104") + .build(), String.class); + + Assert.assertNotNull(deleteClusterResponseEntity); + Assert.assertEquals(HttpStatus.OK.value(), deleteClusterResponseEntity.getStatusCodeValue()); } - //-----------------product=naming,cluster=cluster01 -------------------// - @Test - public void postClusterWithProductAndCluster() { + public void postClusterWithProductAndCluster() throws InterruptedException { + LinkedMultiValueMap params = new LinkedMultiValueMap<>(1); String ips = "127.0.0.100,127.0.0.200,127.0.0.31"; - HashMap params = new HashMap<>(); - params.put("ips", ips); - params.put("product", PRODUCT_NAMING); - params.put("cluster", "cluster01"); - String response = SimpleHttpTestUtils.doPost("http://127.0.0.1:8080/nacos/v1/as/nodes", params, "UTF-8"); - System.err.println(response); - } + + params.add("ips", ips); + params.add("product", PRODUCT_NAMING); + params.add("cluster", "cluster01"); + + final ResponseEntity postClusterResponseEntity = restTemplate.exchange( + RequestEntity.post("/nacos/v1/as/nodes").body(params), String.class); + Assert.assertNotNull(postClusterResponseEntity); + Assert.assertEquals(HttpStatus.OK.value(), postClusterResponseEntity.getStatusCodeValue()); - @Test - public void getClusterWithProductAndCluster() { - HashMap params = new HashMap<>(); - String getUrl = String.format(GET_SERVERLIST_URL_FORMART, PRODUCT_NAMING, "cluster01"); - String response = SimpleHttpTestUtils.doGet(getUrl, params, "UTF-8"); - System.err.println(response); + TimeUnit.MILLISECONDS.sleep(500L); + + final ResponseEntity getClusterResponseEntity = restTemplate.exchange( + RequestEntity.get("/{product}/{cluster}", PRODUCT_NAMING, "cluster01").build(), String.class); + + Assert.assertNotNull(getClusterResponseEntity); + Assert.assertEquals(HttpStatus.OK.value(), getClusterResponseEntity.getStatusCodeValue()); + + final String body = getClusterResponseEntity.getBody(); + Assert.assertNotNull(body); } @Test - public void deleteClusterWithProductAndCluster() { - HashMap params = new HashMap<>(); - params.put("product", PRODUCT_NAMING); - params.put("cluster", "cluster01"); - String response = SimpleHttpTestUtils.doDelete("http://127.0.0.1:8080/nacos/v1/as/nodes", params, "UTF-8"); - System.err.println(response); - } + public void deleteClusterWithProductAndCluster() throws InterruptedException { + + LinkedMultiValueMap params = new LinkedMultiValueMap<>(1); + params.add("ips", "127.0.0.104"); + params.add("product", PRODUCT_NAMING); + params.add("cluster", "cluster01"); + + final ResponseEntity postClusterResponseEntity = restTemplate.exchange( + RequestEntity.post("/nacos/v1/as/nodes").body(params), String.class); + Assert.assertNotNull(postClusterResponseEntity); + Assert.assertEquals(HttpStatus.OK.value(), postClusterResponseEntity.getStatusCodeValue()); - @Test - public void deleteClusterWithProductAndClusterAndIp() { - HashMap params = new HashMap<>(); - params.put("product", PRODUCT_NAMING); - params.put("cluster", "cluster01"); - params.put("ips", "127.0.0.200"); - String response = SimpleHttpTestUtils.doDelete("http://127.0.0.1:8080/nacos/v1/as/nodes", params, "UTF-8"); - System.err.println(response); + TimeUnit.MILLISECONDS.sleep(500L); + + final ResponseEntity deleteClusterResponseEntity = restTemplate.exchange( + RequestEntity.delete("/nacos/v1/as/nodes?product={product}&cluster={cluster}&ips={ips}", PRODUCT_NAMING, + "cluster01", "127.0.0.104").build(), String.class); + + Assert.assertNotNull(deleteClusterResponseEntity); + Assert.assertEquals(HttpStatus.OK.value(), deleteClusterResponseEntity.getStatusCodeValue()); } - @Test - public void putClusterWithProductAndCluster() { - - String ips = "127.0.0.171"; - HashMap params = new HashMap<>(); - params.put("ips", ips); - params.put("product", PRODUCT_NAMING); - params.put("cluster", "cluster01"); - String response = SimpleHttpTestUtils.doPut("http://127.0.0.1:8080/nacos/v1/as/nodes", params, "UTF-8"); - System.err.println(response); + @AfterClass + public static void teardown() { + System.clearProperty("nacos.standalone"); + System.clearProperty("embeddedStorage"); } + } diff --git a/address/src/test/java/com/alibaba/nacos/address/SimpleHttpTestUtils.java b/address/src/test/java/com/alibaba/nacos/address/SimpleHttpTestUtils.java deleted file mode 100644 index 2a00c59c415..00000000000 --- a/address/src/test/java/com/alibaba/nacos/address/SimpleHttpTestUtils.java +++ /dev/null @@ -1,176 +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.address; - -import com.alibaba.nacos.common.utils.IoUtils; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLEncoder; -import java.util.Map; - -public class SimpleHttpTestUtils { - - private static final String REQUEST_METHOD_DELETE = "DELETE"; - - private static final String REQUEST_METHOD_PUT = "PUT"; - - private static final String REQUEST_METHOD_POST = "POST"; - - private static final String REQUEST_METHOD_GET = "GET"; - - /** - * 连接超时. - */ - private static final int CONNECT_TIME_OUT = 2000; - - /** - * 读取数据超时. - */ - private static final int READ_TIME_OUT = 2000; - - /** - * 请求编码. - */ - public static final String REQUEST_ENCODING = "UTF-8"; - - /** - * 接收编码. - */ - public static final String RESPONSE_ENCODING = "UTF-8"; - - public static final short OK = 200; - - public static final short BAD_REQUEST = 400; - - public static final short INTERNAL_SERVER_ERROR = 500; - - public static final short PARAM_ERROR_NO_ANALYSESOR = 1000; - - /** - * 发送带参数的GET的HTTP请求. - * - * @param reqUrl HTTP请求URL - * @param paramMap 参数映射表 - * @return HTTP响应的字符串 - */ - public static String doGet(String reqUrl, Map paramMap, String recvEncoding) { - return doRequest(reqUrl, paramMap, REQUEST_METHOD_GET, recvEncoding); - } - - /** - * 发送带参数的POST的HTTP请求. - * - * @param reqUrl HTTP请求URL - * @param paramMap 参数映射表 - * @return HTTP响应的字符串 - */ - public static String doPost(String reqUrl, Map paramMap, String recvEncoding) { - return doRequest(reqUrl, paramMap, REQUEST_METHOD_POST, recvEncoding); - } - - /** - * 发送带参数的 PUT 的 HTTP 请求. - * - * @param reqUrl HTTP请求URL - * @param paramMap 参数映射表 - * @return HTTP响应的字符串 - */ - public static String doPut(String reqUrl, Map paramMap, String recvEncoding) { - return doRequest(reqUrl, paramMap, REQUEST_METHOD_PUT, recvEncoding); - } - - /** - * 发送带参数的 DELETE 的 HTTP 请求. - * - * @param reqUrl HTTP请求URL - * @param paramMap 参数映射表 - * @return HTTP响应的字符串 - */ - public static String doDelete(String reqUrl, Map paramMap, String recvEncoding) { - return doRequest(reqUrl, paramMap, REQUEST_METHOD_DELETE, recvEncoding); - } - - private static String doRequest(String reqUrl, Map paramMap, String reqMethod, - String recvEncoding) { - - return doExecute(reqUrl, paramMap, reqMethod, recvEncoding); - } - - private static String doExecute(String reqUrl, Map paramMap, String reqMethod, - String recvEncoding) { - HttpURLConnection urlCon = null; - String responseContent = null; - try { - StringBuilder params = new StringBuilder(); - if (paramMap != null) { - for (Map.Entry element : paramMap.entrySet()) { - params.append(element.getKey()); - params.append('='); - params.append(URLEncoder.encode(element.getValue(), REQUEST_ENCODING)); - params.append('&'); - } - - if (params.length() > 0) { - params = params.deleteCharAt(params.length() - 1); - } - - if (params.length() > 0 && (REQUEST_METHOD_GET.equals(reqMethod) || REQUEST_METHOD_DELETE - .equals(reqMethod))) { - reqUrl = reqUrl + "?" + params.toString(); - } - } - URL url = new URL(reqUrl); - urlCon = (HttpURLConnection) url.openConnection(); - urlCon.setRequestMethod(reqMethod); - urlCon.setConnectTimeout(CONNECT_TIME_OUT); - urlCon.setReadTimeout(READ_TIME_OUT); - urlCon.setDoOutput(true); - if (REQUEST_METHOD_POST.equals(reqMethod) || REQUEST_METHOD_PUT.equals(reqMethod)) { - byte[] b = params.toString().getBytes(); - urlCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); - urlCon.setRequestProperty("Content-Length", String.valueOf(b.length)); - urlCon.getOutputStream().write(b, 0, b.length); - urlCon.getOutputStream().flush(); - urlCon.getOutputStream().close(); - } - InputStream in = urlCon.getInputStream(); - BufferedReader rd = new BufferedReader(new InputStreamReader(in, recvEncoding)); - String tempLine = rd.readLine(); - StringBuffer tempStr = new StringBuffer(); - while (tempLine != null) { - tempStr.append(tempLine); - tempLine = rd.readLine(); - } - responseContent = tempStr.toString(); - rd.close(); - in.close(); - - urlCon.getResponseMessage(); - } catch (IOException e) { - e.printStackTrace(); - } finally { - IoUtils.closeQuietly(urlCon); - } - return responseContent; - } - -} 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 new file mode 100644 index 00000000000..0f42249bf54 --- /dev/null +++ b/address/src/test/java/com/alibaba/nacos/address/component/AddressServerGeneratorManagerTest.java @@ -0,0 +1,110 @@ +/* + * 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.address.component; + +import com.alibaba.nacos.address.constant.AddressServerConstants; +import com.alibaba.nacos.naming.core.Instance; +import org.junit.Assert; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +public class AddressServerGeneratorManagerTest { + + @Test + public void testGenerateProductName() { + AddressServerGeneratorManager manager = new AddressServerGeneratorManager(); + final String blankName = manager.generateProductName(""); + Assert.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); + + final String testName = manager.generateProductName("test"); + Assert.assertEquals("nacos.as.test", testName); + + } + + @Test + public void testGenerateInstancesByIps() { + AddressServerGeneratorManager manager = new AddressServerGeneratorManager(); + final List empty = manager.generateInstancesByIps(null, null, null, null); + Assert.assertNotNull(empty); + Assert.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()); + + final Instance instance1 = instanceList.get(0); + Assert.assertEquals("192.168.3.1", instance1.getIp()); + + final Instance instance2 = instanceList.get(1); + Assert.assertEquals("192.168.3.2", instance2.getIp()); + + final Instance instance3 = instanceList.get(2); + Assert.assertEquals("192.168.3.3", instance3.getIp()); + + } + + @Test + public void testGenerateResponseIps() { + final List instanceList = new ArrayList<>(); + Instance instance1 = new Instance(); + instance1.setIp("192.168.3.1"); + instance1.setPort(8848); + + Instance instance2 = new Instance(); + instance2.setIp("192.168.3.2"); + instance2.setPort(8848); + + Instance instance3 = new Instance(); + instance3.setIp("192.168.3.3"); + instance3.setPort(8848); + + instanceList.add(instance1); + instanceList.add(instance2); + instanceList.add(instance3); + + AddressServerGeneratorManager manager = new AddressServerGeneratorManager(); + final String ipListStr = manager.generateResponseIps(instanceList); + + StringBuilder expectStr = new StringBuilder(); + final StringBuilder ret = expectStr + .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); + + } + + @Test + public void testGenerateNacosServiceName() { + AddressServerGeneratorManager manager = new AddressServerGeneratorManager(); + + final String containDefault = manager.generateNacosServiceName("DEFAULT_GROUP@@test"); + Assert.assertEquals("DEFAULT_GROUP@@test", containDefault); + + final String product = manager.generateNacosServiceName("product"); + Assert.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 4141af90f78..25c6441dbb2 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 @@ -41,4 +41,23 @@ public void getDefaultClusterNameIfEmpty() { assertEquals("otherServerList", ADDRESS_SERVER_MANAGER.getDefaultClusterNameIfEmpty("otherServerList")); } + @Test + public void testGetRawClusterName() { + assertEquals("serverList", ADDRESS_SERVER_MANAGER.getRawClusterName("serverList")); + assertEquals(AddressServerConstants.DEFAULT_GET_CLUSTER, ADDRESS_SERVER_MANAGER.getRawClusterName("")); + } + + @Test + public 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"); + assertEquals(1, one.length); + assertEquals("192.168.1.12:8848", one[0]); + final String[] two = ADDRESS_SERVER_MANAGER.splitIps("192.168.1.12:8848,192.268.3.33:8848"); + assertEquals(2, two.length); + assertEquals("192.168.1.12:8848", two[0]); + assertEquals("192.268.3.33:8848", two[1]); + } + } 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 new file mode 100644 index 00000000000..366ef5008eb --- /dev/null +++ b/address/src/test/java/com/alibaba/nacos/address/controller/AddressServerClusterControllerTest.java @@ -0,0 +1,163 @@ +/* + * 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.address.controller; + +import com.alibaba.nacos.address.component.AddressServerGeneratorManager; +import com.alibaba.nacos.address.component.AddressServerManager; +import com.alibaba.nacos.address.constant.AddressServerConstants; +import com.alibaba.nacos.api.common.Constants; +import com.alibaba.nacos.api.exception.NacosException; +import com.alibaba.nacos.naming.core.Service; +import com.alibaba.nacos.naming.core.ServiceManager; +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.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +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 { + + @Mock + private ServiceManager serviceManager; + + private MockMvc mockMvc; + + @Before + public void before() { + mockMvc = MockMvcBuilders.standaloneSetup(new AddressServerClusterController(serviceManager, new AddressServerManager(), + new AddressServerGeneratorManager())).build(); + } + + @Test + public 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 { + 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 { + + Mockito.doThrow(new NacosException(500, "create service error")).when(serviceManager) + .createServiceIfAbsent(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID), Mockito.eq( + Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"), + Mockito.eq(false), Mockito.any()); + + mockMvc.perform(post("/nacos/v1/as/nodes") + .param("product", "default") + .param("cluster", "serverList") + .param("ips", "192.168.1")) + .andExpect(status().isInternalServerError()); + + } + + @Test + public void testDeleteCluster() throws Exception { + + Mockito.when(serviceManager.getService(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID), + Mockito.eq(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"))) + .thenReturn(new Service(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default")); + + 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 { + + 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 { + + Mockito.when(serviceManager.getService(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID), + Mockito.eq(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"))) + .thenReturn(new Service(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default")); + + mockMvc.perform(delete("/nacos/v1/as/nodes") + .param("product", "default") + .param("cluster", "serverList") + .param("ips", "") + ).andExpect(status().isBadRequest()); + } + + @Test + public void testDeleteClusterErrorIps() throws Exception { + + Mockito.when(serviceManager.getService(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID), + Mockito.eq(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"))) + .thenReturn(new Service(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default")); + + 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 { + + Mockito.when(serviceManager.getService(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID), + Mockito.eq(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"))) + .thenReturn(new Service(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default")); + + Mockito.doThrow(new NacosException(500, "remove service error")) + .when(serviceManager) + .removeInstance(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID), + Mockito.eq(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"), + Mockito.eq(false), + Mockito.any()); + + 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().isInternalServerError()); + } + +} 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 new file mode 100644 index 00000000000..43fbaa9fddf --- /dev/null +++ b/address/src/test/java/com/alibaba/nacos/address/controller/ServerListControllerTest.java @@ -0,0 +1,110 @@ +/* + * 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.address.controller; + +import com.alibaba.nacos.address.component.AddressServerGeneratorManager; +import com.alibaba.nacos.address.constant.AddressServerConstants; +import com.alibaba.nacos.api.common.Constants; +import com.alibaba.nacos.naming.core.Cluster; +import com.alibaba.nacos.naming.core.Instance; +import com.alibaba.nacos.naming.core.Service; +import com.alibaba.nacos.naming.core.ServiceManager; +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.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +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 { + + @Mock + private ServiceManager serviceManager; + + private MockMvc mockMvc; + + @Before + public void before() { + this.mockMvc = MockMvcBuilders + .standaloneSetup(new ServerListController(serviceManager, new AddressServerGeneratorManager())) + .build(); + } + + @Test + public void testGetCluster() throws Exception { + + final Service service = new Service( + Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"); + + Cluster cluster = new Cluster(); + cluster.setName("serverList"); + cluster.setService(service); + + final HashMap clusterMap = new HashMap<>(1); + clusterMap.put("serverList", cluster); + service.setClusterMap(clusterMap); + + List list = new ArrayList<>(2); + list.add(new Instance("192.168.3.1", 8848)); + list.add(new Instance("192.168.3.2", 8848)); + cluster.updateIps(list, false); + + Mockito.when(serviceManager.getService(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID), + Mockito.eq(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"))) + .thenReturn(service); + + mockMvc.perform(get("/nacos/serverList")) + .andExpect(status().isOk()); + + } + + @Test + public void testGetClusterCannotFindService() throws Exception { + + mockMvc.perform(get("/default/serverList")) + .andExpect(status().isNotFound()); + + } + + @Test + public void testGetClusterCannotFindCluster() throws Exception { + + final Service service = new Service( + Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"); + + final HashMap clusterMap = new HashMap<>(1); + service.setClusterMap(clusterMap); + + Mockito.when(serviceManager.getService(Mockito.eq(Constants.DEFAULT_NAMESPACE_ID), + Mockito.eq(Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + "nacos.as.default"))) + .thenReturn(service); + + mockMvc.perform(get("/nacos/serverList")) + .andExpect(status().isNotFound()); + + } +}