add test 2sct polaris router (#731)

Co-authored-by: Haotian Zhang <928016560@qq.com>
pull/772/head
dongyinuo 2 years ago committed by GitHub
parent 6e8e5f7268
commit 854223b3a8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -16,6 +16,7 @@
- [Fix:fix javadoc.](https://github.com/Tencent/spring-cloud-tencent/pull/721)
- [Code optimization & correct comment](https://github.com/Tencent/spring-cloud-tencent/pull/722)
- [fix:fix discovery junit.](https://github.com/Tencent/spring-cloud-tencent/pull/730)
- [Test:add sct-stater-polaris-router juint.](https://github.com/Tencent/spring-cloud-tencent/pull/731)
- [adapt polaris-java 1.10.1 version](https://github.com/Tencent/spring-cloud-tencent/pull/746)
- [Optimize: change RouteArgument.buildCustom to RouteArgument.fromLabel](https://github.com/Tencent/spring-cloud-tencent/pull/749)
- [Optimize: get service instances by Flux.blockLast() to resolve concurrent problem](https://github.com/Tencent/spring-cloud-tencent/pull/764)

@ -114,7 +114,6 @@ public class PolarisRouterServiceInstanceListSupplier extends DelegatingServiceI
return doRouter(allServers, routerContext);
}
//set method to public for unit test
PolarisRouterContext buildRouterContext(HttpHeaders headers) {
Collection<String> labelHeaderValues = headers.get(RouterConstant.ROUTER_LABEL_HEADER);

@ -40,6 +40,7 @@ import com.tencent.cloud.polaris.router.interceptor.MetadataRouterRequestInterce
import com.tencent.cloud.polaris.router.interceptor.NearbyRouterRequestInterceptor;
import com.tencent.cloud.polaris.router.interceptor.RuleBasedRouterRequestInterceptor;
import com.tencent.cloud.polaris.router.spi.RouterRequestInterceptor;
import com.tencent.polaris.api.exception.PolarisException;
import com.tencent.polaris.api.pojo.DefaultInstance;
import com.tencent.polaris.api.pojo.DefaultServiceInstances;
import com.tencent.polaris.api.pojo.Instance;
@ -55,6 +56,7 @@ import com.tencent.polaris.router.api.rpc.ProcessRoutersResponse;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
@ -63,8 +65,14 @@ import org.mockito.junit.MockitoJUnitRunner;
import reactor.core.publisher.Flux;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.DefaultRequest;
import org.springframework.cloud.client.loadbalancer.RequestData;
import org.springframework.cloud.client.loadbalancer.RequestDataContext;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
@ -228,6 +236,53 @@ public class PolarisRouterServiceInstanceListSupplierTest {
}
}
@Test
public void buildRouterContext() {
PolarisRouterServiceInstanceListSupplier polarisSupplier = new PolarisRouterServiceInstanceListSupplier(
delegate, routerAPI, requestInterceptors, null);
HttpHeaders headers = new HttpHeaders();
PolarisRouterContext context = polarisSupplier.buildRouterContext(headers);
Assert.assertNull(context);
// mock
try (MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class)) {
mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString())).thenReturn("mock-value");
MetadataContextHolder.set(new MetadataContext());
headers = new HttpHeaders();
headers.add(RouterConstant.ROUTER_LABEL_HEADER, "{\"k1\":\"v1\"}");
PolarisRouterContext routerContext = polarisSupplier.buildRouterContext(headers);
assertThat(routerContext.getLabel("k1")).isEqualTo("v1");
}
}
@Test
public void testGet01() {
PolarisRouterServiceInstanceListSupplier polarisSupplier = new PolarisRouterServiceInstanceListSupplier(
delegate, routerAPI, requestInterceptors, null);
Assertions.assertThrows(PolarisException.class, () -> polarisSupplier.get());
}
@Test
public void testGet02() {
try (MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class)) {
mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString()))
.thenReturn(testCallerService);
PolarisRouterServiceInstanceListSupplier polarisSupplier = new PolarisRouterServiceInstanceListSupplier(
delegate, routerAPI, requestInterceptors, null);
MockServerHttpRequest httpRequest = MockServerHttpRequest.get("/" + testCalleeService + "/users")
.header("k1", "v1")
.queryParam("userid", "zhangsan")
.build();
RequestDataContext requestDataContext = new RequestDataContext(new RequestData(httpRequest), "blue");
DefaultRequest request = new DefaultRequest(requestDataContext);
Assert.assertNull(polarisSupplier.get(request));
}
}
private void setTransitiveMetadata() {
if (initTransitiveMetadata.compareAndSet(false, true)) {
// mock transitive metadata

@ -0,0 +1,52 @@
/*
* 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.router.config;
import com.tencent.cloud.common.metadata.config.MetadataAutoConfiguration;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.router.feign.RouterLabelFeignInterceptor;
import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* test for {@link FeignAutoConfiguration}.
* @author dongyinuo
*/
public class FeignAutoConfigurationTest {
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
MetadataAutoConfiguration.class,
RouterAutoConfiguration.class,
PolarisContextAutoConfiguration.class,
FeignAutoConfiguration.class));
@Test
public void routerLabelInterceptor() {
contextRunner.run(context -> {
assertThat(context).hasSingleBean(FeignAutoConfiguration.class);
assertThat(context).hasSingleBean(RouterLabelFeignInterceptor.class);
});
}
}

@ -0,0 +1,91 @@
/*
* 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.router.config;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.loadbalancer.config.PolarisLoadBalancerAutoConfiguration;
import com.tencent.cloud.polaris.router.PolarisRouterServiceInstanceListSupplier;
import com.tencent.polaris.router.api.core.RouterAPI;
import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.ReactiveDiscoveryClient;
import org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClient;
import org.springframework.cloud.client.discovery.simple.SimpleDiscoveryProperties;
import org.springframework.cloud.client.discovery.simple.reactive.SimpleReactiveDiscoveryClient;
import org.springframework.cloud.client.discovery.simple.reactive.SimpleReactiveDiscoveryProperties;
import static org.assertj.core.api.Assertions.assertThat;
/**
* test for {@link LoadBalancerConfiguration}.
* @author dongyinuo
*/
public class LoadBalancerConfigurationTest {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner();
@Test
public void testLoadBalancerConfiguration() {
contextRunner.withConfiguration(AutoConfigurations.of(
PolarisLoadBalancerAutoConfiguration.class,
PolarisContextAutoConfiguration.class,
LoadBalancerConfiguration.class))
.run(context -> {
assertThat(context).hasSingleBean(LoadBalancerConfiguration.class);
});
}
@Test
public void testPolarisReactiveSupportConfiguration() {
contextRunner.withConfiguration(AutoConfigurations.of(
LoadBalancerConfiguration.PolarisReactiveSupportConfiguration.class,
PolarisLoadBalancerAutoConfiguration.class,
PolarisContextAutoConfiguration.class))
.withBean(SimpleReactiveDiscoveryProperties.class)
.withBean(SimpleReactiveDiscoveryClient.class)
.run(context -> {
assertThat(context).hasSingleBean(LoadBalancerConfiguration.PolarisReactiveSupportConfiguration.class);
assertThat(context).hasSingleBean(RouterAPI.class);
assertThat(context).hasSingleBean(ReactiveDiscoveryClient.class);
assertThat(context).hasSingleBean(PolarisRouterServiceInstanceListSupplier.class);
});
}
@Test
public void testPolarisBlockingSupportConfiguration() {
contextRunner.withConfiguration(AutoConfigurations.of(
PolarisLoadBalancerAutoConfiguration.class,
PolarisContextAutoConfiguration.class,
LoadBalancerConfiguration.PolarisBlockingSupportConfiguration.class
))
.withBean(SimpleDiscoveryProperties.class)
.withBean(SimpleDiscoveryClient.class)
.run(context -> {
assertThat(context).hasSingleBean(LoadBalancerConfiguration.PolarisBlockingSupportConfiguration.class);
assertThat(context).hasSingleBean(DiscoveryClient.class);
assertThat(context).hasSingleBean(RouterAPI.class);
assertThat(context).hasSingleBean(PolarisRouterServiceInstanceListSupplier.class);
});
}
}

@ -0,0 +1,62 @@
/*
* 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.router.config;
import com.tencent.cloud.common.metadata.config.MetadataAutoConfiguration;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
/**
* test for {@link RouterAutoConfiguration }.
* @author dongyinuo
*/
public class RouterAutoConfigurationTests {
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
TestRestTemplatesConfiguration.class,
MetadataAutoConfiguration.class,
RouterAutoConfiguration.class,
PolarisContextAutoConfiguration.class,
RouterAutoConfiguration.RouterLabelRestTemplateConfig.class));
@Test
public void testRouterLabelRestTemplateConfig() {
contextRunner.run(context -> {
assertThat(context).hasSingleBean(RouterAutoConfiguration.RouterLabelRestTemplateConfig.class);
});
}
@Configuration
static class TestRestTemplatesConfiguration {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
}

@ -0,0 +1,54 @@
/*
* 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.router.config.properties;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* test for {@link PolarisMetadataRouterProperties}.
*/
public class PolarisMetadataRouterPropertiesTest {
PolarisMetadataRouterProperties properties;
@Before
public void setUp() {
properties = new PolarisMetadataRouterProperties();
}
@Test
public void isEnabled() {
assertThat(properties.isEnabled()).isEqualTo(true);
}
@Test
public void setEnabled() {
properties.setEnabled(false);
assertThat(properties.isEnabled()).isEqualTo(false);
}
@Test
public void testToString() {
assertThat(properties.toString())
.isEqualTo("PolarisMetadataRouterProperties{enabled=true}");
}
}

@ -0,0 +1,56 @@
/*
* 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.router.config.properties;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* test for {@link PolarisNearByRouterProperties}.
*/
public class PolarisNearByRouterPropertiesTest {
PolarisNearByRouterProperties properties;
@Before
public void setUp() {
properties = new PolarisNearByRouterProperties();
}
@Test
public void isEnabled() {
assertThat(properties.isEnabled()).isEqualTo(true);
}
@Test
public void setEnabled() {
properties.setEnabled(false);
assertThat(properties.isEnabled()).isEqualTo(false);
}
@Test
public void testToString() {
assertThat(properties.toString())
.isEqualTo("PolarisNearByRouterProperties{enabled=true}");
}
}

@ -0,0 +1,55 @@
/*
* 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.router.config.properties;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* test for {@link PolarisRuleBasedRouterProperties}.
*/
public class PolarisRuleBasedRouterPropertiesTest {
PolarisRuleBasedRouterProperties properties;
@Before
public void setUp() {
properties = new PolarisRuleBasedRouterProperties();
}
@Test
public void isEnabled() {
assertThat(properties.isEnabled()).isEqualTo(true);
}
@Test
public void setEnabled() {
properties.setEnabled(false);
assertThat(properties.isEnabled()).isEqualTo(false);
}
@Test
public void testToString() {
assertThat(properties.toString())
.isEqualTo("PolarisNearByRouterProperties{enabled=true}");
}
}

@ -0,0 +1,65 @@
/*
* 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.router.endpoint;
import com.tencent.cloud.polaris.context.ServiceRuleManager;
import com.tencent.polaris.client.api.SDKContext;
import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
/**
* test for {@link PolarisRouterEndpointAutoConfiguration}.
* @author dongyinuo
*/
public class PolarisRouterEndpointAutoConfigurationTests {
private ServiceRuleManager serviceRuleManager;
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
TestServiceRuleManagerConfiguration.class,
PolarisRouterEndpointAutoConfiguration.class))
.withPropertyValues("endpoints.polaris-router.enabled=true");
@Test
public void polarisRouterEndpoint() {
contextRunner.run(context -> {
assertThat(context).hasSingleBean(PolarisRouterEndpointAutoConfiguration.class);
});
}
@Configuration
static class TestServiceRuleManagerConfiguration {
@Bean
public ServiceRuleManager serviceRuleManager(SDKContext sdkContext) {
return new ServiceRuleManager(sdkContext);
}
@Bean
public SDKContext sdkContext() {
return SDKContext.initContext();
}
}
}

@ -46,6 +46,7 @@ import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
@ -71,6 +72,8 @@ public class RouterLabelFeignInterceptorTest {
Collections.singletonList(routerLabelResolver),
staticMetadataManager, routerRuleLabelResolver, polarisContextProperties);
assertThat(routerLabelFeignInterceptor.getOrder()).isEqualTo(0);
// mock request template
RequestTemplate requestTemplate = new RequestTemplate();
String headerUidKey = "uid";

@ -0,0 +1,59 @@
/*
* 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.router.resttemplate;
import org.junit.Test;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerRequest;
import org.springframework.http.HttpRequest;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
/**
* test for {@link PolarisLoadBalancerRequest}.
* @author dongyinuo
*/
public class PolarisLoadBalancerRequestTests {
@Test
public void test() throws Exception {
String calleeService = "calleeService";
HttpRequest request = new RouterLabelRestTemplateInterceptorTest.MockedHttpRequest("http://" + calleeService + "/user/get");
MockLoadBalancerRequest mockLoadBalancerRequest = new MockLoadBalancerRequest();
PolarisLoadBalancerRequest<ServiceInstance> polarisLoadBalancerRequest = new PolarisLoadBalancerRequest<>(request, mockLoadBalancerRequest);
DefaultServiceInstance serviceInstance = new DefaultServiceInstance();
serviceInstance.setServiceId(calleeService);
ServiceInstance apply = polarisLoadBalancerRequest.apply(serviceInstance);
assertThat(apply.getServiceId()).isEqualTo(calleeService);
assertThat(polarisLoadBalancerRequest.getRequest()).isEqualTo(request);
assertThat(polarisLoadBalancerRequest.getDelegate()).isEqualTo(mockLoadBalancerRequest);
}
static class MockLoadBalancerRequest implements LoadBalancerRequest {
@Override
public Object apply(ServiceInstance instance) throws Exception {
return instance;
}
}
}

@ -40,7 +40,6 @@ import com.tencent.cloud.common.util.expresstion.SpringWebExpressionLabelUtils;
import com.tencent.cloud.polaris.context.config.PolarisContextProperties;
import com.tencent.cloud.polaris.router.RouterRuleLabelResolver;
import com.tencent.cloud.polaris.router.spi.SpringWebRouterLabelResolver;
import org.assertj.core.api.Assertions;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
@ -50,6 +49,7 @@ import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
@ -59,6 +59,7 @@ import org.springframework.http.client.ClientHttpResponse;
import org.springframework.mock.http.client.MockClientHttpResponse;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
@ -146,6 +147,8 @@ public class RouterLabelRestTemplateInterceptorTest {
ClientHttpResponse mockedResponse = new MockClientHttpResponse(new byte[] {}, HttpStatus.OK);
when(clientHttpRequestExecution.execute(eq(request), any())).thenReturn(mockedResponse);
assertThat(routerLabelRestTemplateInterceptor.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE);
routerLabelRestTemplateInterceptor.intercept(request, null, clientHttpRequestExecution);
verify(staticMetadataManager).getMergedStaticMetadata();
@ -155,11 +158,11 @@ public class RouterLabelRestTemplateInterceptorTest {
Map<String, String> headers = JacksonUtils.deserialize2Map(URLDecoder.decode(Objects.requireNonNull(request.getHeaders()
.get(RouterConstant.ROUTER_LABEL_HEADER)).get(0), "UTF-8"));
Assertions.assertThat("v1").isEqualTo(headers.get("k1"));
Assertions.assertThat("v22").isEqualTo(headers.get("k2"));
Assertions.assertThat("v4").isEqualTo(headers.get("k4"));
Assertions.assertThat("GET").isEqualTo(headers.get("${http.method}"));
Assertions.assertThat("/user/get").isEqualTo(headers.get("${http.uri}"));
assertThat("v1").isEqualTo(headers.get("k1"));
assertThat("v22").isEqualTo(headers.get("k2"));
assertThat("v4").isEqualTo(headers.get("k4"));
assertThat("GET").isEqualTo(headers.get("${http.method}"));
assertThat("/user/get").isEqualTo(headers.get("${http.uri}"));
String encodedLabelsContent;
try {
encodedLabelsContent = URLEncoder.encode(JacksonUtils.serialize2Json(routerLabels), UTF_8);
@ -167,7 +170,7 @@ public class RouterLabelRestTemplateInterceptorTest {
catch (UnsupportedEncodingException e) {
throw new RuntimeException("unsupported charset exception " + UTF_8);
}
Assertions.assertThat(mockedResponse.getHeaders().get(RouterConstant.ROUTER_LABEL_HEADER).get(0))
assertThat(mockedResponse.getHeaders().get(RouterConstant.ROUTER_LABEL_HEADER).get(0))
.isEqualTo(encodedLabelsContent);
}

@ -19,6 +19,7 @@
package com.tencent.cloud.polaris.router.scg;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
@ -45,17 +46,28 @@ import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import reactor.core.publisher.Mono;
import org.springframework.cloud.client.loadbalancer.LoadBalancerProperties;
import org.springframework.cloud.gateway.config.GatewayLoadBalancerProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.loadbalancer.core.NoopServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.core.ReactorServiceInstanceLoadBalancer;
import org.springframework.cloud.loadbalancer.core.RoundRobinLoadBalancer;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.cloud.loadbalancer.support.SimpleObjectProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR;
/**
* Test for ${@link PolarisReactiveLoadBalancerClientFilter}.
@ -88,7 +100,7 @@ public class PolarisReactiveLoadBalancerClientFilterTest {
mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString()))
.thenReturn(callerService);
MetadataContext metadataContext = Mockito.mock(MetadataContext.class);
MetadataContext metadataContext = mock(MetadataContext.class);
// mock transitive metadata
Map<String, String> transitiveLabels = new HashMap<>();
@ -142,4 +154,43 @@ public class PolarisReactiveLoadBalancerClientFilterTest {
Assert.assertEquals("v1", routerLabels.get("t1"));
Assert.assertEquals("v2", routerLabels.get("t2"));
}
@Test
public void testFilter01() throws Exception {
PolarisReactiveLoadBalancerClientFilter filter = new PolarisReactiveLoadBalancerClientFilter(loadBalancerClientFactory,
gatewayLoadBalancerProperties, staticMetadataManager, routerRuleLabelResolver,
Lists.newArrayList(routerLabelResolver), polarisContextProperties);
MockServerHttpRequest request = MockServerHttpRequest.get("/" + calleeService + "/users").build();
MockServerWebExchange exchange = new MockServerWebExchange.Builder(request).build();
// mock no lb
EmptyGatewayFilterChain chain = new EmptyGatewayFilterChain();
Mono<Void> ret = filter.filter(exchange, chain);
Assert.assertEquals(ret, Mono.empty());
// mock with lb
exchange = new MockServerWebExchange.Builder(request).build();
exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, new URI("https://" + calleeService + ":8091"));
exchange.getAttributes().put(GATEWAY_SCHEME_PREFIX_ATTR, "lb");
NoopServiceInstanceListSupplier serviceInstanceListSupplier = new NoopServiceInstanceListSupplier();
RoundRobinLoadBalancer roundRobinLoadBalancer = new RoundRobinLoadBalancer(new SimpleObjectProvider<>(serviceInstanceListSupplier), calleeService);
when(loadBalancerClientFactory.getInstance(calleeService, ReactorServiceInstanceLoadBalancer.class)).thenReturn(roundRobinLoadBalancer);
LoadBalancerProperties loadBalancerProperties = mock(LoadBalancerProperties.class);
when(loadBalancerProperties.getHint()).thenReturn(new HashMap<>());
when(loadBalancerClientFactory.getProperties(calleeService)).thenReturn(loadBalancerProperties);
filter.filter(exchange, chain);
}
static class EmptyGatewayFilterChain implements GatewayFilterChain {
@Override
public Mono<Void> filter(ServerWebExchange exchange) {
return Mono.empty();
}
}
}

Loading…
Cancel
Save