From 6a90de6d1e4d9c50a5f2d293da507a13b50a6d1b Mon Sep 17 00:00:00 2001 From: Haotian Zhang <928016560@qq.com> Date: Fri, 27 May 2022 16:28:49 +0800 Subject: [PATCH] test:add junit test to polaris-discovery. (#205) --- CHANGELOG.md | 1 + LICENSE | 3 - .../pom.xml | 14 --- .../pom.xml | 12 -- .../DiscoveryPropertiesAutoConfiguration.java | 4 +- .../polaris/PolarisDiscoveryProperties.java | 57 +++------ .../discovery/PolarisDiscoveryClient.java | 2 +- .../discovery/PolarisDiscoveryHandler.java | 33 ----- .../PolarisReactiveDiscoveryClient.java | 2 +- .../consul/ConsulContextProperties.java | 34 ++---- ...coveryPropertiesAutoConfigurationTest.java | 90 ++++++++++++++ ...pertiesBootstrapAutoConfigurationTest.java | 46 +++++++ .../PolarisDiscoveryPropertiesTest.java | 102 ++++++++++++++++ .../discovery/PolarisDiscoveryClientTest.java | 4 + .../PolarisReactiveDiscoveryClientTest.java | 53 ++++++-- ...olarisServiceStatusChangeListenerTest.java | 114 ++++++++++++++++++ .../consul/ConsulContextPropertiesTest.java | 90 ++++++++++++++ ...DiscoveryRibbonAutoConfigurationTest.java} | 41 +++---- ...arisRibbonServerListConfigurationTest.java | 58 +++------ .../polaris/ribbon/PolarisServerListTest.java | 44 ++++--- .../cloud/polaris/util/OkHttpUtilTest.java | 60 +++++++++ spring-cloud-tencent-dependencies/pom.xml | 15 --- 22 files changed, 634 insertions(+), 245 deletions(-) create mode 100644 spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/DiscoveryPropertiesAutoConfigurationTest.java create mode 100644 spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/DiscoveryPropertiesBootstrapAutoConfigurationTest.java create mode 100644 spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/PolarisDiscoveryPropertiesTest.java create mode 100644 spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/refresh/PolarisServiceStatusChangeListenerTest.java create mode 100644 spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/extend/consul/ConsulContextPropertiesTest.java rename spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/{PolarisPropertiesTest.java => ribbon/PolarisDiscoveryRibbonAutoConfigurationTest.java} (51%) create mode 100644 spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/util/OkHttpUtilTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d65d2a39..9b244a15a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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) diff --git a/LICENSE b/LICENSE index 800722292..9840b7dba 100644 --- a/LICENSE +++ b/LICENSE @@ -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: -------------------------------------------------------------------- diff --git a/spring-cloud-starter-tencent-metadata-transfer/pom.xml b/spring-cloud-starter-tencent-metadata-transfer/pom.xml index 212bd2b29..d2ea877cb 100644 --- a/spring-cloud-starter-tencent-metadata-transfer/pom.xml +++ b/spring-cloud-starter-tencent-metadata-transfer/pom.xml @@ -50,20 +50,6 @@ spring-cloud-starter-netflix-ribbon test - - - - org.powermock - powermock-module-junit4 - test - - - - - org.powermock - powermock-api-mockito2 - test - diff --git a/spring-cloud-starter-tencent-polaris-discovery/pom.xml b/spring-cloud-starter-tencent-polaris-discovery/pom.xml index 56095e975..39d8d5f83 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/pom.xml +++ b/spring-cloud-starter-tencent-polaris-discovery/pom.xml @@ -98,17 +98,5 @@ reactor-test test - - - org.powermock - powermock-module-junit4 - test - - - - org.powermock - powermock-api-mockito2 - test - diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/DiscoveryPropertiesAutoConfiguration.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/DiscoveryPropertiesAutoConfiguration.java index 21ad954c1..d0129afc0 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/DiscoveryPropertiesAutoConfiguration.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/DiscoveryPropertiesAutoConfiguration.java @@ -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 { diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/PolarisDiscoveryProperties.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/PolarisDiscoveryProperties.java index 77483b360..2de7d0140 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/PolarisDiscoveryProperties.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/PolarisDiscoveryProperties.java @@ -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 diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClient.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClient.java index 783ef4687..f07469807 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClient.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClient.java @@ -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; diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryHandler.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryHandler.java index bd64f463b..e1691ea4e 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryHandler.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryHandler.java @@ -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 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 diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClient.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClient.java index aa098ac04..6d3588c6f 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClient.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClient.java @@ -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 diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/extend/consul/ConsulContextProperties.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/extend/consul/ConsulContextProperties.java index cfea83cf3..b24c72897 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/extend/consul/ConsulContextProperties.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/extend/consul/ConsulContextProperties.java @@ -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 + ":" - + consulContextProperties.port)); + serverConnectorConfig.setAddresses(Collections.singletonList(consulContextProperties.host + ":" + + consulContextProperties.port)); serverConnectorConfig.setProtocol(DefaultPlugins.SERVER_CONNECTOR_CONSUL); Map 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); diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/DiscoveryPropertiesAutoConfigurationTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/DiscoveryPropertiesAutoConfigurationTest.java new file mode 100644 index 000000000..b75d16d93 --- /dev/null +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/DiscoveryPropertiesAutoConfigurationTest.java @@ -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; + } + } +} diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/DiscoveryPropertiesBootstrapAutoConfigurationTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/DiscoveryPropertiesBootstrapAutoConfigurationTest.java new file mode 100644 index 000000000..729c0a30a --- /dev/null +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/DiscoveryPropertiesBootstrapAutoConfigurationTest.java @@ -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); + }); + } +} diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/PolarisDiscoveryPropertiesTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/PolarisDiscoveryPropertiesTest.java new file mode 100644 index 000000000..390c6ea24 --- /dev/null +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/PolarisDiscoveryPropertiesTest.java @@ -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}"); + } +} diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClientTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClientTest.java index 33231b2ff..b678593d9 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClientTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClientTest.java @@ -72,4 +72,8 @@ public class PolarisDiscoveryClientTest { } + @Test + public void testDescription() { + assertThat(client.description()).isEqualTo("Spring Cloud Tencent Polaris Discovery Client."); + } } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClientTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClientTest.java index 88c34028a..ac5f2088a 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClientTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClientTest.java @@ -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 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 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."); + } } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/refresh/PolarisServiceStatusChangeListenerTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/refresh/PolarisServiceStatusChangeListenerTest.java new file mode 100644 index 000000000..e468a46ed --- /dev/null +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/refresh/PolarisServiceStatusChangeListenerTest.java @@ -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); + } + } +} diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/extend/consul/ConsulContextPropertiesTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/extend/consul/ConsulContextPropertiesTest.java new file mode 100644 index 000000000..ac4afe13a --- /dev/null +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/extend/consul/ConsulContextPropertiesTest.java @@ -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 serverConnectorConfigs = configuration.getGlobal().getServerConnectors(); + Map 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; + } + } +} diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/PolarisPropertiesTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/ribbon/PolarisDiscoveryRibbonAutoConfigurationTest.java similarity index 51% rename from spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/PolarisPropertiesTest.java rename to spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/ribbon/PolarisDiscoveryRibbonAutoConfigurationTest.java index a1259704a..e14d9be7d 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/PolarisPropertiesTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/ribbon/PolarisDiscoveryRibbonAutoConfigurationTest.java @@ -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); +public class PolarisDiscoveryRibbonAutoConfigurationTest { - temp.setService(SERVICE_PROVIDER); - assertThat(temp.getService()).isEqualTo(SERVICE_PROVIDER); + private ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner(); - temp.setToken("xxxxxx"); - assertThat(temp.getToken()).isEqualTo("xxxxxx"); - - 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); + }); } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/ribbon/PolarisRibbonServerListConfigurationTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/ribbon/PolarisRibbonServerListConfigurationTest.java index ae3a1eb79..277555901 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/ribbon/PolarisRibbonServerListConfigurationTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/ribbon/PolarisRibbonServerListConfigurationTest.java @@ -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(); - } - } } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/ribbon/PolarisServerListTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/ribbon/PolarisServerListTest.java index a036ed344..db41fb959 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/ribbon/PolarisServerListTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/ribbon/PolarisServerListTest.java @@ -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 { } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/util/OkHttpUtilTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/util/OkHttpUtilTest.java new file mode 100644 index 000000000..7256c3dc2 --- /dev/null +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/util/OkHttpUtilTest.java @@ -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"; + } + } +} diff --git a/spring-cloud-tencent-dependencies/pom.xml b/spring-cloud-tencent-dependencies/pom.xml index 1caacd35f..dc869bcc5 100644 --- a/spring-cloud-tencent-dependencies/pom.xml +++ b/spring-cloud-tencent-dependencies/pom.xml @@ -72,7 +72,6 @@ 1.5.0-Hoxton.SR9-SNAPSHOT 1.6.0-SNAPSHOT - 2.0.0 4.5.1 1.12.10 @@ -147,20 +146,6 @@ ${revision} - - - org.powermock - powermock-module-junit4 - ${powermock.version} - - - - - org.powermock - powermock-api-mockito2 - ${powermock.version} - - org.mockito mockito-inline