From 523f039c95edf96da0dc0acd0a21de5f95759c8c Mon Sep 17 00:00:00 2001 From: flystar32 <flystar32@163.com> Date: Tue, 22 Jan 2019 11:50:38 +0800 Subject: [PATCH] add test case for ans module --- spring-cloud-alicloud-ans/pom.xml | 12 ++ .../alicloud/ans/AnsAutoConfiguration.java | 3 + .../ans/registry/AnsRegistration.java | 6 +- .../alicloud/ans/AnsDiscoveryClientTests.java | 116 +++++++++++++ ...ceRegistrationIpNetworkInterfaceTests.java | 147 ++++++++++++++++ .../AnsAutoServiceRegistrationIpTests.java | 81 +++++++++ ...erviceRegistrationManagementPortTests.java | 87 ++++++++++ .../AnsAutoServiceRegistrationPortTests.java | 81 +++++++++ .../AnsAutoServiceRegistrationTests.java | 158 ++++++++++++++++++ .../AnsRibbonClientConfigurationTests.java | 86 ++++++++++ .../ans/ribbon/AnsServerListTests.java | 148 ++++++++++++++++ .../ans/ribbon/AnsServiceListTests.java | 76 +++++++++ .../cloud/alicloud/ans/test/AnsMockTest.java | 45 +++++ 13 files changed, 1043 insertions(+), 3 deletions(-) create mode 100644 spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/AnsDiscoveryClientTests.java create mode 100644 spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationIpNetworkInterfaceTests.java create mode 100644 spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationIpTests.java create mode 100644 spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationManagementPortTests.java create mode 100644 spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationPortTests.java create mode 100644 spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationTests.java create mode 100644 spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/ribbon/AnsRibbonClientConfigurationTests.java create mode 100644 spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServerListTests.java create mode 100644 spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServiceListTests.java create mode 100644 spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/test/AnsMockTest.java diff --git a/spring-cloud-alicloud-ans/pom.xml b/spring-cloud-alicloud-ans/pom.xml index d1fdf2c93..3aa33c0b8 100644 --- a/spring-cloud-alicloud-ans/pom.xml +++ b/spring-cloud-alicloud-ans/pom.xml @@ -103,6 +103,18 @@ <artifactId>spring-cloud-test-support</artifactId> <scope>test</scope> </dependency> + <dependency> + <groupId>org.powermock</groupId> + <artifactId>powermock-module-junit4</artifactId> + <version>2.0.0</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.powermock</groupId> + <artifactId>powermock-api-mockito2</artifactId> + <version>2.0.0</version> + <scope>test</scope> + </dependency> </dependencies> diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsAutoConfiguration.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsAutoConfiguration.java index d563632ea..8d0f0fe64 100644 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsAutoConfiguration.java +++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/AnsAutoConfiguration.java @@ -16,6 +16,7 @@ package org.springframework.cloud.alicloud.ans; +import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; @@ -27,6 +28,7 @@ import org.springframework.cloud.alicloud.ans.registry.AnsRegistration; import org.springframework.cloud.alicloud.ans.registry.AnsServiceRegistry; import org.springframework.cloud.alicloud.context.ans.AnsProperties; import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration; +import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; @@ -44,6 +46,7 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnAnsEnabled @AutoConfigureBefore({ AutoServiceRegistrationAutoConfiguration.class, AnsDiscoveryClientAutoConfiguration.class }) +@AutoConfigureAfter(AutoServiceRegistrationConfiguration.class) public class AnsAutoConfiguration { @Bean diff --git a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsRegistration.java b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsRegistration.java index 39a98b736..79be8e853 100644 --- a/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsRegistration.java +++ b/spring-cloud-alicloud-ans/src/main/java/org/springframework/cloud/alicloud/ans/registry/AnsRegistration.java @@ -35,9 +35,9 @@ import org.springframework.util.StringUtils; */ public class AnsRegistration implements Registration, ServiceInstance { - private static final String MANAGEMENT_PORT = "management.port"; - private static final String MANAGEMENT_CONTEXT_PATH = "management.context-path"; - private static final String MANAGEMENT_ADDRESS = "management.address"; + static final String MANAGEMENT_PORT = "management.port"; + static final String MANAGEMENT_CONTEXT_PATH = "management.context-path"; + static final String MANAGEMENT_ADDRESS = "management.address"; private AnsProperties ansProperties; private ApplicationContext context; diff --git a/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/AnsDiscoveryClientTests.java b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/AnsDiscoveryClientTests.java new file mode 100644 index 000000000..3e02bc3dc --- /dev/null +++ b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/AnsDiscoveryClientTests.java @@ -0,0 +1,116 @@ +/* + * Copyright (C) 2018 the original author or authors. + * + * 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 org.springframework.cloud.alicloud.ans; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; +import static org.springframework.cloud.alicloud.ans.test.AnsMockTest.hostInstance; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.cloud.client.ServiceInstance; + +import com.alibaba.ans.core.NamingService; +import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host; + +/** + * @author xiaojing + */ +@RunWith(PowerMockRunner.class) +@PrepareForTest(NamingService.class) +public class AnsDiscoveryClientTests { + + private String host = "123.123.123.123"; + private int port = 8888; + private String serviceName = "test-service"; + + @Test + public void testGetServers() throws Exception { + + ArrayList<Host> hosts = new ArrayList<>(); + + HashMap<String, String> map = new HashMap<>(); + map.put("test-key", "test-value"); + map.put("secure", "true"); + + hosts.add(hostInstance(serviceName, false, host, port, map)); + + PowerMockito.mockStatic(NamingService.class); + when(NamingService.getHosts(eq(serviceName))).thenReturn(hosts); + + AnsDiscoveryClient discoveryClient = new AnsDiscoveryClient(); + + List<ServiceInstance> serviceInstances = discoveryClient + .getInstances(serviceName); + + assertThat(serviceInstances.size()).isEqualTo(1); + + ServiceInstance serviceInstance = serviceInstances.get(0); + + assertThat(serviceInstance.getServiceId()).isEqualTo(serviceName); + assertThat(serviceInstance.getHost()).isEqualTo(host); + assertThat(serviceInstance.getPort()).isEqualTo(port); + // assertThat(serviceInstance.isSecure()).isEqualTo(true); + // ans doesn't support metadata + assertThat(serviceInstance.getUri().toString()) + .isEqualTo(getUri(serviceInstance)); + // assertThat(serviceInstance.getMetadata().get("test-key")).isEqualTo("test-value"); + // ans doesn't support metadata + + } + + @Test + public void testGetAllService() throws Exception { + + Set<String> subscribedServices = new HashSet<>(); + + subscribedServices.add(serviceName + "1"); + subscribedServices.add(serviceName + "2"); + subscribedServices.add(serviceName + "3"); + + PowerMockito.mockStatic(NamingService.class); + when(NamingService.getDomsSubscribed()).thenReturn(subscribedServices); + + AnsDiscoveryClient discoveryClient = new AnsDiscoveryClient(); + List<String> services = discoveryClient.getServices(); + + assertThat(services.size()).isEqualTo(3); + assertThat(services.contains(serviceName + "1")); + assertThat(services.contains(serviceName + "2")); + assertThat(services.contains(serviceName + "3")); + + } + + private String getUri(ServiceInstance instance) { + + if (instance.isSecure()) { + return "https://" + host + ":" + port; + } + + return "http://" + host + ":" + port; + } +} diff --git a/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationIpNetworkInterfaceTests.java b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationIpNetworkInterfaceTests.java new file mode 100644 index 000000000..0259c27b9 --- /dev/null +++ b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationIpNetworkInterfaceTests.java @@ -0,0 +1,147 @@ +/* + * Copyright (C) 2018 the original author or authors. + * + * 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 org.springframework.cloud.alicloud.ans.registry; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertEquals; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.util.Enumeration; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.alicloud.ans.AnsAutoConfiguration; +import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration; +import org.springframework.cloud.alicloud.context.ans.AnsProperties; +import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; +import org.springframework.cloud.commons.util.InetUtils; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * @author xiaojing + */ + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AnsAutoServiceRegistrationIpNetworkInterfaceTests.TestConfig.class, properties = { + "spring.application.name=myTestService1", + "spring.cloud.alicloud.ans.server-list=127.0.0.1", + "spring.cloud.alicloud.ans.server-port=8080" }, webEnvironment = RANDOM_PORT) +public class AnsAutoServiceRegistrationIpNetworkInterfaceTests { + + @Autowired + private AnsRegistration registration; + + @Autowired + private AnsAutoServiceRegistration ansAutoServiceRegistration; + + @Autowired + private AnsProperties properties; + + @Autowired + private InetUtils inetUtils; + + @Test + public void contextLoads() throws Exception { + + assertNotNull("AnsRegistration was not created", registration); + assertNotNull("AnsProperties was not created", properties); + assertNotNull("AnsAutoServiceRegistration was not created", + ansAutoServiceRegistration); + + checkoutAnsDiscoveryServiceIP(); + + } + + private void checkoutAnsDiscoveryServiceIP() { + assertEquals("AnsProperties service IP was wrong", + getIPFromNetworkInterface(TestConfig.netWorkInterfaceName), + registration.getHost()); + + } + + private String getIPFromNetworkInterface(String networkInterface) { + + if (!TestConfig.hasValidNetworkInterface) { + return inetUtils.findFirstNonLoopbackHostInfo().getIpAddress(); + } + + try { + NetworkInterface netInterface = NetworkInterface.getByName(networkInterface); + + Enumeration<InetAddress> inetAddress = netInterface.getInetAddresses(); + while (inetAddress.hasMoreElements()) { + InetAddress currentAddress = inetAddress.nextElement(); + if (currentAddress instanceof Inet4Address + && !currentAddress.isLoopbackAddress()) { + return currentAddress.getHostAddress(); + } + } + return networkInterface; + } + catch (Exception e) { + return networkInterface; + } + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, + AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class }) + public static class TestConfig { + + static boolean hasValidNetworkInterface = false; + static String netWorkInterfaceName; + + static { + + try { + Enumeration<NetworkInterface> enumeration = NetworkInterface + .getNetworkInterfaces(); + while (enumeration.hasMoreElements() && !hasValidNetworkInterface) { + NetworkInterface networkInterface = enumeration.nextElement(); + Enumeration<InetAddress> inetAddress = networkInterface + .getInetAddresses(); + while (inetAddress.hasMoreElements()) { + InetAddress currentAddress = inetAddress.nextElement(); + if (currentAddress instanceof Inet4Address + && !currentAddress.isLoopbackAddress()) { + hasValidNetworkInterface = true; + netWorkInterfaceName = networkInterface.getName(); + System.setProperty( + "spring.cloud.alicloud.ans.client-interface-ame", + networkInterface.getName()); + break; + } + } + } + + } + catch (Exception e) { + + } + } + } + +} diff --git a/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationIpTests.java b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationIpTests.java new file mode 100644 index 000000000..53d7b5c2e --- /dev/null +++ b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationIpTests.java @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2018 the original author or authors. + * + * 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 org.springframework.cloud.alicloud.ans.registry; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.alicloud.ans.AnsAutoConfiguration; +import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration; +import org.springframework.cloud.alicloud.context.ans.AnsProperties; +import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * @author xiaojing + */ + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AnsAutoServiceRegistrationIpTests.TestConfig.class, properties = { + "spring.application.name=myTestService1", + "spring.cloud.alicloud.ans.server-list=127.0.0.1", + "spring.cloud.alicloud.ans.server-port=8080", + "spring.cloud.alicloud.ans.client-ip=123.123.123.123" }, webEnvironment = RANDOM_PORT) +public class AnsAutoServiceRegistrationIpTests { + + @Autowired + private AnsRegistration registration; + + @Autowired + private AnsAutoServiceRegistration ansAutoServiceRegistration; + + @Autowired + private AnsProperties properties; + + @Test + public void contextLoads() throws Exception { + + assertNotNull("AnsRegistration was not created", registration); + assertNotNull("AnsProperties was not created", properties); + assertNotNull("AnsAutoServiceRegistration was not created", + ansAutoServiceRegistration); + + checkoutAnsDiscoveryServiceIP(); + + } + + private void checkoutAnsDiscoveryServiceIP() { + assertEquals("AnsProperties service IP was wrong", "123.123.123.123", + registration.getHost()); + + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, + AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class }) + public static class TestConfig { + } +} diff --git a/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationManagementPortTests.java b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationManagementPortTests.java new file mode 100644 index 000000000..a73f25c28 --- /dev/null +++ b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationManagementPortTests.java @@ -0,0 +1,87 @@ +/* + * Copyright (C) 2018 the original author or authors. + * + * 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 org.springframework.cloud.alicloud.ans.registry; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; +import static org.springframework.cloud.alicloud.ans.registry.AnsRegistration.MANAGEMENT_CONTEXT_PATH; +import static org.springframework.cloud.alicloud.ans.registry.AnsRegistration.MANAGEMENT_PORT; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.alicloud.ans.AnsAutoConfiguration; +import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration; +import org.springframework.cloud.alicloud.context.ans.AnsProperties; +import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * @author xiaojing + */ + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AnsAutoServiceRegistrationManagementPortTests.TestConfig.class, properties = { + "spring.application.name=myTestService1", "management.server.port=8888", + "management.server.servlet.context-path=/test-context-path", + "spring.cloud.alicloud.ans.server-list=127.0.0.1", + "spring.cloud.alicloud.ans.server-port=8080" }, webEnvironment = RANDOM_PORT) +public class AnsAutoServiceRegistrationManagementPortTests { + + @Autowired + private AnsRegistration registration; + + @Autowired + private AnsAutoServiceRegistration ansAutoServiceRegistration; + + @Autowired + private AnsProperties properties; + + @Test + public void contextLoads() throws Exception { + + assertNotNull("AnsRegistration was not created", registration); + assertNotNull("AnsProperties was not created", properties); + assertNotNull("AnsAutoServiceRegistration was not created", + ansAutoServiceRegistration); + + checkoutNacosDiscoveryManagementData(); + + } + + private void checkoutNacosDiscoveryManagementData() { + assertEquals("AnsProperties management port was wrong", "8888", + properties.getClientMetadata().get(MANAGEMENT_PORT)); + + assertEquals("AnsProperties management context path was wrong", + "/test-context-path", + properties.getClientMetadata().get(MANAGEMENT_CONTEXT_PATH)); + + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, + AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class }) + public static class TestConfig { + } +} diff --git a/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationPortTests.java b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationPortTests.java new file mode 100644 index 000000000..20e03eb46 --- /dev/null +++ b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationPortTests.java @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2018 the original author or authors. + * + * 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 org.springframework.cloud.alicloud.ans.registry; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.alicloud.ans.AnsAutoConfiguration; +import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration; +import org.springframework.cloud.alicloud.context.ans.AnsProperties; +import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * @author xiaojing + */ + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AnsAutoServiceRegistrationPortTests.TestConfig.class, properties = { + "spring.application.name=myTestService1", + "spring.cloud.alicloud.ans.server-list=127.0.0.1", + "spring.cloud.alicloud.ans.server-port=8080", + "spring.cloud.alicloud.ans.client-port=8888" }, webEnvironment = RANDOM_PORT) +public class AnsAutoServiceRegistrationPortTests { + + @Autowired + private AnsRegistration registration; + + @Autowired + private AnsAutoServiceRegistration ansAutoServiceRegistration; + + @Autowired + private AnsProperties properties; + + @Test + public void contextLoads() throws Exception { + + assertNotNull("AnsRegistration was not created", registration); + assertNotNull("AnsDiscoveryProperties was not created", properties); + assertNotNull("AnsAutoServiceRegistration was not created", + ansAutoServiceRegistration); + + checkoutAnsDiscoveryServicePort(); + + } + + private void checkoutAnsDiscoveryServicePort() { + assertEquals("AnsDiscoveryProperties service Port was wrong", 8888, + registration.getPort()); + + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, + AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class }) + public static class TestConfig { + } +} diff --git a/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationTests.java b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationTests.java new file mode 100644 index 000000000..933814086 --- /dev/null +++ b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/registry/AnsAutoServiceRegistrationTests.java @@ -0,0 +1,158 @@ +/* + * Copyright (C) 2018 the original author or authors. + * + * 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 org.springframework.cloud.alicloud.ans.registry; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.alibaba.ans.core.NamingService; +import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.cloud.alicloud.ans.AnsAutoConfiguration; +import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration; +import org.springframework.cloud.alicloud.ans.endpoint.AnsEndpoint; +import org.springframework.cloud.alicloud.context.ans.AnsProperties; +import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; +import org.springframework.cloud.commons.util.InetUtils; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * @author xiaojing + */ + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AnsAutoServiceRegistrationTests.TestConfig.class, properties = { + "spring.application.name=myTestService1", + "spring.cloud.alicloud.ans.server-list=127.0.0.1", + "spring.cloud.alicloud.ans.server-port=8080", + "spring.cloud.alicloud.ans.endpoint=test-endpoint" }, webEnvironment = RANDOM_PORT) +public class AnsAutoServiceRegistrationTests { + + @Autowired + private AnsRegistration registration; + + @Autowired + private AnsAutoServiceRegistration ansAutoServiceRegistration; + + @LocalServerPort + private int port; + + @Autowired + private AnsProperties properties; + + @Autowired + private InetUtils inetUtils; + + @Test + public void contextLoads() throws Exception { + + assertNotNull("AnsRegistration was not created", registration); + assertNotNull("AnsProperties was not created", properties); + assertNotNull("AnsAutoServiceRegistration was not created", + ansAutoServiceRegistration); + + checkoutAnsDiscoveryServerList(); + checkoutAnsDiscoveryServerPort(); + + checkoutAnsDiscoveryServiceName(); + checkoutAnsDiscoveryServiceIP(); + checkoutAnsDiscoveryServicePort(); + + checkAutoRegister(); + + checkoutEndpoint(); + + } + + private void checkAutoRegister() { + assertTrue("Ans Auto Registration was not start", + ansAutoServiceRegistration.isRunning()); + } + + private void checkoutAnsDiscoveryServerList() { + assertEquals("AnsDiscoveryProperties server list was wrong", "127.0.0.1", + properties.getServerList()); + + } + + private void checkoutAnsDiscoveryServerPort() { + assertEquals("AnsDiscoveryProperties server port was wrong", "8080", + properties.getServerPort()); + + } + + private void checkoutAnsDiscoveryServiceName() { + assertEquals("AnsDiscoveryProperties service name was wrong", "myTestService1", + properties.getClientDomains()); + + } + + private void checkoutAnsDiscoveryServiceIP() { + assertEquals("AnsDiscoveryProperties service IP was wrong", + inetUtils.findFirstNonLoopbackHostInfo().getIpAddress(), + registration.getHost()); + + } + + private void checkoutAnsDiscoveryServicePort() { + assertEquals("AnsDiscoveryProperties service Port was wrong", port, + registration.getPort()); + + } + + private void checkoutEndpoint() throws Exception { + AnsEndpoint ansEndpoint = new AnsEndpoint(properties); + Map<String, Object> map = ansEndpoint.invoke(); + assertEquals(map.get("ansProperties"), properties); + + Map<String, Object> subscribes = new HashMap<>(); + Set<String> subscribeServices = NamingService.getDomsSubscribed(); + for (String service : subscribeServices) { + try { + List<Host> hosts = NamingService.getHosts(service); + subscribes.put(service, hosts); + } + catch (Exception ignoreException) { + + } + } + + assertEquals(map.get("subscribes"), subscribes); + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, + AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class }) + public static class TestConfig { + } +} diff --git a/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/ribbon/AnsRibbonClientConfigurationTests.java b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/ribbon/AnsRibbonClientConfigurationTests.java new file mode 100644 index 000000000..beb825c71 --- /dev/null +++ b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/ribbon/AnsRibbonClientConfigurationTests.java @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2018 the original author or authors. + * + * 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 org.springframework.cloud.alicloud.ans.ribbon; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.alicloud.ans.AnsAutoConfiguration; +import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; +import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.client.RestTemplate; + +import com.netflix.client.config.DefaultClientConfigImpl; +import com.netflix.client.config.IClientConfig; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +/** + * @author xiaojing + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AnsRibbonClientConfigurationTests.TestConfig.class, properties = { + "spring.application.name=myTestService1", + "spring.cloud.alicloud.ans.server-list=127.0.0.1", + "spring.cloud.alicloud.ans.server-port=8080", + "spring.cloud.alicloud.ans.endpoint=test-endpoint" }, webEnvironment = RANDOM_PORT) +public class AnsRibbonClientConfigurationTests { + + @Autowired + private AnsServerList serverList; + + @Test + public void contextLoads() throws Exception { + assertThat(serverList.getDom()).isEqualTo("myapp"); + } + + @Configuration + public static class AnsRibbonTestConfiguration { + + @Bean + IClientConfig iClientConfig() { + DefaultClientConfigImpl config = new DefaultClientConfigImpl(); + config.setClientName("myapp"); + return config; + } + + @Bean + @LoadBalanced + RestTemplate restTemplate() { + return new RestTemplate(); + } + + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, + AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class, + AnsRibbonTestConfiguration.class, RibbonAnsAutoConfiguration.class, + AnsRibbonClientConfiguration.class }) + public static class TestConfig { + } + +} diff --git a/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServerListTests.java b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServerListTests.java new file mode 100644 index 000000000..815fa89da --- /dev/null +++ b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServerListTests.java @@ -0,0 +1,148 @@ +/* + * Copyright (C) 2018 the original author or authors. + * + * 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 org.springframework.cloud.alicloud.ans.ribbon; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.springframework.cloud.alicloud.ans.test.AnsMockTest.hostInstance; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.stream.Collectors; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.alibaba.ans.core.NamingService; +import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host; + +import com.netflix.client.config.IClientConfig; + +/** + * @author xiaojing + */ +@RunWith(PowerMockRunner.class) +@PrepareForTest({ NamingService.class, AnsServer.class }) +public class AnsServerListTests { + + @Test + @SuppressWarnings("unchecked") + public void testEmptyInstancesReturnsEmptyList() throws Exception { + + PowerMockito.mockStatic(NamingService.class); + when(NamingService.getHosts(anyString())).thenReturn(Collections.EMPTY_LIST); + + IClientConfig clientConfig = mock(IClientConfig.class); + when(clientConfig.getClientName()).thenReturn("test-service"); + AnsServerList serverList = new AnsServerList("test-service"); + serverList.initWithNiwsConfig(clientConfig); + List<AnsServer> servers = serverList.getInitialListOfServers(); + assertThat(servers).isEmpty(); + } + + @Test + @SuppressWarnings("unchecked") + public void testGetServers() throws Exception { + + ArrayList<Host> hosts = new ArrayList<>(); + hosts.add(hostInstance("test-service", true, Collections.emptyMap())); + + PowerMockito.mockStatic(NamingService.class); + when(NamingService.getHosts(anyString())).thenReturn(hosts); + PowerMockito.stub(PowerMockito.method(AnsServer.class, "isAlive", long.class)) + .toReturn(true); + + IClientConfig clientConfig = mock(IClientConfig.class); + when(clientConfig.getClientName()).thenReturn("test-service"); + AnsServerList serverList = new AnsServerList("test-service"); + serverList.initWithNiwsConfig(clientConfig); + List<AnsServer> servers = serverList.getInitialListOfServers(); + assertThat(servers).hasSize(1); + + servers = serverList.getUpdatedListOfServers(); + assertThat(servers).hasSize(1); + } + + @Test + @SuppressWarnings("unchecked") + public void testGetServersWithInstanceStatus() throws Exception { + ArrayList<Host> hosts = new ArrayList<>(); + + HashMap<String, String> map1 = new HashMap<>(); + map1.put("instanceNum", "1"); + HashMap<String, String> map2 = new HashMap<>(); + map2.put("instanceNum", "2"); + hosts.add(hostInstance("test-service", false, map1)); + hosts.add(hostInstance("test-service", true, map2)); + + PowerMockito.mockStatic(NamingService.class); + when(NamingService.getHosts(eq("test-service"))).thenReturn( + hosts.stream().filter(Host::isValid).collect(Collectors.toList())); + + PowerMockito.stub(PowerMockito.method(AnsServer.class, "isAlive", long.class)) + .toReturn(true); + + IClientConfig clientConfig = mock(IClientConfig.class); + when(clientConfig.getClientName()).thenReturn("test-service"); + AnsServerList serverList = new AnsServerList("test-service"); + serverList.initWithNiwsConfig(clientConfig); + List<AnsServer> servers = serverList.getInitialListOfServers(); + assertThat(servers).hasSize(1); + + AnsServer ansServer = servers.get(0); + Host host = ansServer.getHealthService(); + + assertThat(ansServer.getMetaInfo().getInstanceId()).isEqualTo( + host.getIp() + ":" + host.getHostname() + ":" + host.getPort()); + assertThat(ansServer.getHealthService().isValid()).isEqualTo(true); + assertThat(ansServer.getHealthService().getHostname()).isEqualTo("test-service"); + + } + + @Test + public void testUpdateServers() throws Exception { + ArrayList<Host> hosts = new ArrayList<>(); + + HashMap<String, String> map = new HashMap<>(); + map.put("instanceNum", "1"); + hosts.add(hostInstance("test-service", true, map)); + + PowerMockito.mockStatic(NamingService.class); + when(NamingService.getHosts(eq("test-service"))).thenReturn( + hosts.stream().filter(Host::isValid).collect(Collectors.toList())); + PowerMockito.stub(PowerMockito.method(AnsServer.class, "isAlive", long.class)) + .toReturn(true); + + IClientConfig clientConfig = mock(IClientConfig.class); + when(clientConfig.getClientName()).thenReturn("test-service"); + AnsServerList serverList = new AnsServerList("test-service"); + serverList.initWithNiwsConfig(clientConfig); + + List<AnsServer> servers = serverList.getUpdatedListOfServers(); + assertThat(servers).hasSize(1); + + assertThat(servers.get(0).getHealthService().isValid()).isEqualTo(true); + } +} \ No newline at end of file diff --git a/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServiceListTests.java b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServiceListTests.java new file mode 100644 index 000000000..3e3d59e42 --- /dev/null +++ b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/ribbon/AnsServiceListTests.java @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2018 the original author or authors. + * + * 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 org.springframework.cloud.alicloud.ans.ribbon; + +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host; +import com.netflix.loadbalancer.Server; + +/** + * @author xiaolongzuo + */ +public class AnsServiceListTests { + + static final String IP_ADDR = "10.0.0.2"; + + static final int PORT = 8080; + + @Test + public void testAnsServer() { + AnsServerList serverList = getAnsServerList(); + List<AnsServer> servers = serverList.getInitialListOfServers(); + assertNotNull("servers was null", servers); + assertEquals("servers was not size 1", 1, servers.size()); + Server des = assertAnsServer(servers); + assertEquals("hostPort was wrong", IP_ADDR + ":" + PORT, des.getHostPort()); + } + + protected Server assertAnsServer(List<AnsServer> servers) { + Server actualServer = servers.get(0); + assertTrue("server was not a DomainExtractingServer", + actualServer instanceof AnsServer); + AnsServer des = AnsServer.class.cast(actualServer); + assertNotNull("host is null", des.getHealthService()); + assertEquals("unit was wrong", "DEFAULT", des.getHealthService().getUnit()); + return des; + } + + protected AnsServerList getAnsServerList() { + Host host = mock(Host.class); + given(host.getIp()).willReturn(IP_ADDR); + given(host.getDoubleWeight()).willReturn(1.0); + given(host.getPort()).willReturn(PORT); + given(host.getWeight()).willReturn(1); + given(host.getUnit()).willReturn("DEFAULT"); + + AnsServer server = new AnsServer(host, "testDom"); + @SuppressWarnings("unchecked") + AnsServerList originalServerList = mock(AnsServerList.class); + given(originalServerList.getInitialListOfServers()) + .willReturn(Arrays.asList(server)); + return originalServerList; + } + +} diff --git a/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/test/AnsMockTest.java b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/test/AnsMockTest.java new file mode 100644 index 000000000..795f2b49a --- /dev/null +++ b/spring-cloud-alicloud-ans/src/test/java/org/springframework/cloud/alicloud/ans/test/AnsMockTest.java @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2018 the original author or authors. + * + * 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 org.springframework.cloud.alicloud.ans.test; + +import java.util.Map; + +import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host; + +/** + * @author xiaojing + */ +public class AnsMockTest { + + public static Host hostInstance(String serviceName, boolean valid, + Map<String, String> metadata) { + Host host = new Host(); + host.setHostname(serviceName); + host.setValid(valid); + return host; + } + + public static Host hostInstance(String serviceName, boolean valid, String ip, + int port, Map<String, String> metadata) { + Host host = new Host(); + host.setIp(ip); + host.setPort(port); + host.setValid(valid); + host.setHostname(serviceName); + return host; + } +}