Merge pull request #306 from flystar32/master

Add ans module unit test
pull/319/head
format 6 years ago committed by GitHub
commit a30c1525da
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -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>

@ -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

@ -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;

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

@ -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) {
}
}
}
}

@ -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 {
}
}

@ -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 {
}
}

@ -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 {
}
}

@ -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 {
}
}

@ -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 {
}
}

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

@ -14,7 +14,7 @@
* limitations under the License.
*/
package org.springframework.cloud.alibaba.ans.ribbon;
package org.springframework.cloud.alicloud.ans.ribbon;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.given;
@ -24,8 +24,6 @@ import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.springframework.cloud.alicloud.ans.ribbon.AnsServer;
import org.springframework.cloud.alicloud.ans.ribbon.AnsServerList;
import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host;
import com.netflix.loadbalancer.Server;

@ -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;
}
}
Loading…
Cancel
Save