Optimize code style & unit test case (main). (#336)

pull/358/head
VOPEN.XYZ 2 years ago committed by GitHub
parent 4603c4a6b3
commit e5ad87e62e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -21,8 +21,9 @@
- [Fix the current limiting effect is that other requests cannot be processed when queuing at a constant speed](https://github.com/Tencent/spring-cloud-tencent/pull/316)
- [Fix config file format misspell](https://github.com/Tencent/spring-cloud-tencent/pull/319)
- [UT: improve test coverage for load balancer unit test](https://github.com/Tencent/spring-cloud-tencent/pull/325)
- [Feature: Optimize polaris load balancer test code format](https://github.com/Tencent/spring-cloud-tencent/pull/333)
- [optimize polaris load balancer test code format](https://github.com/Tencent/spring-cloud-tencent/pull/333)
- [feat:Add GitHub action of codecov.yml.](https://github.com/Tencent/spring-cloud-tencent/pull/328)
- [Feature: add spring cloud tencent logo](https://github.com/Tencent/spring-cloud-tencent/pull/329)
- [Feature: Optimize static metadata manager](https://github.com/Tencent/spring-cloud-tencent/pull/327)
- [test:update junit of metadata.](https://github.com/Tencent/spring-cloud-tencent/pull/340)
- [Optimize code style & unit test case](https://github.com/Tencent/spring-cloud-tencent/pull/336)

@ -32,8 +32,8 @@ import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
/**
* resolve custom transitive metadata from request.
*@author lepdou 2022-05-20
* Resolve custom transitive metadata from request.
* @author lepdou 2022-05-20
*/
public class CustomTransitiveMetadataResolver {

@ -48,7 +48,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT,
classes = EncodeTransferMedataScgFilterTest.TestApplication.class,
properties = { "spring.config.location = classpath:application-test.yml", "spring.main.web-application-type = reactive" })
properties = {"spring.config.location = classpath:application-test.yml", "spring.main.web-application-type = reactive"})
public class EncodeTransferMedataScgFilterTest {
@Autowired
@ -60,11 +60,17 @@ public class EncodeTransferMedataScgFilterTest {
@Test
public void testTransitiveMetadataFromApplicationConfig() throws UnsupportedEncodingException {
EncodeTransferMedataScgFilter filter = applicationContext.getBean(EncodeTransferMedataScgFilter.class);
// Mock Server Http Request
MockServerHttpRequest.BaseBuilder<?> builder = MockServerHttpRequest.get("");
MockServerWebExchange exchange = MockServerWebExchange.from(builder);
filter.filter(exchange, chain);
String metadataStr = exchange.getRequest().getHeaders().getFirst(MetadataConstant.HeaderName.CUSTOM_METADATA);
String decode = URLDecoder.decode(metadataStr, StandardCharsets.UTF_8.name());
// Check metadata str
String metadata = exchange.getRequest().getHeaders().getFirst(MetadataConstant.HeaderName.CUSTOM_METADATA);
Assertions.assertThat(metadata).isNotNull();
String decode = URLDecoder.decode(metadata, StandardCharsets.UTF_8.name());
Map<String, String> transitiveMap = JacksonUtils.deserialize2Map(decode);
Assertions.assertThat(transitiveMap.size()).isEqualTo(1);
Assertions.assertThat(transitiveMap.get("b")).isEqualTo("2");

@ -27,7 +27,6 @@ import com.netflix.zuul.context.RequestContext;
import com.tencent.cloud.common.constant.MetadataConstant;
import com.tencent.cloud.common.util.JacksonUtils;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -42,19 +41,21 @@ import org.springframework.test.context.junit4.SpringRunner;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* Test for {@link EncodeTransferMetadataZuulFilter}.
*
* @author quan
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT,
classes = EncodeTransferMetadataZuulFilterTest.TestApplication.class,
properties = { "spring.config.location = classpath:application-test.yml", "spring.main.web-application-type = reactive" })
properties = {"spring.config.location = classpath:application-test.yml", "spring.main.web-application-type = reactive"})
public class EncodeTransferMetadataZuulFilterTest {
@Autowired
private ApplicationContext applicationContext;
private MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest();
private final MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest();
@Before
public void init() {
@ -69,11 +70,13 @@ public class EncodeTransferMetadataZuulFilterTest {
filter.run();
final RequestContext ctx = RequestContext.getCurrentContext();
Map<String, String> zuulRequestHeaders = ctx.getZuulRequestHeaders();
String metaData = zuulRequestHeaders.get(MetadataConstant.HeaderName.CUSTOM_METADATA.toLowerCase());
String decode = URLDecoder.decode(metaData, StandardCharsets.UTF_8.name());
String metadata = zuulRequestHeaders.get(MetadataConstant.HeaderName.CUSTOM_METADATA.toLowerCase());
Assertions.assertThat(metadata).isNotNull();
String decode = URLDecoder.decode(metadata, StandardCharsets.UTF_8.name());
Map<String, String> transitiveMap = JacksonUtils.deserialize2Map(decode);
Assertions.assertThat(transitiveMap.size()).isEqualTo(1);
Assert.assertEquals(transitiveMap.get("b"), "2");
Assertions.assertThat(transitiveMap.get("b")).isEqualTo("2");
}
@SpringBootApplication

@ -102,6 +102,12 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>

@ -32,9 +32,9 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* @author : wh
* @date : 2022/6/21 21:34
* @description: Auto configuration PolarisRestTemplateAutoConfiguration
* Auto configuration PolarisRestTemplateAutoConfiguration .
*
* @author wh 2022/6/21
*/
@ConditionalOnProperty(value = "spring.cloud.polaris.circuitbreaker.enabled",
havingValue = "true", matchIfMissing = true)
@ -44,13 +44,16 @@ public class PolarisRestTemplateAutoConfiguration {
@Bean
@ConditionalOnBean(RestTemplate.class)
public PolarisRestTemplateResponseErrorHandler polarisRestTemplateResponseErrorHandler(ConsumerAPI consumerAPI, @Autowired(required = false) PolarisResponseErrorHandler polarisResponseErrorHandler) {
public PolarisRestTemplateResponseErrorHandler polarisRestTemplateResponseErrorHandler(
ConsumerAPI consumerAPI, @Autowired(required = false) PolarisResponseErrorHandler polarisResponseErrorHandler) {
return new PolarisRestTemplateResponseErrorHandler(consumerAPI, polarisResponseErrorHandler);
}
@Bean
@ConditionalOnBean(RestTemplate.class)
public PolarisRestTemplateModifier polarisRestTemplateBeanPostProcessor(PolarisRestTemplateResponseErrorHandler restTemplateResponseErrorHandler) {
public PolarisRestTemplateModifier polarisRestTemplateBeanPostProcessor(
PolarisRestTemplateResponseErrorHandler restTemplateResponseErrorHandler) {
return new PolarisRestTemplateModifier(restTemplateResponseErrorHandler);
}
}

@ -20,9 +20,9 @@ package com.tencent.cloud.polaris.circuitbreaker.resttemplate;
import org.springframework.web.client.ResponseErrorHandler;
/**
* @author : wh
* @date : 2022/6/21 19:12
* @description: errorHandler {@link ResponseErrorHandler}
* Polaris Response Error Handler Definition Of {@link ResponseErrorHandler}.
*
* @author wh 2022/6/21
*/
public interface PolarisResponseErrorHandler extends ResponseErrorHandler {

@ -28,10 +28,10 @@ import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;
/**
* @author : wh
* @date : 2022/6/21 21:20
* @description: auto configuration RestTemplate Find the RestTemplate bean annotated with {@link LoadBalanced} and replace {@link org.springframework.web.client.ResponseErrorHandler}
* with {@link PolarisRestTemplateResponseErrorHandler}
* Auto configuration RestTemplate, Find the RestTemplate bean annotated with {@link LoadBalanced},
* then replace {@link org.springframework.web.client.ResponseErrorHandler} with {@link PolarisRestTemplateResponseErrorHandler} .
*
* @author wh 2022/6/21
*/
public class PolarisRestTemplateModifier implements ApplicationContextAware, SmartInitializingSingleton {

@ -29,24 +29,25 @@ import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.api.pojo.RetStatus;
import com.tencent.polaris.api.pojo.ServiceKey;
import com.tencent.polaris.api.rpc.ServiceCallResult;
import com.tencent.polaris.api.utils.StringUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.web.client.ResponseErrorHandler;
/**
* @author : wh
* @date : 2022/6/21 17:25
* @description: Extend ResponseErrorHandler to get request information
* Extend ResponseErrorHandler to get request information.
*
* @author wh 2022/6/21
*/
public class PolarisRestTemplateResponseErrorHandler implements ResponseErrorHandler {
private static final Logger LOG = LoggerFactory.getLogger(PolarisRestTemplateResponseErrorHandler.class);
private static final String FileName = "connection";
private static final String FIELD_NAME = "connection";
private final ConsumerAPI consumerAPI;
@ -59,12 +60,12 @@ public class PolarisRestTemplateResponseErrorHandler implements ResponseErrorHan
}
@Override
public boolean hasError(ClientHttpResponse response) {
public boolean hasError(@NonNull ClientHttpResponse response) {
return true;
}
@Override
public void handleError(ClientHttpResponse response) throws IOException {
public void handleError(@NonNull ClientHttpResponse response) throws IOException {
if (Objects.nonNull(polarisResponseErrorHandler)) {
if (polarisResponseErrorHandler.hasError(response)) {
polarisResponseErrorHandler.handleError(response);
@ -72,12 +73,22 @@ public class PolarisRestTemplateResponseErrorHandler implements ResponseErrorHan
}
}
public void handleError(URI url, HttpMethod method, ClientHttpResponse response) throws IOException {
ServiceCallResult resultRequest = null;
@Override
public void handleError(@NonNull URI url, @NonNull HttpMethod method, @NonNull ClientHttpResponse response) throws IOException {
ServiceCallResult resultRequest = createServiceCallResult(url);
try {
resultRequest = builderServiceCallResult(url, response);
HttpURLConnection connection = (HttpURLConnection) ReflectionUtils.getFieldValue(response, FIELD_NAME);
if (connection != null) {
URL realURL = connection.getURL();
resultRequest.setHost(realURL.getHost());
resultRequest.setPort(realURL.getPort());
}
if (response.getStatusCode().value() > 500) {
resultRequest.setRetStatus(RetStatus.RetFail);
}
}
catch (IOException e) {
catch (Exception e) {
LOG.error("Will report response of {} url {}", response, url, e);
throw e;
}
@ -86,7 +97,7 @@ public class PolarisRestTemplateResponseErrorHandler implements ResponseErrorHan
}
}
private ServiceCallResult builderServiceCallResult(URI uri, ClientHttpResponse response) throws IOException {
private ServiceCallResult createServiceCallResult(URI uri) {
ServiceCallResult resultRequest = new ServiceCallResult();
String serviceName = uri.getHost();
resultRequest.setService(serviceName);
@ -98,13 +109,6 @@ public class PolarisRestTemplateResponseErrorHandler implements ResponseErrorHan
if (StringUtils.isNotBlank(sourceNamespace) && StringUtils.isNotBlank(sourceService)) {
resultRequest.setCallerService(new ServiceKey(sourceNamespace, sourceService));
}
HttpURLConnection connection = (HttpURLConnection) ReflectionUtils.getFieldValue(response, FileName);
URL url = connection.getURL();
resultRequest.setHost(url.getHost());
resultRequest.setPort(url.getPort());
if (response.getStatusCode().value() > 500) {
resultRequest.setRetStatus(RetStatus.RetFail);
}
return resultRequest;
}

@ -0,0 +1,72 @@
/*
* 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.circuitbreaker;
import com.tencent.cloud.polaris.circuitbreaker.config.PolarisRestTemplateAutoConfiguration;
import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisRestTemplateModifier;
import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisRestTemplateResponseErrorHandler;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
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 PolarisRestTemplateAutoConfiguration} .
*
* @author <a href="mailto:iskp.me@gmail.com">Palmer Xu</a> 2022-06-28
*/
public class PolarisRestTemplateAutoConfigurationTest {
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
PolarisRestTemplateAutoConfigurationTester.class,
PolarisContextAutoConfiguration.class,
PolarisRestTemplateAutoConfiguration.class))
.withPropertyValues("spring.cloud.polaris.circuitbreaker.enabled=true");
@Test
public void testInitialization() {
this.contextRunner
.run(context -> {
assertThat(context).hasSingleBean(PolarisRestTemplateModifier.class);
assertThat(context).hasSingleBean(PolarisRestTemplateResponseErrorHandler.class);
});
}
@Configuration
@EnableAutoConfiguration
@AutoConfigureBefore(PolarisRestTemplateAutoConfiguration.class)
static class PolarisRestTemplateAutoConfigurationTester {
@Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
}
}

@ -15,14 +15,13 @@
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.circuitbreaker;
package com.tencent.cloud.polaris.circuitbreaker.resttemplate;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisRestTemplateResponseErrorHandler;
import com.tencent.polaris.api.core.ConsumerAPI;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -36,9 +35,9 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author : wh
* @date : 2022/6/22 09:00
* @description: Test for {@link PolarisRestTemplateResponseErrorHandler}.
* Test For {@link PolarisRestTemplateResponseErrorHandler}.
*
* @author wh 2022/6/22
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = PolarisRestTemplateResponseErrorHandlerTest.TestApplication.class,

@ -15,7 +15,7 @@
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.circuitbreaker;
package com.tencent.cloud.polaris.circuitbreaker.resttemplate;
import java.io.IOException;
import java.io.InputStream;
@ -29,9 +29,9 @@ import org.springframework.util.StringUtils;
/**
* @author : wh
* @date : 2022/6/22 09:00
* @description: mock {@link org.springframework.http.client.SimpleClientHttpResponse}
* Mock Test for {@link AbstractClientHttpResponse}.
*
* @author wh 2022/6/22
*/
public class SimpleClientHttpResponseTest extends AbstractClientHttpResponse {
Loading…
Cancel
Save