test:add junit test to polaris-discovery. (#205)

pull/206/head
Haotian Zhang 3 years ago committed by GitHub
parent b97f77a418
commit 6a90de6d1e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -11,3 +11,4 @@
- [Feature: Load application.yml and application-${profile}.yml from polaris server.](https://github.com/Tencent/spring-cloud-tencent/pull/199)
- [feat:add rate limit of unirate.](https://github.com/Tencent/spring-cloud-tencent/pull/197)
- [test:add junit test to polaris-circuitbreaker.](https://github.com/Tencent/spring-cloud-tencent/pull/202)
- [test:add junit test to polaris-discovery.](https://github.com/Tencent/spring-cloud-tencent/pull/205)

@ -41,9 +41,6 @@ Copyright (c) guava authors and contributors.
6. reactor
Copyright (c) reactor authors and contributors.
7. powermock
Copyright 2007-2017 PowerMock Contributors
Terms of the Apache v2.0 License:
--------------------------------------------------------------------

@ -50,20 +50,6 @@
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
<scope>test</scope>
</dependency>
<!-- powermock-module-junit4 -->
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<scope>test</scope>
</dependency>
<!-- powermock-api-mockito -->
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

@ -98,17 +98,5 @@
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

@ -54,14 +54,14 @@ public class DiscoveryPropertiesAutoConfiguration {
private boolean discoveryEnabled = false;
@Bean(name = "polarisProvider")
@Bean
@ConditionalOnMissingBean
public ProviderAPI polarisProvider(SDKContext polarisContext)
throws PolarisException {
return DiscoveryAPIFactory.createProviderAPIByContext(polarisContext);
}
@Bean(name = "polarisConsumer")
@Bean
@ConditionalOnMissingBean
public ConsumerAPI polarisConsumer(SDKContext polarisContext)
throws PolarisException {

@ -18,14 +18,11 @@
package com.tencent.cloud.polaris;
import javax.annotation.PostConstruct;
import com.tencent.cloud.common.constant.ContextConstant;
import com.tencent.cloud.polaris.context.PolarisConfigModifier;
import com.tencent.polaris.factory.config.ConfigurationImpl;
import com.tencent.polaris.factory.config.consumer.DiscoveryConfigImpl;
import com.tencent.polaris.factory.config.provider.RegisterConfigImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
@ -42,11 +39,6 @@ import org.springframework.core.env.Environment;
@ConfigurationProperties("spring.cloud.polaris.discovery")
public class PolarisDiscoveryProperties {
/**
* The polaris authentication token.
*/
private String token;
/**
* Namespace, separation registry of different environments.
*/
@ -59,6 +51,11 @@ public class PolarisDiscoveryProperties {
@Value("${spring.cloud.polaris.discovery.service:${spring.cloud.polaris.service:${spring.application.name:}}}")
private String service;
/**
* The polaris authentication token.
*/
private String token;
/**
* Load balance weight.
*/
@ -79,7 +76,7 @@ public class PolarisDiscoveryProperties {
/**
* Port of instance.
*/
@Value("${server.port:}")
@Value("${server.port:8080}")
private int port;
/**
@ -113,29 +110,7 @@ public class PolarisDiscoveryProperties {
@Autowired
private Environment environment;
/**
* Init properties.
*/
@PostConstruct
public void init() {
if (StringUtils.isEmpty(this.getNamespace())) {
this.setNamespace(environment
.resolvePlaceholders("${spring.cloud.polaris.discovery.namespace:}"));
}
if (StringUtils.isEmpty(this.getService())) {
this.setService(environment
.resolvePlaceholders("${spring.cloud.polaris.discovery.service:}"));
}
if (StringUtils.isEmpty(this.getToken())) {
this.setToken(environment
.resolvePlaceholders("${spring.cloud.polaris.discovery.token:}"));
}
}
public boolean isHeartbeatEnabled() {
if (null == heartbeatEnabled) {
return false;
}
return heartbeatEnabled;
}
@ -233,12 +208,20 @@ public class PolarisDiscoveryProperties {
@Override
public String toString() {
return "PolarisProperties{" + "token='" + token + '\'' + ", namespace='"
+ namespace + '\'' + ", service='" + service + '\'' + ", weight=" + weight
+ ", version='" + version + '\'' + ", protocol='" + protocol + '\''
+ ", port=" + port + '\'' + ", registerEnabled=" + registerEnabled
+ ", heartbeatEnabled=" + heartbeatEnabled + ", healthCheckUrl="
+ healthCheckUrl + ", environment=" + environment + '}';
return "PolarisDiscoveryProperties{" +
"namespace='" + namespace + '\'' +
", service='" + service + '\'' +
", token='" + token + '\'' +
", weight=" + weight +
", version='" + version + '\'' +
", protocol='" + protocol + '\'' +
", port=" + port +
", enabled=" + enabled +
", registerEnabled=" + registerEnabled +
", heartbeatEnabled=" + heartbeatEnabled +
", healthCheckUrl='" + healthCheckUrl + '\'' +
", serviceListRefreshInterval=" + serviceListRefreshInterval +
'}';
}
@Bean

@ -32,7 +32,7 @@ public class PolarisDiscoveryClient implements DiscoveryClient {
/**
* Polaris Discovery Client Description.
*/
public final String description = "Spring Cloud Polaris Discovery Client";
public final String description = "Spring Cloud Tencent Polaris Discovery Client.";
private final PolarisServiceDiscovery polarisServiceDiscovery;

@ -18,22 +18,15 @@
package com.tencent.cloud.polaris.discovery;
import java.util.Map;
import com.tencent.cloud.common.metadata.MetadataContext;
import com.tencent.cloud.common.metadata.MetadataContextHolder;
import com.tencent.cloud.polaris.PolarisDiscoveryProperties;
import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.api.core.ProviderAPI;
import com.tencent.polaris.api.pojo.ServiceInfo;
import com.tencent.polaris.api.rpc.GetAllInstancesRequest;
import com.tencent.polaris.api.rpc.GetHealthyInstancesRequest;
import com.tencent.polaris.api.rpc.GetInstancesRequest;
import com.tencent.polaris.api.rpc.GetServicesRequest;
import com.tencent.polaris.api.rpc.InstancesResponse;
import com.tencent.polaris.api.rpc.ServicesResponse;
import com.tencent.polaris.client.api.SDKContext;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@ -58,32 +51,6 @@ public class PolarisDiscoveryHandler {
@Autowired
private ConsumerAPI polarisConsumer;
/**
* Get a list of instances after service routing.
* @param service service name
* @return list of instances
*/
@Deprecated
public InstancesResponse getFilteredInstances(String service) {
String namespace = polarisDiscoveryProperties.getNamespace();
GetInstancesRequest getInstancesRequest = new GetInstancesRequest();
getInstancesRequest.setNamespace(namespace);
getInstancesRequest.setService(service);
String localNamespace = MetadataContext.LOCAL_NAMESPACE;
String localService = MetadataContext.LOCAL_SERVICE;
Map<String, String> allTransitiveCustomMetadata = MetadataContextHolder.get().
getFragmentContext(MetadataContext.FRAGMENT_TRANSITIVE);
if (StringUtils.isNotBlank(localNamespace) || StringUtils.isNotBlank(localService)
|| null != allTransitiveCustomMetadata) {
ServiceInfo sourceService = new ServiceInfo();
sourceService.setNamespace(localNamespace);
sourceService.setService(localService);
sourceService.setMetadata(allTransitiveCustomMetadata);
getInstancesRequest.setServiceInfo(sourceService);
}
return polarisConsumer.getInstances(getInstancesRequest);
}
/**
* Get a list of healthy instances.
* @param service service name

@ -50,7 +50,7 @@ public class PolarisReactiveDiscoveryClient implements ReactiveDiscoveryClient {
@Override
public String description() {
return "Spring Cloud Polaris Reactive Discovery Client";
return "Spring Cloud Tencent Polaris Reactive Discovery Client.";
}
@Override

@ -73,14 +73,6 @@ public class ConsulContextProperties {
@Value("${spring.cloud.consul.discovery.prefer-ip-address:#{'false'}}")
private boolean preferIpAddress;
public void setHost(String host) {
this.host = host;
}
public void setPort(int port) {
this.port = port;
}
public boolean isEnabled() {
return enabled;
}
@ -113,40 +105,32 @@ public class ConsulContextProperties {
@Override
public void modify(ConfigurationImpl configuration) {
if (consulContextProperties != null && consulContextProperties.enabled) {
if (CollectionUtils
.isEmpty(configuration.getGlobal().getServerConnectors())) {
if (CollectionUtils.isEmpty(configuration.getGlobal().getServerConnectors())) {
configuration.getGlobal().setServerConnectors(new ArrayList<>());
}
if (CollectionUtils
.isEmpty(configuration.getGlobal().getServerConnectors())
if (CollectionUtils.isEmpty(configuration.getGlobal().getServerConnectors())
&& null != configuration.getGlobal().getServerConnector()) {
configuration.getGlobal().getServerConnectors()
.add(configuration.getGlobal().getServerConnector());
configuration.getGlobal().getServerConnectors().add(configuration.getGlobal().getServerConnector());
}
ServerConnectorConfigImpl serverConnectorConfig = new ServerConnectorConfigImpl();
serverConnectorConfig.setId(ID);
serverConnectorConfig.setAddresses(
Collections.singletonList(consulContextProperties.host + ":"
serverConnectorConfig.setAddresses(Collections.singletonList(consulContextProperties.host + ":"
+ consulContextProperties.port));
serverConnectorConfig.setProtocol(DefaultPlugins.SERVER_CONNECTOR_CONSUL);
Map<String, String> metadata = serverConnectorConfig.getMetadata();
if (StringUtils.isNotBlank(consulContextProperties.serviceName)) {
metadata.put(MetadataMapKey.SERVICE_NAME_KEY,
consulContextProperties.serviceName);
metadata.put(MetadataMapKey.SERVICE_NAME_KEY, consulContextProperties.serviceName);
}
if (StringUtils.isNotBlank(consulContextProperties.instanceId)) {
metadata.put(MetadataMapKey.INSTANCE_ID_KEY,
consulContextProperties.instanceId);
metadata.put(MetadataMapKey.INSTANCE_ID_KEY, consulContextProperties.instanceId);
}
if (consulContextProperties.preferIpAddress
&& StringUtils.isNotBlank(consulContextProperties.ipAddress)) {
metadata.put(MetadataMapKey.PREFER_IP_ADDRESS_KEY,
String.valueOf(consulContextProperties.preferIpAddress));
metadata.put(MetadataMapKey.IP_ADDRESS_KEY,
consulContextProperties.ipAddress);
metadata.put(MetadataMapKey.IP_ADDRESS_KEY, consulContextProperties.ipAddress);
}
configuration.getGlobal().getServerConnectors()
.add(serverConnectorConfig);
configuration.getGlobal().getServerConnectors().add(serverConnectorConfig);
DiscoveryConfigImpl discoveryConfig = new DiscoveryConfigImpl();
discoveryConfig.setServerConnectorId(ID);

@ -0,0 +1,90 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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.tencent.cloud.polaris;
import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler;
import com.tencent.cloud.polaris.extend.consul.ConsulContextProperties;
import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.api.core.ProviderAPI;
import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test for {@link DiscoveryPropertiesAutoConfiguration}.
*
* @author Haotian Zhang
*/
public class DiscoveryPropertiesAutoConfigurationTest {
@Test
public void testDefaultInitialization() {
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner().withConfiguration(
AutoConfigurations.of(PolarisContextAutoConfiguration.class,
DiscoveryPropertiesAutoConfiguration.class));
applicationContextRunner.run(context -> {
assertThat(context).hasSingleBean(DiscoveryPropertiesAutoConfiguration.class);
assertThat(context).hasSingleBean(PolarisDiscoveryProperties.class);
assertThat(context).hasSingleBean(ConsulContextProperties.class);
assertThat(context).hasSingleBean(ProviderAPI.class);
assertThat(context).hasSingleBean(ConsumerAPI.class);
assertThat(context).hasSingleBean(PolarisDiscoveryHandler.class);
assertThat(context).hasSingleBean(DiscoveryConfigModifier.class);
});
}
@Test
public void testInit() {
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner().withConfiguration(
AutoConfigurations.of(PolarisContextAutoConfiguration.class,
TestConfiguration.class,
DiscoveryPropertiesAutoConfiguration.class))
.withPropertyValues("spring.cloud.polaris.discovery.register=false")
.withPropertyValues("spring.cloud.consul.discovery.register=false")
.withPropertyValues("spring.cloud.consul.discovery.enabled=false");
applicationContextRunner.run(context -> {
assertThat(context).hasSingleBean(DiscoveryPropertiesAutoConfiguration.class);
DiscoveryPropertiesAutoConfiguration discoveryPropertiesAutoConfiguration = context.getBean(DiscoveryPropertiesAutoConfiguration.class);
assertThat(discoveryPropertiesAutoConfiguration.isRegisterEnabled()).isFalse();
assertThat(discoveryPropertiesAutoConfiguration.isDiscoveryEnabled()).isFalse();
});
}
@Configuration
static class TestConfiguration {
@Bean
public PolarisDiscoveryProperties polarisDiscoveryProperties() {
PolarisDiscoveryProperties polarisDiscoveryProperties = new PolarisDiscoveryProperties();
polarisDiscoveryProperties.setEnabled(false);
return polarisDiscoveryProperties;
}
@Bean
public ConsulContextProperties consulContextProperties() {
ConsulContextProperties consulContextProperties = new ConsulContextProperties();
consulContextProperties.setEnabled(true);
return consulContextProperties;
}
}
}

@ -0,0 +1,46 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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.tencent.cloud.polaris;
import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test for {@link DiscoveryPropertiesBootstrapAutoConfiguration}.
*
* @author Haotian Zhang
*/
public class DiscoveryPropertiesBootstrapAutoConfigurationTest {
@Test
public void testDefaultInitialization() {
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner().withConfiguration(
AutoConfigurations.of(PolarisContextAutoConfiguration.class,
DiscoveryPropertiesBootstrapAutoConfiguration.class))
.withPropertyValues("spring.cloud.polaris.enabled=true");
applicationContextRunner.run(context -> {
assertThat(context).hasSingleBean(DiscoveryPropertiesBootstrapAutoConfiguration.class);
assertThat(context).hasSingleBean(DiscoveryPropertiesAutoConfiguration.class);
});
}
}

@ -0,0 +1,102 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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.tencent.cloud.polaris;
import org.junit.Test;
import static com.tencent.polaris.test.common.Consts.NAMESPACE_TEST;
import static com.tencent.polaris.test.common.Consts.PORT;
import static com.tencent.polaris.test.common.Consts.PROVIDER_TOKEN;
import static com.tencent.polaris.test.common.Consts.SERVICE_PROVIDER;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test for {@link PolarisDiscoveryProperties}.
*
* @author Haotian Zhang
*/
public class PolarisDiscoveryPropertiesTest {
@Test
public void testGetAndSet() {
PolarisDiscoveryProperties polarisDiscoveryProperties = new PolarisDiscoveryProperties();
// HeartbeatEnabled
polarisDiscoveryProperties.setHeartbeatEnabled(true);
assertThat(polarisDiscoveryProperties.isHeartbeatEnabled()).isTrue();
// Namespace
polarisDiscoveryProperties.setNamespace(NAMESPACE_TEST);
assertThat(polarisDiscoveryProperties.getNamespace()).isEqualTo(NAMESPACE_TEST);
// Weight
polarisDiscoveryProperties.setWeight(10);
assertThat(polarisDiscoveryProperties.getWeight()).isEqualTo(10);
// Service
polarisDiscoveryProperties.setService(SERVICE_PROVIDER);
assertThat(polarisDiscoveryProperties.getService()).isEqualTo(SERVICE_PROVIDER);
// Enabled
polarisDiscoveryProperties.setEnabled(true);
assertThat(polarisDiscoveryProperties.isEnabled()).isTrue();
// RegisterEnabled
polarisDiscoveryProperties.setRegisterEnabled(true);
assertThat(polarisDiscoveryProperties.isRegisterEnabled()).isTrue();
// Token
polarisDiscoveryProperties.setToken(PROVIDER_TOKEN);
assertThat(polarisDiscoveryProperties.getToken()).isEqualTo(PROVIDER_TOKEN);
// Version
polarisDiscoveryProperties.setVersion("1.0.0");
assertThat(polarisDiscoveryProperties.getVersion()).isEqualTo("1.0.0");
// HTTP
polarisDiscoveryProperties.setProtocol("HTTP");
assertThat(polarisDiscoveryProperties.getProtocol()).isEqualTo("HTTP");
// Port
polarisDiscoveryProperties.setPort(PORT);
assertThat(polarisDiscoveryProperties.getPort()).isEqualTo(PORT);
// HealthCheckUrl
polarisDiscoveryProperties.setHealthCheckUrl("/health");
assertThat(polarisDiscoveryProperties.getHealthCheckUrl()).isEqualTo("/health");
// ServiceListRefreshInterval
polarisDiscoveryProperties.setServiceListRefreshInterval(1000L);
assertThat(polarisDiscoveryProperties.getServiceListRefreshInterval()).isEqualTo(1000L);
assertThat(polarisDiscoveryProperties.toString())
.isEqualTo("PolarisDiscoveryProperties{"
+ "namespace='Test'"
+ ", service='java_provider_test'"
+ ", token='19485a7674294e3c88dba293373c1534'"
+ ", weight=10, version='1.0.0'"
+ ", protocol='HTTP'"
+ ", port=9091"
+ ", enabled=true"
+ ", registerEnabled=true"
+ ", heartbeatEnabled=true"
+ ", healthCheckUrl='/health'"
+ ", serviceListRefreshInterval=1000}");
}
}

@ -72,4 +72,8 @@ public class PolarisDiscoveryClientTest {
}
@Test
public void testDescription() {
assertThat(client.description()).isEqualTo("Spring Cloud Tencent Polaris Discovery Client.");
}
}

@ -20,6 +20,7 @@ package com.tencent.cloud.polaris.discovery.reactive;
import java.util.Arrays;
import com.tencent.cloud.polaris.discovery.PolarisServiceDiscovery;
import com.tencent.polaris.api.exception.ErrorCode;
import com.tencent.polaris.api.exception.PolarisException;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -33,6 +34,9 @@ import org.springframework.cloud.client.ServiceInstance;
import static com.tencent.polaris.test.common.Consts.SERVICE_PROVIDER;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
@ -46,34 +50,57 @@ public class PolarisReactiveDiscoveryClientTest {
@Mock
private PolarisServiceDiscovery serviceDiscovery;
@Mock
private ServiceInstance serviceInstance;
@InjectMocks
private PolarisReactiveDiscoveryClient client;
private int count = 0;
@Test
public void testGetInstances() throws PolarisException {
when(serviceDiscovery.getInstances(SERVICE_PROVIDER))
.thenReturn(singletonList(serviceInstance));
when(serviceDiscovery.getInstances(anyString())).thenAnswer(invocation -> {
String serviceName = invocation.getArgument(0);
if (SERVICE_PROVIDER.equalsIgnoreCase(serviceName)) {
return singletonList(mock(ServiceInstance.class));
}
else {
throw new PolarisException(ErrorCode.UNKNOWN_SERVER_ERROR);
}
});
// Normal
Flux<ServiceInstance> instances = this.client.getInstances(SERVICE_PROVIDER);
StepVerifier.create(instances).expectNextCount(1).expectComplete().verify();
// PolarisException
instances = this.client.getInstances(SERVICE_PROVIDER + 1);
StepVerifier.create(instances).expectNextCount(0).expectComplete().verify();
}
@Test
public void testGetServices() throws PolarisException {
when(serviceDiscovery.getServices())
.thenReturn(Arrays.asList(SERVICE_PROVIDER + 1, SERVICE_PROVIDER + 2));
when(serviceDiscovery.getServices()).thenAnswer(invocation -> {
if (count == 0) {
count++;
return Arrays.asList(SERVICE_PROVIDER + 1, SERVICE_PROVIDER + 2);
}
else {
throw new PolarisException(ErrorCode.UNKNOWN_SERVER_ERROR);
}
});
// Normal
Flux<String> services = this.client.getServices();
StepVerifier.create(services).expectNext(SERVICE_PROVIDER + 1, SERVICE_PROVIDER + 2).expectComplete().verify();
StepVerifier.create(services)
.expectNext(SERVICE_PROVIDER + 1, SERVICE_PROVIDER + 2).expectComplete()
.verify();
// PolarisException
services = this.client.getServices();
StepVerifier.create(services).expectNextCount(0).expectComplete().verify();
}
@Test
public void testDescription() {
assertThat(client.description()).isEqualTo("Spring Cloud Tencent Polaris Reactive Discovery Client.");
}
}

@ -0,0 +1,114 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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.tencent.cloud.polaris.discovery.refresh;
import java.lang.reflect.Field;
import java.util.Collections;
import com.tencent.polaris.api.pojo.DefaultInstance;
import com.tencent.polaris.api.pojo.ServiceEventKey;
import com.tencent.polaris.api.pojo.ServiceInfo;
import com.tencent.polaris.api.pojo.ServiceKey;
import com.tencent.polaris.client.pojo.ServiceInstancesByProto;
import com.tencent.polaris.client.pojo.ServicesByProto;
import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import static com.tencent.polaris.test.common.Consts.HOST;
import static com.tencent.polaris.test.common.Consts.NAMESPACE_TEST;
import static com.tencent.polaris.test.common.Consts.PORT;
import static com.tencent.polaris.test.common.Consts.SERVICE_PROVIDER;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* Test for {@link PolarisServiceStatusChangeListener}.
*
* @author Haotian Zhang
*/
public class PolarisServiceStatusChangeListenerTest {
private ApplicationEventPublisher publisher;
@Before
public void setUp() {
publisher = mock(ApplicationEventPublisher.class);
doNothing().when(publisher).publishEvent(any(ApplicationEvent.class));
}
@Test
public void testOnResourceUpdated() {
PolarisServiceStatusChangeListener polarisServiceStatusChangeListener = new PolarisServiceStatusChangeListener();
polarisServiceStatusChangeListener.setApplicationEventPublisher(publisher);
// Service update event
ServiceEventKey serviceUpdateEventKey = new ServiceEventKey(new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER), ServiceEventKey.EventType.SERVICE);
ServiceInfo serviceInfo = new ServiceInfo();
serviceInfo.setNamespace(NAMESPACE_TEST);
serviceInfo.setService(SERVICE_PROVIDER);
// Need update
ServicesByProto oldServices = new ServicesByProto(Collections.emptyList());
ServicesByProto newServices = new ServicesByProto(Collections.singletonList(serviceInfo));
polarisServiceStatusChangeListener.onResourceUpdated(serviceUpdateEventKey, oldServices, newServices);
verify(publisher, times(1)).publishEvent(any(ApplicationEvent.class));
// No need update
oldServices = new ServicesByProto(Collections.singletonList(serviceInfo));
newServices = new ServicesByProto(Collections.singletonList(serviceInfo));
polarisServiceStatusChangeListener.onResourceUpdated(serviceUpdateEventKey, oldServices, newServices);
verify(publisher, times(1)).publishEvent(any(ApplicationEvent.class));
// Instance update event
ServiceEventKey instanceUpdateEventKey = new ServiceEventKey(new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER), ServiceEventKey.EventType.INSTANCE);
DefaultInstance instance = new DefaultInstance();
instance.setNamespace(NAMESPACE_TEST);
instance.setService(SERVICE_PROVIDER);
instance.setHost(HOST);
instance.setPort(PORT);
try {
Field instances = ServiceInstancesByProto.class.getDeclaredField("instances");
instances.setAccessible(true);
// Need update
ServiceInstancesByProto oldInstances = new ServiceInstancesByProto();
instances.set(oldInstances, Collections.emptyList());
ServiceInstancesByProto newInstances = new ServiceInstancesByProto();
instances.set(newInstances, Collections.singletonList(instance));
polarisServiceStatusChangeListener.onResourceUpdated(serviceUpdateEventKey, oldInstances, newInstances);
verify(publisher, times(2)).publishEvent(any(ApplicationEvent.class));
// No need update
oldInstances = new ServiceInstancesByProto();
instances.set(oldInstances, Collections.singletonList(instance));
newInstances = new ServiceInstancesByProto();
instances.set(newInstances, Collections.singletonList(instance));
polarisServiceStatusChangeListener.onResourceUpdated(serviceUpdateEventKey, oldInstances, newInstances);
verify(publisher, times(2)).publishEvent(any(ApplicationEvent.class));
}
catch (NoSuchFieldException | IllegalAccessException e) {
Assertions.fail("Exception encountered.", e);
}
}
}

@ -0,0 +1,90 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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.tencent.cloud.polaris.extend.consul;
import java.util.List;
import java.util.Map;
import com.tencent.cloud.polaris.DiscoveryPropertiesAutoConfiguration;
import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.factory.config.global.ServerConnectorConfigImpl;
import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static com.tencent.polaris.plugins.connector.common.constant.ConsulConstant.MetadataMapKey.INSTANCE_ID_KEY;
import static com.tencent.polaris.plugins.connector.common.constant.ConsulConstant.MetadataMapKey.IP_ADDRESS_KEY;
import static com.tencent.polaris.plugins.connector.common.constant.ConsulConstant.MetadataMapKey.PREFER_IP_ADDRESS_KEY;
import static com.tencent.polaris.plugins.connector.common.constant.ConsulConstant.MetadataMapKey.SERVICE_NAME_KEY;
import static com.tencent.polaris.test.common.Consts.HOST;
import static com.tencent.polaris.test.common.Consts.SERVICE_PROVIDER;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test for {@link ConsulContextProperties}.
*
* @author Haotian Zhang
*/
public class ConsulContextPropertiesTest {
@Test
public void testModify() {
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner().withConfiguration(
AutoConfigurations.of(PolarisContextAutoConfiguration.class,
ConsulContextPropertiesTest.TestConfiguration.class,
DiscoveryPropertiesAutoConfiguration.class))
.withPropertyValues("spring.cloud.consul.discovery.register=true")
.withPropertyValues("spring.cloud.consul.discovery.enabled=true")
.withPropertyValues("spring.application.name=" + SERVICE_PROVIDER)
.withPropertyValues("spring.cloud.consul.discovery.instance-id=ins-test")
.withPropertyValues("spring.cloud.consul.discovery.prefer-ip-address=true")
.withPropertyValues("spring.cloud.consul.discovery.ip-address=" + HOST);
applicationContextRunner.run(context -> {
assertThat(context).hasSingleBean(SDKContext.class);
SDKContext sdkContext = context.getBean(SDKContext.class);
com.tencent.polaris.api.config.Configuration configuration = sdkContext.getConfig();
List<ServerConnectorConfigImpl> serverConnectorConfigs = configuration.getGlobal().getServerConnectors();
Map<String, String> metadata = null;
for (ServerConnectorConfigImpl serverConnectorConfig : serverConnectorConfigs) {
if (serverConnectorConfig.getId().equals("consul")) {
metadata = serverConnectorConfig.getMetadata();
}
}
assertThat(metadata).isNotNull();
assertThat(metadata.get(SERVICE_NAME_KEY)).isEqualTo(SERVICE_PROVIDER);
assertThat(metadata.get(INSTANCE_ID_KEY)).isEqualTo("ins-test");
assertThat(metadata.get(PREFER_IP_ADDRESS_KEY)).isEqualTo("true");
assertThat(metadata.get(IP_ADDRESS_KEY)).isEqualTo(HOST);
});
}
@Configuration
static class TestConfiguration {
@Bean
public ConsulContextProperties consulContextProperties() {
ConsulContextProperties consulContextProperties = new ConsulContextProperties();
consulContextProperties.setEnabled(true);
return consulContextProperties;
}
}
}

@ -13,45 +13,32 @@
* 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.tencent.cloud.polaris;
package com.tencent.cloud.polaris.ribbon;
import org.junit.Test;
import static com.tencent.polaris.test.common.Consts.NAMESPACE_TEST;
import static com.tencent.polaris.test.common.Consts.SERVICE_PROVIDER;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
/**
* Test for {@link PolarisDiscoveryProperties}.
* Test for {@link PolarisDiscoveryRibbonAutoConfiguration}.
*
* @author Haotian Zhang
*/
public class PolarisPropertiesTest {
@Test
public void testInitAndGetSet() {
PolarisDiscoveryProperties temp = new PolarisDiscoveryProperties();
try {
temp.setNamespace(NAMESPACE_TEST);
assertThat(temp.getNamespace()).isEqualTo(NAMESPACE_TEST);
temp.setService(SERVICE_PROVIDER);
assertThat(temp.getService()).isEqualTo(SERVICE_PROVIDER);
public class PolarisDiscoveryRibbonAutoConfigurationTest {
temp.setToken("xxxxxx");
assertThat(temp.getToken()).isEqualTo("xxxxxx");
private ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner();
temp.init();
assertThat(temp).isNotNull();
}
catch (Exception e) {
fail();
e.printStackTrace();
}
@Test
public void testDefaultInitialization() {
this.applicationContextRunner
.withConfiguration(AutoConfigurations.of(PolarisDiscoveryRibbonAutoConfiguration.class))
.run(context -> {
assertThat(context).hasSingleBean(PolarisDiscoveryRibbonAutoConfiguration.class);
});
}
}

@ -19,22 +19,14 @@ package com.tencent.cloud.polaris.ribbon;
import com.netflix.client.config.DefaultClientConfigImpl;
import com.netflix.client.config.IClientConfig;
import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClientConfiguration;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler;
import com.netflix.loadbalancer.ServerList;
import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import static com.tencent.polaris.test.common.Consts.NAMESPACE_TEST;
import static com.tencent.polaris.test.common.Consts.PORT;
import static com.tencent.polaris.test.common.Consts.SERVICE_PROVIDER;
import static org.assertj.core.api.Assertions.assertThat;
@ -45,48 +37,28 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class PolarisRibbonServerListConfigurationTest {
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(PolarisRibbonClientTest.class,
PolarisDiscoveryClientConfiguration.class,
PolarisContextAutoConfiguration.class))
.withPropertyValues("spring.application.name=" + SERVICE_PROVIDER)
.withPropertyValues("server.port=" + PORT)
.withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081")
.withPropertyValues(
"spring.cloud.polaris.discovery.namespace=" + NAMESPACE_TEST)
.withPropertyValues("spring.cloud.polaris.discovery.token=xxxxxx");
private ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner();
@Test
public void testProperties() {
this.contextRunner.run(context -> {
PolarisDiscoveryHandler discoveryHandler = context
.getBean(PolarisDiscoveryHandler.class);
PolarisServerList serverList = new PolarisServerList(discoveryHandler);
IClientConfig iClientConfig = context.getBean(IClientConfig.class);
serverList.initWithNiwsConfig(iClientConfig);
assertThat(serverList.getServiceId()).isEqualTo(SERVICE_PROVIDER);
public void testDefaultInitialization() {
this.applicationContextRunner
.withConfiguration(AutoConfigurations.of(
TestApplication.class, PolarisRibbonServerListConfiguration.class))
.run(context -> {
assertThat(context).hasSingleBean(PolarisRibbonServerListConfiguration.class);
assertThat(context).hasSingleBean(ServerList.class);
});
}
@Configuration
@EnableAutoConfiguration
@EnableDiscoveryClient
static class PolarisRibbonClientTest {
@SpringBootApplication
static class TestApplication {
@Bean
IClientConfig iClientConfig() {
public IClientConfig iClientConfig() {
DefaultClientConfigImpl config = new DefaultClientConfigImpl();
config.setClientName(SERVICE_PROVIDER);
return config;
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
}

@ -29,13 +29,13 @@ import com.tencent.polaris.api.pojo.ServiceKey;
import com.tencent.polaris.test.mock.discovery.NamingServer;
import com.tencent.polaris.test.mock.discovery.NamingService;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Configuration;
import static com.tencent.polaris.test.common.Consts.NAMESPACE_TEST;
@ -68,6 +68,8 @@ public class PolarisServerListTest {
"spring.cloud.polaris.discovery.namespace=" + NAMESPACE_TEST)
.withPropertyValues("spring.cloud.polaris.discovery.token=xxxxxx");
private IClientConfig iClientConfig;
@BeforeClass
public static void beforeClass() throws Exception {
namingServer = NamingServer.startNamingServer(10081);
@ -84,16 +86,17 @@ public class PolarisServerListTest {
}
}
/**
* Test {@link PolarisServerList#getInitialListOfServers()} with empty server list.
*/
@Before
public void setUp() {
// mock IClientConfig
iClientConfig = mock(IClientConfig.class);
when(iClientConfig.getClientName()).thenReturn(SERVICE_PROVIDER);
}
@Test
@SuppressWarnings("unchecked")
public void test1() {
public void testGetInitialListOfServers() {
this.contextRunner.run(context -> {
// mock
IClientConfig iClientConfig = mock(IClientConfig.class);
when(iClientConfig.getClientName()).thenReturn(SERVICE_PROVIDER);
PolarisDiscoveryHandler polarisDiscoveryHandler = context
.getBean(PolarisDiscoveryHandler.class);
PolarisServerList serverList = new PolarisServerList(polarisDiscoveryHandler);
@ -104,17 +107,9 @@ public class PolarisServerListTest {
});
}
/**
* Test {@link PolarisServerList#getUpdatedListOfServers()} with server list of size
* 3.
*/
@Test
@SuppressWarnings("unchecked")
public void test2() {
public void testGetUpdatedListOfServers() {
this.contextRunner.run(context -> {
// mock
IClientConfig iClientConfig = mock(IClientConfig.class);
when(iClientConfig.getClientName()).thenReturn(SERVICE_PROVIDER);
PolarisDiscoveryHandler polarisDiscoveryHandler = context
.getBean(PolarisDiscoveryHandler.class);
PolarisServerList serverList = new PolarisServerList(polarisDiscoveryHandler);
@ -137,9 +132,20 @@ public class PolarisServerListTest {
});
}
@Test
public void testProperties() {
this.contextRunner.run(context -> {
PolarisDiscoveryHandler polarisDiscoveryHandler = context
.getBean(PolarisDiscoveryHandler.class);
PolarisServerList serverList = new PolarisServerList(polarisDiscoveryHandler);
serverList.initWithNiwsConfig(iClientConfig);
assertThat(serverList.getServiceId()).isEqualTo(SERVICE_PROVIDER);
});
}
@Configuration
@EnableAutoConfiguration
@EnableDiscoveryClient
static class PolarisPropertiesConfiguration {
}

@ -0,0 +1,60 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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.tencent.cloud.polaris.util;
import org.assertj.core.util.Maps;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test for {@link OkHttpUtil}.
*
* @author Haotian Zhang
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = OkHttpUtilTest.TestApplication.class)
public class OkHttpUtilTest {
@LocalServerPort
private int port;
@Test
public void testGet() {
assertThat(OkHttpUtil.get("http://localhost:" + port + "/test", Maps.newHashMap("key", "value"))).isTrue();
assertThat(OkHttpUtil.get("http://localhost:" + port + "/error", Maps.newHashMap("key", "value"))).isFalse();
assertThat(OkHttpUtil.get("http://localhost:55555/error", Maps.newHashMap("key", "value"))).isFalse();
}
@SpringBootApplication
@RestController
static class TestApplication {
@GetMapping("/test")
public String test() {
return "test";
}
}
}

@ -72,7 +72,6 @@
<properties>
<revision>1.5.0-Hoxton.SR9-SNAPSHOT</revision>
<polaris.version>1.6.0-SNAPSHOT</polaris.version>
<powermock.version>2.0.0</powermock.version>
<mocktio.version>4.5.1</mocktio.version>
<byte-buddy.version>1.12.10</byte-buddy.version>
@ -147,20 +146,6 @@
<version>${revision}</version>
</dependency>
<!-- powermock-module-junit4 -->
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
</dependency>
<!-- powermock-api-mockito -->
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>${powermock.version}</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>

Loading…
Cancel
Save