[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
This commit is contained in:
onewe 2022-07-07 11:36:47 +08:00 committed by GitHub
parent fcc9b0aef9
commit 3124f0ae9f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 584 additions and 321 deletions

View File

@ -46,6 +46,11 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

@ -28,7 +28,6 @@ import com.alibaba.nacos.naming.core.Instance;
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 @@ import java.util.List;
@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 class AddressServerClusterController {
List<Instance> 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);
}

View File

@ -21,7 +21,6 @@ import com.alibaba.nacos.api.common.Constants;
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 @@ import org.springframework.web.bind.annotation.RestController;
@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.

View File

@ -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";
@Autowired
private TestRestTemplate restTemplate;
private static final String GET_SERVERLIST_URL_FORMART = "http://127.0.0.1:8080/%s/%s";
//-----------------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<String, String> 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<String, String> 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);
}
@Test
public void deleteCluster() {
HashMap<String, String> 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);
}
@Test
public void deleteClusterWithSpecIp() {
HashMap<String, String> 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);
}
@Test
public void putCluster() {
final ResponseEntity<String> postClusterResponseEntity = restTemplate.exchange(
RequestEntity.post("/nacos/v1/as/nodes").body(params), String.class);
Assert.assertNotNull(postClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), postClusterResponseEntity.getStatusCodeValue());
TimeUnit.MILLISECONDS.sleep(500L);
final ResponseEntity<String> getClusterResponseEntity = restTemplate.exchange(
RequestEntity.get("/nacos/serverlist").build(), String.class);
Assert.assertNotNull(getClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), getClusterResponseEntity.getStatusCodeValue());
String ips = "127.0.0.114";
HashMap<String, String> 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);
}
//-----------------product=config,cluster=cluster01 -------------------//
@Test
public void deleteCluster() throws InterruptedException {
LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>(1);
params.add("ips", "127.0.0.104");
final ResponseEntity<String> postClusterResponseEntity = restTemplate.exchange(
RequestEntity.post("/nacos/v1/as/nodes").body(params), String.class);
Assert.assertNotNull(postClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), postClusterResponseEntity.getStatusCodeValue());
TimeUnit.MILLISECONDS.sleep(500L);
final ResponseEntity<String> 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());
}
@Test
public void postClusterWithProduct() {
public void postClusterWithProduct() throws InterruptedException {
LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>(2);
String ips = "127.0.0.101,127.0.0.102,127.0.0.103";
HashMap<String, String> 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<String, String> 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);
}
@Test
public void deleteClusterWithProduct() {
HashMap<String, String> 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);
}
@Test
public void deleteClusterWithProductAndIp() {
HashMap<String, String> 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);
}
@Test
public void putClusterWithProduct() {
params.add("ips", ips);
params.add("product", PRODUCT_CONFIG);
String ips = "127.0.0.196";
HashMap<String, String> 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);
final ResponseEntity<String> postClusterResponseEntity = restTemplate.exchange(
RequestEntity.post("/nacos/v1/as/nodes").body(params), String.class);
Assert.assertNotNull(postClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), postClusterResponseEntity.getStatusCodeValue());
TimeUnit.MILLISECONDS.sleep(500L);
final ResponseEntity<String> 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);
}
//-----------------product=naming,cluster=cluster01 -------------------//
@Test
public void deleteClusterWithProduct() throws InterruptedException {
LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>(1);
params.add("ips", "127.0.0.104");
params.add("product", PRODUCT_CONFIG);
final ResponseEntity<String> postClusterResponseEntity = restTemplate.exchange(
RequestEntity.post("/nacos/v1/as/nodes").body(params), String.class);
Assert.assertNotNull(postClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), postClusterResponseEntity.getStatusCodeValue());
TimeUnit.MILLISECONDS.sleep(500L);
final ResponseEntity<String> 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());
}
@Test
public void postClusterWithProductAndCluster() {
public void postClusterWithProductAndCluster() throws InterruptedException {
LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>(1);
String ips = "127.0.0.100,127.0.0.200,127.0.0.31";
HashMap<String, String> 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);
}
@Test
public void getClusterWithProductAndCluster() {
HashMap<String, String> 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);
}
@Test
public void deleteClusterWithProductAndCluster() {
HashMap<String, String> 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);
}
@Test
public void deleteClusterWithProductAndClusterAndIp() {
HashMap<String, String> 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);
}
@Test
public void putClusterWithProductAndCluster() {
String ips = "127.0.0.171";
HashMap<String, String> 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);
params.add("ips", ips);
params.add("product", PRODUCT_NAMING);
params.add("cluster", "cluster01");
final ResponseEntity<String> postClusterResponseEntity = restTemplate.exchange(
RequestEntity.post("/nacos/v1/as/nodes").body(params), String.class);
Assert.assertNotNull(postClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), postClusterResponseEntity.getStatusCodeValue());
TimeUnit.MILLISECONDS.sleep(500L);
final ResponseEntity<String> 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() throws InterruptedException {
LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>(1);
params.add("ips", "127.0.0.104");
params.add("product", PRODUCT_NAMING);
params.add("cluster", "cluster01");
final ResponseEntity<String> postClusterResponseEntity = restTemplate.exchange(
RequestEntity.post("/nacos/v1/as/nodes").body(params), String.class);
Assert.assertNotNull(postClusterResponseEntity);
Assert.assertEquals(HttpStatus.OK.value(), postClusterResponseEntity.getStatusCodeValue());
TimeUnit.MILLISECONDS.sleep(500L);
final ResponseEntity<String> 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());
}
@AfterClass
public static void teardown() {
System.clearProperty("nacos.standalone");
System.clearProperty("embeddedStorage");
}
}

View File

@ -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<String, String> 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<String, String> 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<String, String> 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<String, String> paramMap, String recvEncoding) {
return doRequest(reqUrl, paramMap, REQUEST_METHOD_DELETE, recvEncoding);
}
private static String doRequest(String reqUrl, Map<String, String> paramMap, String reqMethod,
String recvEncoding) {
return doExecute(reqUrl, paramMap, reqMethod, recvEncoding);
}
private static String doExecute(String reqUrl, Map<String, String> paramMap, String reqMethod,
String recvEncoding) {
HttpURLConnection urlCon = null;
String responseContent = null;
try {
StringBuilder params = new StringBuilder();
if (paramMap != null) {
for (Map.Entry<String, String> 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;
}
}

View File

@ -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<Instance> 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<Instance> 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<Instance> 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);
}
}

View File

@ -41,4 +41,23 @@ public class AddressServerManagerTests {
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]);
}
}

View File

@ -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());
}
}

View File

@ -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<String, Cluster> clusterMap = new HashMap<>(1);
clusterMap.put("serverList", cluster);
service.setClusterMap(clusterMap);
List<Instance> 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<String, Cluster> 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());
}
}