refactor:update to junit 5. (#866)

pull/871/head
Haotian Zhang 2 years ago committed by GitHub
parent b524d1c8e8
commit 3f70d7bd1d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -8,3 +8,4 @@
- [feature:add PolarisRateLimiterLimitedFallback spi.](https://github.com/Tencent/spring-cloud-tencent/pull/857) - [feature:add PolarisRateLimiterLimitedFallback spi.](https://github.com/Tencent/spring-cloud-tencent/pull/857)
- [fix:fix the error capture of rate limit exception.](https://github.com/Tencent/spring-cloud-tencent/pull/860) - [fix:fix the error capture of rate limit exception.](https://github.com/Tencent/spring-cloud-tencent/pull/860)
- [feat:enable stat reporting as default.](https://github.com/Tencent/spring-cloud-tencent/pull/863) - [feat:enable stat reporting as default.](https://github.com/Tencent/spring-cloud-tencent/pull/863)
- [refactor:update to junit 5.](https://github.com/Tencent/spring-cloud-tencent/pull/866)

@ -197,13 +197,6 @@
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<inherited>true</inherited> <inherited>true</inherited>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit4</artifactId>
<version>2.22.2</version>
</dependency>
</dependencies>
<configuration> <configuration>
<forkCount>1</forkCount> <forkCount>1</forkCount>
<reuseForks>false</reuseForks> <reuseForks>false</reuseForks>

@ -26,8 +26,7 @@ import java.util.stream.Collectors;
import com.tencent.cloud.metadata.core.EncodeTransferMedataFeignInterceptor; import com.tencent.cloud.metadata.core.EncodeTransferMedataFeignInterceptor;
import com.tencent.cloud.metadata.core.EncodeTransferMedataRestTemplateInterceptor; import com.tencent.cloud.metadata.core.EncodeTransferMedataRestTemplateInterceptor;
import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ApplicationContextRunner;
@ -38,6 +37,8 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
/** /**
* Test for {@link MetadataTransferAutoConfiguration}. * Test for {@link MetadataTransferAutoConfiguration}.
* *
@ -54,15 +55,12 @@ public class MetadataTransferAutoConfigurationTest {
public void test1() { public void test1() {
this.applicationContextRunner.withConfiguration(AutoConfigurations.of(MetadataTransferAutoConfiguration.class)) this.applicationContextRunner.withConfiguration(AutoConfigurations.of(MetadataTransferAutoConfiguration.class))
.run(context -> { .run(context -> {
Assertions.assertThat(context).hasSingleBean( assertThat(context).hasSingleBean(MetadataTransferAutoConfiguration.MetadataTransferFeignInterceptorConfig.class);
MetadataTransferAutoConfiguration.MetadataTransferFeignInterceptorConfig.class); assertThat(context).hasSingleBean(EncodeTransferMedataFeignInterceptor.class);
Assertions.assertThat(context).hasSingleBean(EncodeTransferMedataFeignInterceptor.class); assertThat(context).hasSingleBean(MetadataTransferAutoConfiguration.MetadataTransferRestTemplateConfig.class);
Assertions.assertThat(context) assertThat(context).hasSingleBean(EncodeTransferMedataRestTemplateInterceptor.class);
.hasSingleBean(MetadataTransferAutoConfiguration.MetadataTransferRestTemplateConfig.class); assertThat(context).hasSingleBean(MetadataTransferAutoConfiguration.MetadataTransferScgFilterConfig.class);
Assertions.assertThat(context).hasSingleBean(EncodeTransferMedataRestTemplateInterceptor.class); assertThat(context).hasSingleBean(GlobalFilter.class);
Assertions.assertThat(context)
.hasSingleBean(MetadataTransferAutoConfiguration.MetadataTransferScgFilterConfig.class);
Assertions.assertThat(context).hasSingleBean(GlobalFilter.class);
}); });
} }
@ -73,20 +71,19 @@ public class MetadataTransferAutoConfigurationTest {
.withConfiguration( .withConfiguration(
AutoConfigurations.of(MetadataTransferAutoConfiguration.class, RestTemplateConfiguration.class)) AutoConfigurations.of(MetadataTransferAutoConfiguration.class, RestTemplateConfiguration.class))
.run(context -> { .run(context -> {
Assertions.assertThat(context) assertThat(context).hasSingleBean(EncodeTransferMedataFeignInterceptor.class);
.hasSingleBean(EncodeTransferMedataFeignInterceptor.class);
EncodeTransferMedataRestTemplateInterceptor encodeTransferMedataRestTemplateInterceptor = context.getBean(EncodeTransferMedataRestTemplateInterceptor.class); EncodeTransferMedataRestTemplateInterceptor encodeTransferMedataRestTemplateInterceptor = context.getBean(EncodeTransferMedataRestTemplateInterceptor.class);
Map<String, RestTemplate> restTemplateMap = context.getBeansOfType(RestTemplate.class); Map<String, RestTemplate> restTemplateMap = context.getBeansOfType(RestTemplate.class);
Assertions.assertThat(restTemplateMap.size()).isEqualTo(2); assertThat(restTemplateMap.size()).isEqualTo(2);
for (String beanName : Arrays.asList("restTemplate", "loadBalancedRestTemplate")) { for (String beanName : Arrays.asList("restTemplate", "loadBalancedRestTemplate")) {
RestTemplate restTemplate = restTemplateMap.get(beanName); RestTemplate restTemplate = restTemplateMap.get(beanName);
Assertions.assertThat(restTemplate).isNotNull(); assertThat(restTemplate).isNotNull();
List<ClientHttpRequestInterceptor> encodeTransferMedataFeignInterceptorList = restTemplate.getInterceptors() List<ClientHttpRequestInterceptor> encodeTransferMedataFeignInterceptorList = restTemplate.getInterceptors()
.stream() .stream()
.filter(interceptor -> Objects.equals(interceptor, encodeTransferMedataRestTemplateInterceptor)) .filter(interceptor -> Objects.equals(interceptor, encodeTransferMedataRestTemplateInterceptor))
.collect(Collectors.toList()); .collect(Collectors.toList());
//EncodeTransferMetadataFeignInterceptor is not added repeatedly //EncodeTransferMetadataFeignInterceptor is not added repeatedly
Assertions.assertThat(encodeTransferMedataFeignInterceptorList.size()).isEqualTo(1); assertThat(encodeTransferMedataFeignInterceptorList.size()).isEqualTo(1);
} }
}); });
} }

@ -19,13 +19,14 @@ package com.tencent.cloud.metadata.core;
import java.util.Map; import java.util.Map;
import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.mock.web.server.MockServerWebExchange;
import static org.assertj.core.api.Assertions.assertThat;
/** /**
* Test for {@link CustomTransitiveMetadataResolver}. * Test for {@link CustomTransitiveMetadataResolver}.
* *
@ -39,8 +40,8 @@ public class CustomTransitiveMetadataResolverTest {
builder.header("X-SCT-Metadata-Transitive-a", "test"); builder.header("X-SCT-Metadata-Transitive-a", "test");
MockServerWebExchange exchange = MockServerWebExchange.from(builder); MockServerWebExchange exchange = MockServerWebExchange.from(builder);
Map<String, String> resolve = CustomTransitiveMetadataResolver.resolve(exchange); Map<String, String> resolve = CustomTransitiveMetadataResolver.resolve(exchange);
Assertions.assertThat(resolve.size()).isEqualTo(1); assertThat(resolve.size()).isEqualTo(1);
Assertions.assertThat(resolve.get("a")).isEqualTo("test"); assertThat(resolve.get("a")).isEqualTo("test");
} }
@Test @Test
@ -49,8 +50,8 @@ public class CustomTransitiveMetadataResolverTest {
builder.header("X-Polaris-Metadata-Transitive-a", "test"); builder.header("X-Polaris-Metadata-Transitive-a", "test");
MockServerWebExchange exchange = MockServerWebExchange.from(builder); MockServerWebExchange exchange = MockServerWebExchange.from(builder);
Map<String, String> resolve = CustomTransitiveMetadataResolver.resolve(exchange); Map<String, String> resolve = CustomTransitiveMetadataResolver.resolve(exchange);
Assertions.assertThat(resolve.size()).isEqualTo(1); assertThat(resolve.size()).isEqualTo(1);
Assertions.assertThat(resolve.get("a")).isEqualTo("test"); assertThat(resolve.get("a")).isEqualTo("test");
} }
@Test @Test
@ -58,8 +59,8 @@ public class CustomTransitiveMetadataResolverTest {
MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("X-SCT-Metadata-Transitive-a", "test"); request.addHeader("X-SCT-Metadata-Transitive-a", "test");
Map<String, String> resolve = CustomTransitiveMetadataResolver.resolve(request); Map<String, String> resolve = CustomTransitiveMetadataResolver.resolve(request);
Assertions.assertThat(resolve.size()).isEqualTo(1); assertThat(resolve.size()).isEqualTo(1);
Assertions.assertThat(resolve.get("a")).isEqualTo("test"); assertThat(resolve.get("a")).isEqualTo("test");
} }
@Test @Test
@ -67,7 +68,7 @@ public class CustomTransitiveMetadataResolverTest {
MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("X-Polaris-Metadata-Transitive-a", "test"); request.addHeader("X-Polaris-Metadata-Transitive-a", "test");
Map<String, String> resolve = CustomTransitiveMetadataResolver.resolve(request); Map<String, String> resolve = CustomTransitiveMetadataResolver.resolve(request);
Assertions.assertThat(resolve.size()).isEqualTo(1); assertThat(resolve.size()).isEqualTo(1);
Assertions.assertThat(resolve.get("a")).isEqualTo("test"); assertThat(resolve.get("a")).isEqualTo("test");
} }
} }

@ -19,20 +19,20 @@ package com.tencent.cloud.metadata.core;
import com.tencent.cloud.common.constant.MetadataConstant; import com.tencent.cloud.common.constant.MetadataConstant;
import com.tencent.cloud.common.metadata.config.MetadataLocalProperties; import com.tencent.cloud.common.metadata.config.MetadataLocalProperties;
import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import reactor.core.publisher.Mono; import reactor.core.publisher.Mono;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilterChain; import org.springframework.web.server.WebFilterChain;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.MOCK; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.MOCK;
/** /**
@ -40,7 +40,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@RunWith(SpringRunner.class) @ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = MOCK, @SpringBootTest(webEnvironment = MOCK,
classes = DecodeTransferMetadataServletFilterTest.TestApplication.class, classes = DecodeTransferMetadataServletFilterTest.TestApplication.class,
properties = {"spring.config.location = classpath:application-test.yml"}) properties = {"spring.config.location = classpath:application-test.yml"})
@ -51,14 +51,14 @@ public class DecodeTransferMetadataReactiveFilterTest {
private DecodeTransferMetadataReactiveFilter metadataReactiveFilter; private DecodeTransferMetadataReactiveFilter metadataReactiveFilter;
@Before @BeforeEach
public void setUp() { public void setUp() {
this.metadataReactiveFilter = new DecodeTransferMetadataReactiveFilter(); this.metadataReactiveFilter = new DecodeTransferMetadataReactiveFilter();
} }
@Test @Test
public void test1() { public void test1() {
Assertions.assertThat(this.metadataReactiveFilter.getOrder()) assertThat(this.metadataReactiveFilter.getOrder())
.isEqualTo(MetadataConstant.OrderConstant.WEB_FILTER_ORDER); .isEqualTo(MetadataConstant.OrderConstant.WEB_FILTER_ORDER);
} }
@ -74,8 +74,8 @@ public class DecodeTransferMetadataReactiveFilterTest {
ServerWebExchange exchange = MockServerWebExchange.from(request); ServerWebExchange exchange = MockServerWebExchange.from(request);
metadataReactiveFilter.filter(exchange, webFilterChain); metadataReactiveFilter.filter(exchange, webFilterChain);
Assertions.assertThat(metadataLocalProperties.getContent().get("a")).isEqualTo("1"); assertThat(metadataLocalProperties.getContent().get("a")).isEqualTo("1");
Assertions.assertThat(metadataLocalProperties.getContent().get("b")).isEqualTo("2"); assertThat(metadataLocalProperties.getContent().get("b")).isEqualTo("2");
Assertions.assertThat(metadataLocalProperties.getContent().get("c")).isNull(); assertThat(metadataLocalProperties.getContent().get("c")).isNull();
} }
} }

@ -23,17 +23,17 @@ import com.tencent.cloud.common.constant.MetadataConstant;
import com.tencent.cloud.common.metadata.config.MetadataLocalProperties; import com.tencent.cloud.common.metadata.config.MetadataLocalProperties;
import jakarta.servlet.FilterChain; import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException; import jakarta.servlet.ServletException;
import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/** /**
@ -41,7 +41,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@RunWith(SpringRunner.class) @ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = RANDOM_PORT, @SpringBootTest(webEnvironment = RANDOM_PORT,
classes = DecodeTransferMetadataServletFilterTest.TestApplication.class, classes = DecodeTransferMetadataServletFilterTest.TestApplication.class,
properties = {"spring.config.location = classpath:application-test.yml"}) properties = {"spring.config.location = classpath:application-test.yml"})
@ -65,9 +65,9 @@ public class DecodeTransferMetadataServletFilterTest {
request.addHeader(MetadataConstant.HeaderName.CUSTOM_METADATA, "{\"c\": \"3\"}"); request.addHeader(MetadataConstant.HeaderName.CUSTOM_METADATA, "{\"c\": \"3\"}");
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
metadataServletFilter.doFilter(request, response, filterChain); metadataServletFilter.doFilter(request, response, filterChain);
Assertions.assertThat(metadataLocalProperties.getContent().get("a")).isEqualTo("1"); assertThat(metadataLocalProperties.getContent().get("a")).isEqualTo("1");
Assertions.assertThat(metadataLocalProperties.getContent().get("b")).isEqualTo("2"); assertThat(metadataLocalProperties.getContent().get("b")).isEqualTo("2");
Assertions.assertThat(metadataLocalProperties.getContent().get("c")).isNull(); assertThat(metadataLocalProperties.getContent().get("c")).isNull();
} }
@SpringBootApplication @SpringBootApplication

@ -23,9 +23,8 @@ import com.tencent.cloud.common.metadata.MetadataContextHolder;
import com.tencent.cloud.common.metadata.config.MetadataLocalProperties; import com.tencent.cloud.common.metadata.config.MetadataLocalProperties;
import feign.RequestInterceptor; import feign.RequestInterceptor;
import feign.RequestTemplate; import feign.RequestTemplate;
import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
@ -33,10 +32,11 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT;
/** /**
@ -44,7 +44,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@RunWith(SpringRunner.class) @ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = DEFINED_PORT, @SpringBootTest(webEnvironment = DEFINED_PORT,
classes = EncodeTransferMedataFeignInterceptorTest.TestApplication.class, classes = EncodeTransferMedataFeignInterceptorTest.TestApplication.class,
properties = {"server.port=8081", "spring.config.location = classpath:application-test.yml"}) properties = {"server.port=8081", "spring.config.location = classpath:application-test.yml"})
@ -59,9 +59,9 @@ public class EncodeTransferMedataFeignInterceptorTest {
@Test @Test
public void testTransitiveMetadataFromApplicationConfig() { public void testTransitiveMetadataFromApplicationConfig() {
String metadata = testFeign.test(); String metadata = testFeign.test();
Assertions.assertThat(metadata).isEqualTo("2"); assertThat(metadata).isEqualTo("2");
Assertions.assertThat(metadataLocalProperties.getContent().get("a")).isEqualTo("1"); assertThat(metadataLocalProperties.getContent().get("a")).isEqualTo("1");
Assertions.assertThat(metadataLocalProperties.getContent().get("b")).isEqualTo("2"); assertThat(metadataLocalProperties.getContent().get("b")).isEqualTo("2");
} }
@SpringBootApplication @SpringBootApplication

@ -19,9 +19,8 @@ package com.tencent.cloud.metadata.core;
import com.tencent.cloud.common.metadata.MetadataContext; import com.tencent.cloud.common.metadata.MetadataContext;
import com.tencent.cloud.common.metadata.MetadataContextHolder; import com.tencent.cloud.common.metadata.MetadataContextHolder;
import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
@ -31,11 +30,12 @@ import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity; import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod; import org.springframework.http.HttpMethod;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/** /**
@ -43,7 +43,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@RunWith(SpringRunner.class) @ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = RANDOM_PORT, @SpringBootTest(webEnvironment = RANDOM_PORT,
classes = EncodeTransferMedataRestTemplateInterceptorTest.TestApplication.class, classes = EncodeTransferMedataRestTemplateInterceptorTest.TestApplication.class,
properties = {"spring.config.location = classpath:application-test.yml"}) properties = {"spring.config.location = classpath:application-test.yml"})
@ -62,7 +62,7 @@ public class EncodeTransferMedataRestTemplateInterceptorTest {
String metadata = restTemplate String metadata = restTemplate
.exchange("http://localhost:" + localServerPort + "/test", HttpMethod.GET, httpEntity, String.class) .exchange("http://localhost:" + localServerPort + "/test", HttpMethod.GET, httpEntity, String.class)
.getBody(); .getBody();
Assertions.assertThat(metadata).isEqualTo("2"); assertThat(metadata).isEqualTo("2");
} }
@SpringBootApplication @SpringBootApplication

@ -23,9 +23,8 @@ import java.util.Map;
import com.tencent.cloud.common.constant.MetadataConstant; import com.tencent.cloud.common.constant.MetadataConstant;
import com.tencent.cloud.common.util.JacksonUtils; import com.tencent.cloud.common.util.JacksonUtils;
import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -35,9 +34,10 @@ import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit.jupiter.SpringExtension;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8; import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/** /**
@ -45,7 +45,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* *
* @author quan * @author quan
*/ */
@RunWith(SpringRunner.class) @ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = EncodeTransferMedataScgFilterTest.TestApplication.class, @SpringBootTest(webEnvironment = RANDOM_PORT, classes = EncodeTransferMedataScgFilterTest.TestApplication.class,
properties = {"spring.config.location = classpath:application-test.yml", properties = {"spring.config.location = classpath:application-test.yml",
"spring.main.web-application-type = reactive"}) "spring.main.web-application-type = reactive"})
@ -66,8 +66,8 @@ public class EncodeTransferMedataScgFilterTest {
String metadataStr = exchange.getRequest().getHeaders().getFirst(MetadataConstant.HeaderName.CUSTOM_METADATA); String metadataStr = exchange.getRequest().getHeaders().getFirst(MetadataConstant.HeaderName.CUSTOM_METADATA);
String decode = URLDecoder.decode(metadataStr, UTF_8); String decode = URLDecoder.decode(metadataStr, UTF_8);
Map<String, String> transitiveMap = JacksonUtils.deserialize2Map(decode); Map<String, String> transitiveMap = JacksonUtils.deserialize2Map(decode);
Assertions.assertThat(transitiveMap.size()).isEqualTo(1); assertThat(transitiveMap.size()).isEqualTo(1);
Assertions.assertThat(transitiveMap.get("b")).isEqualTo("2"); assertThat(transitiveMap.get("b")).isEqualTo("2");
} }
@SpringBootApplication @SpringBootApplication

@ -23,16 +23,16 @@ import java.util.Map;
import com.tencent.cloud.common.metadata.MetadataContext; import com.tencent.cloud.common.metadata.MetadataContext;
import com.tencent.cloud.common.metadata.MetadataContextHolder; import com.tencent.cloud.common.metadata.MetadataContextHolder;
import com.tencent.cloud.common.util.JacksonUtils; import com.tencent.cloud.common.util.JacksonUtils;
import org.junit.AfterClass; import org.junit.jupiter.api.AfterAll;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/** /**
@ -40,13 +40,13 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* *
* @author lingxiao.wlx * @author lingxiao.wlx
*/ */
@RunWith(SpringRunner.class) @ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = RANDOM_PORT, @SpringBootTest(webEnvironment = RANDOM_PORT,
classes = DecodeTransferMetadataServletFilterTest.TestApplication.class, classes = DecodeTransferMetadataServletFilterTest.TestApplication.class,
properties = {"spring.config.location = classpath:application-test.yml"}) properties = {"spring.config.location = classpath:application-test.yml"})
public class TransHeadersTransferTest { public class TransHeadersTransferTest {
@AfterClass @AfterAll
public static void afterClass() { static void afterAll() {
MetadataContextHolder.remove(); MetadataContextHolder.remove();
} }
@ -60,9 +60,9 @@ public class TransHeadersTransferTest {
request.addHeader("header3", "3"); request.addHeader("header3", "3");
TransHeadersTransfer.transfer(request); TransHeadersTransfer.transfer(request);
Map<String, String> transHeadersKV = MetadataContextHolder.get().getTransHeadersKV(); Map<String, String> transHeadersKV = MetadataContextHolder.get().getTransHeadersKV();
Assertions.assertEquals(transHeadersKV.get("header1"), "1"); assertThat(transHeadersKV.get("header1")).isEqualTo("1");
Assertions.assertEquals(transHeadersKV.get("header2"), "2"); assertThat(transHeadersKV.get("header2")).isEqualTo("2");
Assertions.assertEquals(transHeadersKV.get("header3"), "3"); assertThat(transHeadersKV.get("header3")).isEqualTo("3");
} }
@Test @Test
@ -79,8 +79,8 @@ public class TransHeadersTransferTest {
MockServerHttpRequest request = builder.build(); MockServerHttpRequest request = builder.build();
TransHeadersTransfer.transfer(request); TransHeadersTransfer.transfer(request);
Map<String, String> transHeadersKV = MetadataContextHolder.get().getTransHeadersKV(); Map<String, String> transHeadersKV = MetadataContextHolder.get().getTransHeadersKV();
Assertions.assertEquals(transHeadersKV.get("header1"), JacksonUtils.serialize2Json(header1)); assertThat(transHeadersKV.get("header1")).isEqualTo(JacksonUtils.serialize2Json(header1));
Assertions.assertEquals(transHeadersKV.get("header2"), JacksonUtils.serialize2Json(header2)); assertThat(transHeadersKV.get("header2")).isEqualTo(JacksonUtils.serialize2Json(header2));
Assertions.assertEquals(transHeadersKV.get("header3"), JacksonUtils.serialize2Json(header3)); assertThat(transHeadersKV.get("header3")).isEqualTo(JacksonUtils.serialize2Json(header3));
} }
} }

@ -19,7 +19,7 @@ package com.tencent.cloud.polaris.circuitbreaker.config;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementAutoConfiguration; import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementAutoConfiguration;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ApplicationContextRunner;

@ -19,7 +19,7 @@ package com.tencent.cloud.polaris.circuitbreaker.config;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementAutoConfiguration; import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementAutoConfiguration;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ApplicationContextRunner;

@ -19,6 +19,7 @@
package com.tencent.cloud.polaris.config.listener; package com.tencent.cloud.polaris.config.listener;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
@ -77,9 +78,9 @@ public final class PolarisConfigChangeEventListener implements ApplicationListen
ConfigurableEnvironment environment = context.getEnvironment(); ConfigurableEnvironment environment = context.getEnvironment();
Map<String, Object> ret = loadEnvironmentProperties(environment); Map<String, Object> ret = loadEnvironmentProperties(environment);
Map<String, ConfigPropertyChangeInfo> changes = merge(ret); Map<String, ConfigPropertyChangeInfo> changes = merge(ret);
ConfigChangeSpringEvent configChangeSpringEvent = new ConfigChangeSpringEvent(Maps.newHashMap(changes)); ConfigChangeSpringEvent configChangeSpringEvent = new ConfigChangeSpringEvent(new HashMap<>(changes));
eventPublisher.publishEvent(configChangeSpringEvent); eventPublisher.publishEvent(configChangeSpringEvent);
fireConfigChange(changes.keySet(), Maps.newHashMap(changes)); fireConfigChange(changes.keySet(), new HashMap<>(changes));
changes.clear(); changes.clear();
} }
} }

@ -29,22 +29,22 @@ import com.tencent.cloud.polaris.config.config.PolarisConfigProperties;
import com.tencent.cloud.polaris.context.config.PolarisContextProperties; import com.tencent.cloud.polaris.context.config.PolarisContextProperties;
import com.tencent.polaris.configuration.api.core.ConfigFileService; import com.tencent.polaris.configuration.api.core.ConfigFileService;
import com.tencent.polaris.configuration.api.core.ConfigKVFile; import com.tencent.polaris.configuration.api.core.ConfigKVFile;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource; import org.springframework.core.env.PropertySource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
/** /**
* test for {@link PolarisConfigFileLocator}. * test for {@link PolarisConfigFileLocator}.
*@author lepdou 2022-06-11 *@author lepdou 2022-06-11
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class PolarisConfigFileLocatorTest { public class PolarisConfigFileLocatorTest {
private final String testNamespace = "testNamespace"; private final String testNamespace = "testNamespace";
@ -88,9 +88,9 @@ public class PolarisConfigFileLocatorTest {
PropertySource<?> propertySource = locator.locate(environment); PropertySource<?> propertySource = locator.locate(environment);
Assert.assertEquals("v1", propertySource.getProperty("k1")); assertThat(propertySource.getProperty("k1")).isEqualTo("v1");
Assert.assertEquals("v2", propertySource.getProperty("k2")); assertThat(propertySource.getProperty("k2")).isEqualTo("v2");
Assert.assertEquals("v3", propertySource.getProperty("k3")); assertThat(propertySource.getProperty("k3")).isEqualTo("v3");
} }
@Test @Test
@ -131,9 +131,9 @@ public class PolarisConfigFileLocatorTest {
PropertySource<?> propertySource = locator.locate(environment); PropertySource<?> propertySource = locator.locate(environment);
Assert.assertEquals("v11", propertySource.getProperty("k1")); assertThat(propertySource.getProperty("k1")).isEqualTo("v11");
Assert.assertEquals("v2", propertySource.getProperty("k2")); assertThat(propertySource.getProperty("k2")).isEqualTo("v2");
Assert.assertEquals("v3", propertySource.getProperty("k3")); assertThat(propertySource.getProperty("k3")).isEqualTo("v3");
} }
@Test @Test
@ -180,8 +180,8 @@ public class PolarisConfigFileLocatorTest {
PropertySource<?> propertySource = locator.locate(environment); PropertySource<?> propertySource = locator.locate(environment);
Assert.assertEquals("v1", propertySource.getProperty("k1")); assertThat(propertySource.getProperty("k1")).isEqualTo("v1");
Assert.assertEquals("v2", propertySource.getProperty("k2")); assertThat(propertySource.getProperty("k2")).isEqualTo("v2");
Assert.assertEquals("v3", propertySource.getProperty("k3")); assertThat(propertySource.getProperty("k3")).isEqualTo("v3");
} }
} }

@ -27,14 +27,14 @@ import com.tencent.cloud.polaris.config.config.ConfigFileGroup;
import com.tencent.cloud.polaris.context.config.PolarisContextProperties; import com.tencent.cloud.polaris.context.config.PolarisContextProperties;
import com.tencent.polaris.configuration.api.core.ConfigFileService; import com.tencent.polaris.configuration.api.core.ConfigFileService;
import com.tencent.polaris.configuration.api.core.ConfigKVFile; import com.tencent.polaris.configuration.api.core.ConfigKVFile;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.core.env.CompositePropertySource; import org.springframework.core.env.CompositePropertySource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
/** /**
@ -42,7 +42,7 @@ import static org.mockito.Mockito.when;
* *
* @author wlx * @author wlx
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class PolarisConfigFilePullerTest { public class PolarisConfigFilePullerTest {
private final String testNamespace = "testNamespace"; private final String testNamespace = "testNamespace";
@ -81,9 +81,9 @@ public class PolarisConfigFilePullerTest {
puller.initInternalConfigFiles(compositePropertySource, new String[] {}, new String[] {}, testServiceName); puller.initInternalConfigFiles(compositePropertySource, new String[] {}, new String[] {}, testServiceName);
Assert.assertEquals("v1", compositePropertySource.getProperty("k1")); assertThat(compositePropertySource.getProperty("k1")).isEqualTo("v1");
Assert.assertEquals("v2", compositePropertySource.getProperty("k2")); assertThat(compositePropertySource.getProperty("k2")).isEqualTo("v2");
Assert.assertEquals("v3", compositePropertySource.getProperty("k3")); assertThat(compositePropertySource.getProperty("k3")).isEqualTo("v3");
} }
@Test @Test
@ -124,9 +124,9 @@ public class PolarisConfigFilePullerTest {
CompositePropertySource compositePropertySource = new CompositePropertySource(polarisConfigPropertySourceName); CompositePropertySource compositePropertySource = new CompositePropertySource(polarisConfigPropertySourceName);
puller.initInternalConfigFiles(compositePropertySource, activeProfiles, new String[] {}, testServiceName); puller.initInternalConfigFiles(compositePropertySource, activeProfiles, new String[] {}, testServiceName);
Assert.assertEquals("v11", compositePropertySource.getProperty("k1")); assertThat(compositePropertySource.getProperty("k1")).isEqualTo("v11");
Assert.assertEquals("v2", compositePropertySource.getProperty("k2")); assertThat(compositePropertySource.getProperty("k2")).isEqualTo("v2");
Assert.assertEquals("v3", compositePropertySource.getProperty("k3")); assertThat(compositePropertySource.getProperty("k3")).isEqualTo("v3");
} }
@Test @Test
@ -162,8 +162,8 @@ public class PolarisConfigFilePullerTest {
CompositePropertySource compositePropertySource = new CompositePropertySource(polarisConfigPropertySourceName); CompositePropertySource compositePropertySource = new CompositePropertySource(polarisConfigPropertySourceName);
puller.initCustomPolarisConfigFiles(compositePropertySource, customFiles); puller.initCustomPolarisConfigFiles(compositePropertySource, customFiles);
Assert.assertEquals("v1", compositePropertySource.getProperty("k1")); assertThat(compositePropertySource.getProperty("k1")).isEqualTo("v1");
Assert.assertEquals("v2", compositePropertySource.getProperty("k2")); assertThat(compositePropertySource.getProperty("k2")).isEqualTo("v2");
Assert.assertEquals("v3", compositePropertySource.getProperty("k3")); assertThat(compositePropertySource.getProperty("k3")).isEqualTo("v3");
} }
} }

@ -32,16 +32,16 @@ import com.tencent.cloud.polaris.config.spring.property.SpringValueRegistry;
import com.tencent.polaris.configuration.api.core.ChangeType; import com.tencent.polaris.configuration.api.core.ChangeType;
import com.tencent.polaris.configuration.api.core.ConfigKVFileChangeEvent; import com.tencent.polaris.configuration.api.core.ConfigKVFileChangeEvent;
import com.tencent.polaris.configuration.api.core.ConfigPropertyChangeInfo; import com.tencent.polaris.configuration.api.core.ConfigPropertyChangeInfo;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.TypeConverter; import org.springframework.beans.TypeConverter;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -51,7 +51,7 @@ import static org.mockito.Mockito.when;
* *
* @author lepdou 2022-06-11 * @author lepdou 2022-06-11
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class PolarisPropertiesSourceAutoRefresherTest { public class PolarisPropertiesSourceAutoRefresherTest {
private final String testNamespace = "testNamespace"; private final String testNamespace = "testNamespace";
@ -114,9 +114,9 @@ public class PolarisPropertiesSourceAutoRefresherTest {
file.fireChangeListener(event); file.fireChangeListener(event);
Assert.assertEquals("v11", polarisPropertySource.getProperty("k1")); assertThat(polarisPropertySource.getProperty("k1")).isEqualTo("v11");
Assert.assertEquals("v3", polarisPropertySource.getProperty("k3")); assertThat(polarisPropertySource.getProperty("k3")).isEqualTo("v3");
Assert.assertNull(polarisPropertySource.getProperty("k2")); assertThat(polarisPropertySource.getProperty("k2")).isNull();
Assert.assertEquals("v4", polarisPropertySource.getProperty("k4")); assertThat(polarisPropertySource.getProperty("k4")).isEqualTo("v4");
} }
} }

@ -31,9 +31,9 @@ import com.tencent.cloud.polaris.config.enums.RefreshType;
import com.tencent.cloud.polaris.config.spring.annotation.SpringValueProcessor; import com.tencent.cloud.polaris.config.spring.annotation.SpringValueProcessor;
import com.tencent.cloud.polaris.config.spring.property.PlaceholderHelper; import com.tencent.cloud.polaris.config.spring.property.PlaceholderHelper;
import com.tencent.cloud.polaris.config.spring.property.SpringValueRegistry; import com.tencent.cloud.polaris.config.spring.property.SpringValueRegistry;
import org.junit.AfterClass; import org.junit.jupiter.api.AfterAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ApplicationContextRunner;
@ -52,8 +52,8 @@ public class ConditionalOnReflectRefreshTypeTest {
private static ServerSocket serverSocket; private static ServerSocket serverSocket;
@BeforeClass @BeforeAll
public static void before() { static void beforeAll() {
new Thread(() -> { new Thread(() -> {
try { try {
serverSocket = new ServerSocket(8093); serverSocket = new ServerSocket(8093);
@ -65,8 +65,8 @@ public class ConditionalOnReflectRefreshTypeTest {
}).start(); }).start();
} }
@AfterClass @AfterAll
public static void after() throws IOException { static void afterAll() throws IOException {
serverSocket.close(); serverSocket.close();
} }

@ -32,12 +32,11 @@ import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.configuration.api.core.ConfigFileService; import com.tencent.polaris.configuration.api.core.ConfigFileService;
import com.tencent.polaris.configuration.api.core.ConfigKVFile; import com.tencent.polaris.configuration.api.core.ConfigKVFile;
import com.tencent.polaris.configuration.factory.ConfigFileServiceFactory; import com.tencent.polaris.configuration.factory.ConfigFileServiceFactory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterAll;
import org.junit.runner.RunWith; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.MockedStatic; import org.mockito.MockedStatic;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.ConfigurableBootstrapContext; import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.context.config.ConfigData; import org.springframework.boot.context.config.ConfigData;
@ -49,6 +48,7 @@ import org.springframework.core.env.PropertySource;
import static com.tencent.cloud.polaris.config.configdata.PolarisConfigDataLoader.CUSTOM_POLARIS_CONFIG_FILE_LOADED; import static com.tencent.cloud.polaris.config.configdata.PolarisConfigDataLoader.CUSTOM_POLARIS_CONFIG_FILE_LOADED;
import static com.tencent.cloud.polaris.config.configdata.PolarisConfigDataLoader.INTERNAL_CONFIG_FILES_LOADED; import static com.tencent.cloud.polaris.config.configdata.PolarisConfigDataLoader.INTERNAL_CONFIG_FILES_LOADED;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.mockStatic;
@ -59,7 +59,7 @@ import static org.mockito.Mockito.when;
* *
* @author wlx * @author wlx
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class PolarisConfigDataLoaderTest { public class PolarisConfigDataLoaderTest {
private static final SDKContext sdkContext = SDKContext.initContext(); private static final SDKContext sdkContext = SDKContext.initContext();
@ -68,6 +68,13 @@ public class PolarisConfigDataLoaderTest {
private final String testServiceName = "testServiceName"; private final String testServiceName = "testServiceName";
private final String polarisConfigPropertySourceName = "polaris-config"; private final String polarisConfigPropertySourceName = "polaris-config";
@AfterAll
static void afterAll() {
if (sdkContext != null) {
sdkContext.destroy();
}
}
@Test @Test
public void loadConfigDataInternalConfigFilesTest() { public void loadConfigDataInternalConfigFilesTest() {
try (MockedStatic<ConfigFileServiceFactory> mockedStatic = mockStatic(ConfigFileServiceFactory.class)) { try (MockedStatic<ConfigFileServiceFactory> mockedStatic = mockStatic(ConfigFileServiceFactory.class)) {
@ -121,9 +128,9 @@ public class PolarisConfigDataLoaderTest {
List<PropertySource<?>> propertySources = configData.getPropertySources(); List<PropertySource<?>> propertySources = configData.getPropertySources();
CompositePropertySource compositePropertySource = new CompositePropertySource(polarisConfigPropertySourceName); CompositePropertySource compositePropertySource = new CompositePropertySource(polarisConfigPropertySourceName);
propertySources.forEach(compositePropertySource::addPropertySource); propertySources.forEach(compositePropertySource::addPropertySource);
Assert.assertEquals("v1", compositePropertySource.getProperty("k1")); assertThat(compositePropertySource.getProperty("k1")).isEqualTo("v1");
Assert.assertEquals("v2", compositePropertySource.getProperty("k2")); assertThat(compositePropertySource.getProperty("k2")).isEqualTo("v2");
Assert.assertEquals("v3", compositePropertySource.getProperty("k3")); assertThat(compositePropertySource.getProperty("k3")).isEqualTo("v3");
} }
} }
@ -198,10 +205,9 @@ public class PolarisConfigDataLoaderTest {
CompositePropertySource compositePropertySource = new CompositePropertySource(polarisConfigPropertySourceName); CompositePropertySource compositePropertySource = new CompositePropertySource(polarisConfigPropertySourceName);
propertySources.forEach(compositePropertySource::addPropertySource); propertySources.forEach(compositePropertySource::addPropertySource);
Assert.assertEquals("v11", compositePropertySource.getProperty("k1")); assertThat(compositePropertySource.getProperty("k1")).isEqualTo("v11");
Assert.assertEquals("v2", compositePropertySource.getProperty("k2")); assertThat(compositePropertySource.getProperty("k2")).isEqualTo("v2");
Assert.assertEquals("v3", compositePropertySource.getProperty("k3")); assertThat(compositePropertySource.getProperty("k3")).isEqualTo("v3");
} }
} }
@ -272,17 +278,9 @@ public class PolarisConfigDataLoaderTest {
CompositePropertySource compositePropertySource = new CompositePropertySource(polarisConfigPropertySourceName); CompositePropertySource compositePropertySource = new CompositePropertySource(polarisConfigPropertySourceName);
propertySources.forEach(compositePropertySource::addPropertySource); propertySources.forEach(compositePropertySource::addPropertySource);
Assert.assertEquals("v1", compositePropertySource.getProperty("k1")); assertThat(compositePropertySource.getProperty("k1")).isEqualTo("v1");
Assert.assertEquals("v2", compositePropertySource.getProperty("k2")); assertThat(compositePropertySource.getProperty("k2")).isEqualTo("v2");
Assert.assertEquals("v3", compositePropertySource.getProperty("k3")); assertThat(compositePropertySource.getProperty("k3")).isEqualTo("v3");
}
}
@AfterAll
static void afterAll() {
if (sdkContext != null) {
sdkContext.destroy();
} }
} }
} }

@ -18,10 +18,10 @@
package com.tencent.cloud.polaris.config.configdata; package com.tencent.cloud.polaris.config.configdata;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.context.config.ConfigDataLocation; import org.springframework.boot.context.config.ConfigDataLocation;
import org.springframework.boot.context.config.ConfigDataLocationResolverContext; import org.springframework.boot.context.config.ConfigDataLocationResolverContext;
@ -37,38 +37,27 @@ import static org.mockito.Mockito.when;
* *
* @author wlx * @author wlx
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class PolarisConfigDataLocationResolverTest { public class PolarisConfigDataLocationResolverTest {
private final PolarisConfigDataLocationResolver resolver = new PolarisConfigDataLocationResolver(new DeferredLogs()); private final PolarisConfigDataLocationResolver resolver = new PolarisConfigDataLocationResolver(new DeferredLogs());
@Mock
private ConfigDataLocationResolverContext context;
private final MockEnvironment environment = new MockEnvironment(); private final MockEnvironment environment = new MockEnvironment();
private final Binder environmentBinder = Binder.get(this.environment); private final Binder environmentBinder = Binder.get(this.environment);
@Mock
private ConfigDataLocationResolverContext context;
@Test @Test
public void testIsResolvable() { public void testIsResolvable() {
when(context.getBinder()).thenReturn(environmentBinder); when(context.getBinder()).thenReturn(environmentBinder);
assertThat( assertThat(this.resolver.isResolvable(this.context, ConfigDataLocation.of("configserver:"))).isFalse();
this.resolver.isResolvable(this.context, ConfigDataLocation.of("configserver:"))) assertThat(this.resolver.isResolvable(this.context, ConfigDataLocation.of("polaris:"))).isTrue();
.isFalse(); assertThat(this.resolver.isResolvable(this.context, ConfigDataLocation.of("polaris"))).isTrue();
assertThat(
this.resolver.isResolvable(this.context, ConfigDataLocation.of("polaris:")))
.isTrue();
assertThat(
this.resolver.isResolvable(this.context, ConfigDataLocation.of("polaris")))
.isTrue();
} }
@Test @Test
public void unEnabledPolarisConfigData() { public void unEnabledPolarisConfigData() {
environment.setProperty("spring.cloud.polaris.config.enabled", "false"); environment.setProperty("spring.cloud.polaris.config.enabled", "false");
when(context.getBinder()).thenReturn(environmentBinder); when(context.getBinder()).thenReturn(environmentBinder);
assertThat( assertThat(this.resolver.isResolvable(this.context, ConfigDataLocation.of("polaris:"))).isFalse();
this.resolver.isResolvable(this.context, ConfigDataLocation.of("polaris:")))
.isFalse();
} }
} }

@ -18,7 +18,8 @@
package com.tencent.cloud.polaris.config.configdata; package com.tencent.cloud.polaris.config.configdata;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.mock.env.MockEnvironment; import org.springframework.mock.env.MockEnvironment;

@ -19,7 +19,7 @@
package com.tencent.cloud.polaris.config.configdata; package com.tencent.cloud.polaris.config.configdata;
import com.tencent.polaris.api.utils.StringUtils; import com.tencent.polaris.api.utils.StringUtils;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.diagnostics.FailureAnalysis; import org.springframework.boot.diagnostics.FailureAnalysis;

@ -26,10 +26,10 @@ import com.tencent.cloud.polaris.config.adapter.MockedConfigKVFile;
import com.tencent.cloud.polaris.config.adapter.PolarisPropertySource; import com.tencent.cloud.polaris.config.adapter.PolarisPropertySource;
import com.tencent.cloud.polaris.config.adapter.PolarisPropertySourceManager; import com.tencent.cloud.polaris.config.adapter.PolarisPropertySourceManager;
import com.tencent.cloud.polaris.config.config.PolarisConfigProperties; import com.tencent.cloud.polaris.config.config.PolarisConfigProperties;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -39,7 +39,7 @@ import static org.mockito.Mockito.when;
* *
* @author shuiqingliu * @author shuiqingliu
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class PolarisConfigEndpointTest { public class PolarisConfigEndpointTest {
private final String testNamespace = "testNamespace"; private final String testNamespace = "testNamespace";

@ -25,8 +25,8 @@ import com.google.common.collect.Sets;
import com.tencent.cloud.polaris.config.annotation.PolarisConfigKVFileChangeListener; import com.tencent.cloud.polaris.config.annotation.PolarisConfigKVFileChangeListener;
import com.tencent.polaris.configuration.api.core.ConfigPropertyChangeInfo; import com.tencent.polaris.configuration.api.core.ConfigPropertyChangeInfo;
import org.assertj.core.api.Assertions; import org.assertj.core.api.Assertions;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
@ -36,7 +36,7 @@ import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT;
@ -45,7 +45,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* *
* @author lepdou 2022-06-11 * @author lepdou 2022-06-11
*/ */
@RunWith(SpringRunner.class) @ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = DEFINED_PORT, classes = ConfigChangeListenerTest.TestApplication.class, @SpringBootTest(webEnvironment = DEFINED_PORT, classes = ConfigChangeListenerTest.TestApplication.class,
properties = {"server.port=8081", "spring.config.location = classpath:application-test.yml"}) properties = {"server.port=8081", "spring.config.location = classpath:application-test.yml"})
public class ConfigChangeListenerTest { public class ConfigChangeListenerTest {

@ -22,7 +22,6 @@ import java.io.IOException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.net.ServerSocket; import java.net.ServerSocket;
import java.util.Collection; import java.util.Collection;
import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import com.tencent.cloud.polaris.config.PolarisConfigBootstrapAutoConfiguration; import com.tencent.cloud.polaris.config.PolarisConfigBootstrapAutoConfiguration;
@ -31,10 +30,9 @@ import com.tencent.cloud.polaris.config.spring.property.Person;
import com.tencent.cloud.polaris.config.spring.property.SpringValue; import com.tencent.cloud.polaris.config.spring.property.SpringValue;
import com.tencent.cloud.polaris.config.spring.property.SpringValueRegistry; import com.tencent.cloud.polaris.config.spring.property.SpringValueRegistry;
import com.tencent.polaris.api.utils.CollectionUtils; import com.tencent.polaris.api.utils.CollectionUtils;
import org.junit.AfterClass; import org.junit.jupiter.api.AfterAll;
import org.junit.Assert; import org.junit.jupiter.api.BeforeAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -47,6 +45,8 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource; import org.springframework.context.annotation.ImportResource;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import static org.assertj.core.api.Assertions.assertThat;
/** /**
* Test for {@link SpringValueProcessor}. * Test for {@link SpringValueProcessor}.
* *
@ -56,8 +56,8 @@ public class SpringValueProcessorTest {
private static ServerSocket serverSocket; private static ServerSocket serverSocket;
@BeforeClass @BeforeAll
public static void before() { static void beforeAll() {
new Thread(() -> { new Thread(() -> {
try { try {
serverSocket = new ServerSocket(8093); serverSocket = new ServerSocket(8093);
@ -69,8 +69,8 @@ public class SpringValueProcessorTest {
}).start(); }).start();
} }
@AfterClass @AfterAll
public static void after() throws IOException { static void afterAll() throws IOException {
serverSocket.close(); serverSocket.close();
} }
@ -92,19 +92,19 @@ public class SpringValueProcessorTest {
PolarisConfigAutoConfiguration polarisConfigAutoConfiguration = context.getBean(PolarisConfigAutoConfiguration.class); PolarisConfigAutoConfiguration polarisConfigAutoConfiguration = context.getBean(PolarisConfigAutoConfiguration.class);
BeanFactory beanFactory = polarisConfigAutoConfiguration.beanFactory; BeanFactory beanFactory = polarisConfigAutoConfiguration.beanFactory;
Collection<SpringValue> timeout = springValueRegistry.get(beanFactory, "timeout"); Collection<SpringValue> timeout = springValueRegistry.get(beanFactory, "timeout");
Assert.assertFalse(CollectionUtils.isEmpty(timeout)); assertThat(CollectionUtils.isEmpty(timeout)).isFalse();
Optional<SpringValue> springValueOptional = timeout.stream().findAny(); Optional<SpringValue> springValueOptional = timeout.stream().findAny();
Assert.assertTrue(springValueOptional.isPresent()); assertThat(springValueOptional.isPresent()).isTrue();
SpringValue springValue = springValueOptional.get(); SpringValue springValue = springValueOptional.get();
Assert.assertEquals("${timeout:1000}", springValue.getPlaceholder()); assertThat(springValue.getPlaceholder()).isEqualTo("${timeout:1000}");
Assert.assertTrue(springValue.isField()); assertThat(springValue.isField()).isTrue();
Assert.assertTrue(Objects.nonNull(springValue.getField())); assertThat(springValue.getField()).isNotNull();
Assert.assertEquals("timeout", springValue.getField().getName()); assertThat(springValue.getField().getName()).isEqualTo("timeout");
Assert.assertEquals(int.class, springValue.getTargetType()); assertThat(springValue.getTargetType()).isEqualTo(int.class);
ValueTest bean = context.getBean(ValueTest.class); ValueTest bean = context.getBean(ValueTest.class);
Assert.assertEquals(10000, bean.timeout); assertThat(bean.timeout).isEqualTo(10000);
}); });
} }
@ -127,19 +127,19 @@ public class SpringValueProcessorTest {
PolarisConfigAutoConfiguration polarisConfigAutoConfiguration = context.getBean(PolarisConfigAutoConfiguration.class); PolarisConfigAutoConfiguration polarisConfigAutoConfiguration = context.getBean(PolarisConfigAutoConfiguration.class);
BeanFactory beanFactory = polarisConfigAutoConfiguration.beanFactory; BeanFactory beanFactory = polarisConfigAutoConfiguration.beanFactory;
Collection<SpringValue> name = springValueRegistry.get(beanFactory, "name"); Collection<SpringValue> name = springValueRegistry.get(beanFactory, "name");
Assert.assertFalse(CollectionUtils.isEmpty(name)); assertThat(name).isNotEmpty();
Optional<SpringValue> springValueOptional = name.stream().findAny(); Optional<SpringValue> springValueOptional = name.stream().findAny();
Assert.assertTrue(springValueOptional.isPresent()); assertThat(springValueOptional.isPresent()).isTrue();
SpringValue springValue = springValueOptional.get(); SpringValue springValue = springValueOptional.get();
Method method = springValue.getMethodParameter().getMethod(); Method method = springValue.getMethodParameter().getMethod();
Assert.assertTrue(Objects.nonNull(method)); assertThat(method).isNotNull();
Assert.assertEquals("setName", method.getName()); assertThat(method.getName()).isEqualTo("setName");
Assert.assertEquals("${name:1000}", springValue.getPlaceholder()); assertThat(springValue.getPlaceholder()).isEqualTo("${name:1000}");
Assert.assertFalse(springValue.isField()); assertThat(springValue.isField()).isFalse();
Assert.assertEquals(String.class, springValue.getTargetType()); assertThat(springValue.getTargetType()).isEqualTo(String.class);
Assert.assertEquals("test", ValueTest.name); assertThat(ValueTest.name).isEqualTo("test");
}); });
} }
@ -163,31 +163,31 @@ public class SpringValueProcessorTest {
SpringValueRegistry springValueRegistry = context.getBean(SpringValueRegistry.class); SpringValueRegistry springValueRegistry = context.getBean(SpringValueRegistry.class);
BeanFactory beanFactory = person.getBeanFactory(); BeanFactory beanFactory = person.getBeanFactory();
Collection<SpringValue> name = springValueRegistry.get(beanFactory, "name"); Collection<SpringValue> name = springValueRegistry.get(beanFactory, "name");
Assert.assertFalse(CollectionUtils.isEmpty(name)); assertThat(name).isNotEmpty();
Optional<SpringValue> nameSpringValueOptional = name.stream().findAny(); Optional<SpringValue> nameSpringValueOptional = name.stream().findAny();
Assert.assertTrue(nameSpringValueOptional.isPresent()); assertThat(nameSpringValueOptional.isPresent()).isTrue();
SpringValue nameSpringValue = nameSpringValueOptional.get(); SpringValue nameSpringValue = nameSpringValueOptional.get();
Method method = nameSpringValue.getMethodParameter().getMethod(); Method method = nameSpringValue.getMethodParameter().getMethod();
Assert.assertTrue(Objects.nonNull(method)); assertThat(method).isNotNull();
Assert.assertEquals("setName", method.getName()); assertThat(method.getName()).isEqualTo("setName");
Assert.assertEquals("${name:test}", nameSpringValue.getPlaceholder()); assertThat(nameSpringValue.getPlaceholder()).isEqualTo("${name:test}");
Assert.assertFalse(nameSpringValue.isField()); assertThat(nameSpringValue.isField()).isFalse();
Assert.assertEquals(String.class, nameSpringValue.getTargetType()); assertThat(nameSpringValue.getTargetType()).isEqualTo(String.class);
Collection<SpringValue> age = springValueRegistry.get(beanFactory, "age"); Collection<SpringValue> age = springValueRegistry.get(beanFactory, "age");
Assert.assertFalse(CollectionUtils.isEmpty(age)); assertThat(age).isNotEmpty();
Optional<SpringValue> ageSpringValueOptional = age.stream().findAny(); Optional<SpringValue> ageSpringValueOptional = age.stream().findAny();
Assert.assertTrue(ageSpringValueOptional.isPresent()); assertThat(ageSpringValueOptional.isPresent()).isTrue();
SpringValue ageSpringValue = ageSpringValueOptional.get(); SpringValue ageSpringValue = ageSpringValueOptional.get();
Method method1 = ageSpringValue.getMethodParameter().getMethod(); Method method1 = ageSpringValue.getMethodParameter().getMethod();
Assert.assertTrue(Objects.nonNull(method1)); assertThat(method1).isNotNull();
Assert.assertEquals("setAge", method1.getName()); assertThat(method1.getName()).isEqualTo("setAge");
Assert.assertEquals("${age:10}", ageSpringValue.getPlaceholder()); assertThat(ageSpringValue.getPlaceholder()).isEqualTo("${age:10}");
Assert.assertFalse(ageSpringValue.isField()); assertThat(ageSpringValue.isField()).isFalse();
Assert.assertEquals(String.class, ageSpringValue.getTargetType()); assertThat(ageSpringValue.getTargetType()).isEqualTo(String.class);
}); });
} }

@ -26,14 +26,15 @@ import java.util.concurrent.atomic.AtomicInteger;
import com.tencent.polaris.configuration.api.core.ChangeType; import com.tencent.polaris.configuration.api.core.ChangeType;
import com.tencent.polaris.configuration.api.core.ConfigPropertyChangeInfo; import com.tencent.polaris.configuration.api.core.ConfigPropertyChangeInfo;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.ApplicationListener; import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
/** /**
* Test for {@link ConfigChangeSpringEvent}. * Test for {@link ConfigChangeSpringEvent}.
@ -42,9 +43,9 @@ import org.springframework.context.annotation.Configuration;
*/ */
public class ConfigChangeSpringEventTest { public class ConfigChangeSpringEventTest {
private static CountDownLatch countDownLatch = new CountDownLatch(1); private static final CountDownLatch countDownLatch = new CountDownLatch(1);
private static AtomicInteger receiveEventTimes = new AtomicInteger(); private static final AtomicInteger receiveEventTimes = new AtomicInteger();
@Test @Test
public void testPublishConfigChangeSpringEvent() { public void testPublishConfigChangeSpringEvent() {
@ -55,7 +56,7 @@ public class ConfigChangeSpringEventTest {
changeMap.put("key", new ConfigPropertyChangeInfo("key", null, "value", ChangeType.ADDED)); changeMap.put("key", new ConfigPropertyChangeInfo("key", null, "value", ChangeType.ADDED));
context.publishEvent(new ConfigChangeSpringEvent(changeMap)); context.publishEvent(new ConfigChangeSpringEvent(changeMap));
countDownLatch.await(5, TimeUnit.SECONDS); countDownLatch.await(5, TimeUnit.SECONDS);
Assert.assertEquals(1, receiveEventTimes.get()); assertThat(receiveEventTimes.get()).isEqualTo(1);
}); });
} }
@ -65,13 +66,13 @@ public class ConfigChangeSpringEventTest {
@Override @Override
public void onApplicationEvent(ConfigChangeSpringEvent event) { public void onApplicationEvent(ConfigChangeSpringEvent event) {
Set<String> changedKeys = event.changedKeys(); Set<String> changedKeys = event.changedKeys();
Assert.assertEquals(1, changedKeys.size()); assertThat(changedKeys.size()).isEqualTo(1);
Assert.assertTrue(event.isChanged("key")); assertThat(event.isChanged("key")).isTrue();
ConfigPropertyChangeInfo changeInfo = event.getChange("key"); ConfigPropertyChangeInfo changeInfo = event.getChange("key");
Assert.assertNotNull(changeInfo); assertThat(changeInfo).isNotNull();
Assert.assertEquals("key", changeInfo.getPropertyName()); assertThat(changeInfo.getPropertyName()).isEqualTo("key");
Assert.assertEquals("value", changeInfo.getNewValue()); assertThat(changeInfo.getNewValue()).isEqualTo("value");
Assert.assertEquals(ChangeType.ADDED, changeInfo.getChangeType()); assertThat(changeInfo.getChangeType()).isEqualTo(ChangeType.ADDED);
receiveEventTimes.incrementAndGet(); receiveEventTimes.incrementAndGet();
countDownLatch.countDown(); countDownLatch.countDown();

@ -20,9 +20,9 @@ package com.tencent.cloud.polaris.config.spring.property;
import java.util.Set; import java.util.Set;
import com.tencent.polaris.api.utils.CollectionUtils; import org.junit.jupiter.api.Test;
import org.junit.Assert;
import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat;
/** /**
* Test for {@link PlaceholderHelper}. * Test for {@link PlaceholderHelper}.
@ -43,31 +43,31 @@ public class PlaceholderHelperTest {
final String placeholderCase5 = "#{new java.text.SimpleDateFormat('${some.key}').parse('${another.key}')}"; final String placeholderCase5 = "#{new java.text.SimpleDateFormat('${some.key}').parse('${another.key}')}";
Set<String> placeholderKeys = PLACEHOLDER_HELPER.extractPlaceholderKeys(placeholderCase); Set<String> placeholderKeys = PLACEHOLDER_HELPER.extractPlaceholderKeys(placeholderCase);
Assert.assertEquals(1, placeholderKeys.size()); assertThat(placeholderKeys.size()).isEqualTo(1);
Assert.assertTrue(placeholderKeys.contains("some.key")); assertThat(placeholderKeys).contains("some.key");
Set<String> placeholderKeys1 = PLACEHOLDER_HELPER.extractPlaceholderKeys(placeholderCase1); Set<String> placeholderKeys1 = PLACEHOLDER_HELPER.extractPlaceholderKeys(placeholderCase1);
Assert.assertEquals(2, placeholderKeys1.size()); assertThat(placeholderKeys1.size()).isEqualTo(2);
Assert.assertTrue(placeholderKeys1.contains("some.key")); assertThat(placeholderKeys1).contains("some.key");
Assert.assertTrue(placeholderKeys1.contains("some.other.key")); assertThat(placeholderKeys1).contains("some.other.key");
Set<String> placeholderKeys2 = PLACEHOLDER_HELPER.extractPlaceholderKeys(placeholderCase2); Set<String> placeholderKeys2 = PLACEHOLDER_HELPER.extractPlaceholderKeys(placeholderCase2);
Assert.assertEquals(1, placeholderKeys2.size()); assertThat(placeholderKeys2.size()).isEqualTo(1);
Assert.assertTrue(placeholderKeys2.contains("some.key")); assertThat(placeholderKeys2).contains("some.key");
Set<String> placeholderKeys3 = PLACEHOLDER_HELPER.extractPlaceholderKeys(placeholderCase3); Set<String> placeholderKeys3 = PLACEHOLDER_HELPER.extractPlaceholderKeys(placeholderCase3);
Assert.assertEquals(1, placeholderKeys3.size()); assertThat(placeholderKeys3.size()).isEqualTo(1);
Assert.assertTrue(placeholderKeys3.contains("some.key")); assertThat(placeholderKeys3).contains("some.key");
Set<String> placeholderKeys4 = PLACEHOLDER_HELPER.extractPlaceholderKeys(placeholderCase4); Set<String> placeholderKeys4 = PLACEHOLDER_HELPER.extractPlaceholderKeys(placeholderCase4);
Assert.assertEquals(2, placeholderKeys4.size()); assertThat(placeholderKeys4.size()).isEqualTo(2);
Assert.assertTrue(placeholderKeys4.contains("some.key")); assertThat(placeholderKeys4).contains("some.key");
Assert.assertTrue(placeholderKeys4.contains("another.key")); assertThat(placeholderKeys4).contains("another.key");
Set<String> placeholderKeys5 = PLACEHOLDER_HELPER.extractPlaceholderKeys(placeholderCase5); Set<String> placeholderKeys5 = PLACEHOLDER_HELPER.extractPlaceholderKeys(placeholderCase5);
Assert.assertEquals(2, placeholderKeys5.size()); assertThat(placeholderKeys5.size()).isEqualTo(2);
Assert.assertTrue(placeholderKeys5.contains("some.key")); assertThat(placeholderKeys5).contains("some.key");
Assert.assertTrue(placeholderKeys5.contains("another.key")); assertThat(placeholderKeys5).contains("another.key");
} }
@Test @Test
@ -77,12 +77,12 @@ public class PlaceholderHelperTest {
final String placeholderCase2 = "some.key"; final String placeholderCase2 = "some.key";
Set<String> placeholderKeys = PLACEHOLDER_HELPER.extractPlaceholderKeys(placeholderCase); Set<String> placeholderKeys = PLACEHOLDER_HELPER.extractPlaceholderKeys(placeholderCase);
Assert.assertTrue(CollectionUtils.isEmpty(placeholderKeys)); assertThat(placeholderKeys).isEmpty();
Set<String> placeholderKeys1 = PLACEHOLDER_HELPER.extractPlaceholderKeys(placeholderCase1); Set<String> placeholderKeys1 = PLACEHOLDER_HELPER.extractPlaceholderKeys(placeholderCase1);
Assert.assertTrue(CollectionUtils.isEmpty(placeholderKeys1)); assertThat(placeholderKeys1).isEmpty();
Set<String> placeholderKeys2 = PLACEHOLDER_HELPER.extractPlaceholderKeys(placeholderCase2); Set<String> placeholderKeys2 = PLACEHOLDER_HELPER.extractPlaceholderKeys(placeholderCase2);
Assert.assertTrue(CollectionUtils.isEmpty(placeholderKeys2)); assertThat(placeholderKeys2).isEmpty();
} }
} }

@ -32,6 +32,12 @@
<groupId>com.tencent.polaris</groupId> <groupId>com.tencent.polaris</groupId>
<artifactId>polaris-test-mock-discovery</artifactId> <artifactId>polaris-test-mock-discovery</artifactId>
<scope>test</scope> <scope>test</scope>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<!-- Polaris dependencies end --> <!-- Polaris dependencies end -->

@ -22,7 +22,7 @@ import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler;
import com.tencent.cloud.polaris.extend.consul.ConsulContextProperties; import com.tencent.cloud.polaris.extend.consul.ConsulContextProperties;
import com.tencent.polaris.api.core.ConsumerAPI; import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.api.core.ProviderAPI; import com.tencent.polaris.api.core.ProviderAPI;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ApplicationContextRunner;

@ -18,7 +18,7 @@
package com.tencent.cloud.polaris; package com.tencent.cloud.polaris;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ApplicationContextRunner;

@ -18,7 +18,8 @@
package com.tencent.cloud.polaris; package com.tencent.cloud.polaris;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static com.tencent.polaris.test.common.Consts.NAMESPACE_TEST; import static com.tencent.polaris.test.common.Consts.NAMESPACE_TEST;
import static com.tencent.polaris.test.common.Consts.PROVIDER_TOKEN; import static com.tencent.polaris.test.common.Consts.PROVIDER_TOKEN;

@ -23,9 +23,9 @@ import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.polaris.api.core.ConsumerAPI; import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.api.core.ProviderAPI; import com.tencent.polaris.api.core.ProviderAPI;
import com.tencent.polaris.test.mock.discovery.NamingServer; import com.tencent.polaris.test.mock.discovery.NamingServer;
import org.junit.AfterClass; import org.junit.jupiter.api.AfterAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@ -55,13 +55,13 @@ public class PolarisDiscoveryAutoConfigurationTest {
.withPropertyValues("server.port=" + PORT) .withPropertyValues("server.port=" + PORT)
.withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081"); .withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081");
@BeforeClass @BeforeAll
public static void beforeClass() throws Exception { static void beforeAll() throws Exception {
namingServer = NamingServer.startNamingServer(10081); namingServer = NamingServer.startNamingServer(10081);
} }
@AfterClass @AfterAll
public static void afterClass() { static void afterAll() {
if (null != namingServer) { if (null != namingServer) {
namingServer.terminate(); namingServer.terminate();
} }

@ -19,9 +19,9 @@ package com.tencent.cloud.polaris.discovery;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.polaris.test.mock.discovery.NamingServer; import com.tencent.polaris.test.mock.discovery.NamingServer;
import org.junit.AfterClass; import org.junit.jupiter.api.AfterAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@ -50,13 +50,13 @@ public class PolarisDiscoveryClientConfigurationTest {
.withPropertyValues("server.port=" + PORT) .withPropertyValues("server.port=" + PORT)
.withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081"); .withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081");
@BeforeClass @BeforeAll
public static void beforeClass() throws Exception { static void beforeAll() throws Exception {
namingServer = NamingServer.startNamingServer(10081); namingServer = NamingServer.startNamingServer(10081);
} }
@AfterClass @AfterAll
public static void afterClass() { static void afterAll() {
if (null != namingServer) { if (null != namingServer) {
namingServer.terminate(); namingServer.terminate();
} }

@ -20,11 +20,11 @@ package com.tencent.cloud.polaris.discovery;
import java.util.List; import java.util.List;
import com.tencent.cloud.common.pojo.PolarisServiceInstance; import com.tencent.cloud.common.pojo.PolarisServiceInstance;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.ServiceInstance;
@ -40,7 +40,7 @@ import static org.mockito.Mockito.when;
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class PolarisDiscoveryClientTest { public class PolarisDiscoveryClientTest {
@Mock @Mock

@ -26,12 +26,12 @@ import com.tencent.polaris.api.pojo.DefaultServiceInstances;
import com.tencent.polaris.api.pojo.ServiceInfo; import com.tencent.polaris.api.pojo.ServiceInfo;
import com.tencent.polaris.api.rpc.InstancesResponse; import com.tencent.polaris.api.rpc.InstancesResponse;
import com.tencent.polaris.api.rpc.ServicesResponse; import com.tencent.polaris.api.rpc.ServicesResponse;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.ServiceInstance;
@ -50,8 +50,7 @@ import static org.mockito.Mockito.when;
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class PolarisServiceDiscoveryTest { public class PolarisServiceDiscoveryTest {
@Mock @Mock
@ -59,8 +58,8 @@ public class PolarisServiceDiscoveryTest {
@InjectMocks @InjectMocks
private PolarisServiceDiscovery polarisServiceDiscovery; private PolarisServiceDiscovery polarisServiceDiscovery;
@Before @BeforeEach
public void before() { void setUp() {
new ApplicationContextAwareUtils().setApplicationContext(new StaticApplicationContext()); new ApplicationContextAwareUtils().setApplicationContext(new StaticApplicationContext());
} }

@ -20,9 +20,9 @@ package com.tencent.cloud.polaris.discovery.reactive;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClientConfiguration; import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClientConfiguration;
import com.tencent.polaris.test.mock.discovery.NamingServer; import com.tencent.polaris.test.mock.discovery.NamingServer;
import org.junit.AfterClass; import org.junit.jupiter.api.AfterAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@ -52,13 +52,14 @@ public class PolarisReactiveDiscoveryClientConfigurationTest {
.withPropertyValues("server.port=" + PORT) .withPropertyValues("server.port=" + PORT)
.withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081"); .withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081");
@BeforeClass
public static void beforeClass() throws Exception { @BeforeAll
static void beforeAll() throws Exception {
namingServer = NamingServer.startNamingServer(10081); namingServer = NamingServer.startNamingServer(10081);
} }
@AfterClass @AfterAll
public static void afterClass() { static void afterAll() {
if (null != namingServer) { if (null != namingServer) {
namingServer.terminate(); namingServer.terminate();
} }

@ -22,11 +22,11 @@ import java.util.Arrays;
import com.tencent.cloud.polaris.discovery.PolarisServiceDiscovery; import com.tencent.cloud.polaris.discovery.PolarisServiceDiscovery;
import com.tencent.polaris.api.exception.ErrorCode; import com.tencent.polaris.api.exception.ErrorCode;
import com.tencent.polaris.api.exception.PolarisException; import com.tencent.polaris.api.exception.PolarisException;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Flux; import reactor.core.publisher.Flux;
import reactor.test.StepVerifier; import reactor.test.StepVerifier;
@ -44,7 +44,7 @@ import static org.mockito.Mockito.when;
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class PolarisReactiveDiscoveryClientTest { public class PolarisReactiveDiscoveryClientTest {
@Mock @Mock

@ -27,8 +27,8 @@ import com.tencent.polaris.api.pojo.ServiceKey;
import com.tencent.polaris.client.pojo.ServiceInstancesByProto; import com.tencent.polaris.client.pojo.ServiceInstancesByProto;
import com.tencent.polaris.client.pojo.ServicesByProto; import com.tencent.polaris.client.pojo.ServicesByProto;
import org.assertj.core.api.Assertions; import org.assertj.core.api.Assertions;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisher;
@ -52,8 +52,9 @@ public class PolarisServiceStatusChangeListenerTest {
private ApplicationEventPublisher publisher; private ApplicationEventPublisher publisher;
@Before
public void setUp() { @BeforeEach
void setUp() {
publisher = mock(ApplicationEventPublisher.class); publisher = mock(ApplicationEventPublisher.class);
doNothing().when(publisher).publishEvent(any(ApplicationEvent.class)); doNothing().when(publisher).publishEvent(any(ApplicationEvent.class));
} }

@ -24,9 +24,9 @@ import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClient;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClientConfiguration; import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClientConfiguration;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler; import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler;
import com.tencent.polaris.test.mock.discovery.NamingServer; import com.tencent.polaris.test.mock.discovery.NamingServer;
import org.junit.AfterClass; import org.junit.jupiter.api.AfterAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@ -60,13 +60,13 @@ public class PolarisDiscoveryEndpointTest {
.withPropertyValues("spring.cloud.polaris.discovery.namespace=" + NAMESPACE_TEST) .withPropertyValues("spring.cloud.polaris.discovery.namespace=" + NAMESPACE_TEST)
.withPropertyValues("spring.cloud.polaris.discovery.token=xxxxxx"); .withPropertyValues("spring.cloud.polaris.discovery.token=xxxxxx");
@BeforeClass @BeforeAll
public static void beforeClass() throws Exception { static void beforeAll() throws Exception {
namingServer = NamingServer.startNamingServer(10081); namingServer = NamingServer.startNamingServer(10081);
} }
@AfterClass @AfterAll
public static void afterClass() { static void afterAll() {
if (null != namingServer) { if (null != namingServer) {
namingServer.terminate(); namingServer.terminate();
} }

@ -22,14 +22,14 @@ import java.util.Map;
import com.tencent.polaris.client.api.SDKContext; import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.factory.config.global.ServerConnectorConfigImpl; import com.tencent.polaris.factory.config.global.ServerConnectorConfigImpl;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit.jupiter.SpringExtension;
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.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.IP_ADDRESS_KEY;
@ -44,7 +44,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@RunWith(SpringRunner.class) @ExtendWith(SpringExtension.class)
@SpringBootTest(classes = ConsulContextPropertiesTest.TestApplication.class) @SpringBootTest(classes = ConsulContextPropertiesTest.TestApplication.class)
@ActiveProfiles("test") @ActiveProfiles("test")
public class ConsulContextPropertiesTest { public class ConsulContextPropertiesTest {

@ -25,14 +25,14 @@ import java.util.Optional;
import com.tencent.polaris.api.config.plugin.DefaultPlugins; import com.tencent.polaris.api.config.plugin.DefaultPlugins;
import com.tencent.polaris.client.api.SDKContext; import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.factory.config.global.ServerConnectorConfigImpl; import com.tencent.polaris.factory.config.global.ServerConnectorConfigImpl;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -42,7 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author lingxiao.wlx * @author lingxiao.wlx
*/ */
@RunWith(SpringRunner.class) @ExtendWith(SpringExtension.class)
@SpringBootTest(classes = NacosContextPropertiesTest.TestApplication.class) @SpringBootTest(classes = NacosContextPropertiesTest.TestApplication.class)
@ActiveProfiles("test") @ActiveProfiles("test")
public class NacosContextPropertiesTest { public class NacosContextPropertiesTest {
@ -75,7 +75,8 @@ public class NacosContextPropertiesTest {
assertThat(optionalServerConnectorConfig.isPresent()).isTrue(); assertThat(optionalServerConnectorConfig.isPresent()).isTrue();
ServerConnectorConfigImpl serverConnectorConfig = optionalServerConnectorConfig.get(); ServerConnectorConfigImpl serverConnectorConfig = optionalServerConnectorConfig.get();
if (!CollectionUtils.isEmpty(serverConnectorConfig.getAddresses())) { if (!CollectionUtils.isEmpty(serverConnectorConfig.getAddresses())) {
assertThat(nacosContextProperties.getServerAddr().equals(serverConnectorConfig.getAddresses().get(0))).isTrue(); assertThat(nacosContextProperties.getServerAddr()
.equals(serverConnectorConfig.getAddresses().get(0))).isTrue();
} }
assertThat(DefaultPlugins.SERVER_CONNECTOR_NACOS.equals(serverConnectorConfig.getProtocol())).isTrue(); assertThat(DefaultPlugins.SERVER_CONNECTOR_NACOS.equals(serverConnectorConfig.getProtocol())).isTrue();

@ -19,7 +19,7 @@ package com.tencent.cloud.polaris.loadbalancer;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.polaris.router.api.core.RouterAPI; import com.tencent.polaris.router.api.core.RouterAPI;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@ -32,7 +32,7 @@ import org.springframework.web.client.RestTemplate;
import static com.tencent.polaris.test.common.Consts.PORT; import static com.tencent.polaris.test.common.Consts.PORT;
import static com.tencent.polaris.test.common.Consts.SERVICE_PROVIDER; import static com.tencent.polaris.test.common.Consts.SERVICE_PROVIDER;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** /**
* Test for {@link PolarisLoadBalancerAutoConfiguration}. * Test for {@link PolarisLoadBalancerAutoConfiguration}.
@ -56,13 +56,9 @@ public class PolarisLoadBalancerAutoConfigurationTest {
this.contextRunner.run(context -> { this.contextRunner.run(context -> {
assertThat(context).hasSingleBean(RouterAPI.class); assertThat(context).hasSingleBean(RouterAPI.class);
assertThat(context).hasSingleBean(RestTemplate.class); assertThat(context).hasSingleBean(RestTemplate.class);
try { assertThatThrownBy(() -> {
context.getBean(RestTemplate.class).getForEntity("http://wrong.url", String.class); context.getBean(RestTemplate.class).getForEntity("http://wrong.url", String.class);
fail(); }).isInstanceOf(Exception.class);
}
catch (Exception e) {
// do nothing
}
}); });
} }

@ -27,14 +27,14 @@ import com.tencent.polaris.api.pojo.Instance;
import com.tencent.polaris.router.api.core.RouterAPI; import com.tencent.polaris.router.api.core.RouterAPI;
import com.tencent.polaris.router.api.rpc.ProcessLoadBalanceResponse; import com.tencent.polaris.router.api.rpc.ProcessLoadBalanceResponse;
import org.assertj.core.api.Assertions; import org.assertj.core.api.Assertions;
import org.junit.AfterClass; import org.junit.jupiter.api.AfterAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockedStatic; import org.mockito.MockedStatic;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Flux; import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono; import reactor.core.publisher.Mono;
@ -56,7 +56,7 @@ import static org.mockito.Mockito.when;
* *
* @author rod.xu * @author rod.xu
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class PolarisLoadBalancerTest { public class PolarisLoadBalancerTest {
private static MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils; private static MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils;
@ -66,8 +66,8 @@ public class PolarisLoadBalancerTest {
@Mock @Mock
private ObjectProvider<ServiceInstanceListSupplier> supplierObjectProvider; private ObjectProvider<ServiceInstanceListSupplier> supplierObjectProvider;
@BeforeClass @BeforeAll
public static void beforeClass() { static void beforeAll() {
mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class); mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class);
mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString())) mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString()))
.thenReturn("unit-test"); .thenReturn("unit-test");
@ -76,8 +76,8 @@ public class PolarisLoadBalancerTest {
LOCAL_SERVICE, "host", 8090); LOCAL_SERVICE, "host", 8090);
} }
@AfterClass @AfterAll
public static void afterClass() { static void afterAll() {
mockedApplicationContextAwareUtils.close(); mockedApplicationContextAwareUtils.close();
} }

@ -19,7 +19,7 @@ package com.tencent.cloud.polaris.loadbalancer;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.polaris.router.api.core.RouterAPI; import com.tencent.polaris.router.api.core.RouterAPI;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

@ -18,11 +18,13 @@
package com.tencent.cloud.polaris.registry; package com.tencent.cloud.polaris.registry;
import com.tencent.cloud.polaris.PolarisDiscoveryProperties; import com.tencent.cloud.polaris.PolarisDiscoveryProperties;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties; import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry; import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
@ -31,7 +33,7 @@ import org.springframework.core.env.Environment;
import static com.tencent.polaris.test.common.Consts.SERVICE_PROVIDER; import static com.tencent.polaris.test.common.Consts.SERVICE_PROVIDER;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.assertj.core.api.Assertions.assertThatCode;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doNothing;
@ -42,7 +44,8 @@ import static org.mockito.Mockito.doReturn;
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
public class PolarisAutoServiceRegistrationTest { public class PolarisAutoServiceRegistrationTest {
@Mock @Mock
@ -65,8 +68,8 @@ public class PolarisAutoServiceRegistrationTest {
private PolarisAutoServiceRegistration polarisAutoServiceRegistration; private PolarisAutoServiceRegistration polarisAutoServiceRegistration;
@Before @BeforeEach
public void setUp() { void setUp() {
doReturn(polarisDiscoveryProperties).when(registration).getPolarisProperties(); doReturn(polarisDiscoveryProperties).when(registration).getPolarisProperties();
doNothing().when(serviceRegistry).register(nullable(PolarisRegistration.class)); doNothing().when(serviceRegistry).register(nullable(PolarisRegistration.class));
@ -81,20 +84,14 @@ public class PolarisAutoServiceRegistrationTest {
@Test @Test
public void testRegister() { public void testRegister() {
doReturn(false).when(registration).isRegisterEnabled(); doReturn(false).when(registration).isRegisterEnabled();
try { assertThatCode(() -> {
polarisAutoServiceRegistration.register(); polarisAutoServiceRegistration.register();
} }).doesNotThrowAnyException();
catch (Exception e) {
fail();
}
doReturn(true).when(registration).isRegisterEnabled(); doReturn(true).when(registration).isRegisterEnabled();
try { assertThatCode(() -> {
polarisAutoServiceRegistration.register(); polarisAutoServiceRegistration.register();
} }).doesNotThrowAnyException();
catch (Exception e) {
fail();
}
} }
@Test @Test
@ -105,20 +102,14 @@ public class PolarisAutoServiceRegistrationTest {
@Test @Test
public void testRegisterManagement() { public void testRegisterManagement() {
doReturn(false).when(registration).isRegisterEnabled(); doReturn(false).when(registration).isRegisterEnabled();
try { assertThatCode(() -> {
polarisAutoServiceRegistration.registerManagement(); polarisAutoServiceRegistration.registerManagement();
} }).doesNotThrowAnyException();
catch (Exception e) {
fail();
}
doReturn(true).when(registration).isRegisterEnabled(); doReturn(true).when(registration).isRegisterEnabled();
try { assertThatCode(() -> {
polarisAutoServiceRegistration.registerManagement(); polarisAutoServiceRegistration.registerManagement();
} }).doesNotThrowAnyException();
catch (Exception e) {
fail();
}
} }
@Test @Test

@ -28,10 +28,12 @@ import com.tencent.polaris.api.config.Configuration;
import com.tencent.polaris.api.config.global.APIConfig; import com.tencent.polaris.api.config.global.APIConfig;
import com.tencent.polaris.api.config.global.GlobalConfig; import com.tencent.polaris.api.config.global.GlobalConfig;
import com.tencent.polaris.client.api.SDKContext; import com.tencent.polaris.client.api.SDKContext;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext; import org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext;
import org.springframework.boot.web.server.WebServer; import org.springframework.boot.web.server.WebServer;
@ -50,7 +52,8 @@ import static org.mockito.Mockito.when;
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
public class PolarisRegistrationTest { public class PolarisRegistrationTest {
private NacosContextProperties nacosContextProperties; private NacosContextProperties nacosContextProperties;
@ -59,8 +62,8 @@ public class PolarisRegistrationTest {
private PolarisRegistration polarisRegistration3; private PolarisRegistration polarisRegistration3;
@Before @BeforeEach
public void setUp() { void setUp() {
// mock PolarisDiscoveryProperties // mock PolarisDiscoveryProperties
PolarisDiscoveryProperties polarisDiscoveryProperties = mock(PolarisDiscoveryProperties.class); PolarisDiscoveryProperties polarisDiscoveryProperties = mock(PolarisDiscoveryProperties.class);
doReturn(SERVICE_PROVIDER).when(polarisDiscoveryProperties).getService(); doReturn(SERVICE_PROVIDER).when(polarisDiscoveryProperties).getService();

@ -21,9 +21,9 @@ import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryAutoConfiguration; import com.tencent.cloud.polaris.discovery.PolarisDiscoveryAutoConfiguration;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClientConfiguration; import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClientConfiguration;
import com.tencent.polaris.test.mock.discovery.NamingServer; import com.tencent.polaris.test.mock.discovery.NamingServer;
import org.junit.AfterClass; import org.junit.jupiter.api.AfterAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@ -53,13 +53,13 @@ public class PolarisServiceRegistryAutoConfigurationTest {
.withPropertyValues("server.port=" + PORT) .withPropertyValues("server.port=" + PORT)
.withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081"); .withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081");
@BeforeClass @BeforeAll
public static void beforeClass() throws Exception { static void beforeAll() throws Exception {
namingServer = NamingServer.startNamingServer(10081); namingServer = NamingServer.startNamingServer(10081);
} }
@AfterClass @AfterAll
public static void afterClass() { static void afterAll() {
if (null != namingServer) { if (null != namingServer) {
namingServer.terminate(); namingServer.terminate();
} }

@ -22,9 +22,9 @@ import com.tencent.cloud.polaris.discovery.PolarisDiscoveryAutoConfiguration;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClientConfiguration; import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClientConfiguration;
import com.tencent.polaris.api.pojo.ServiceKey; import com.tencent.polaris.api.pojo.ServiceKey;
import com.tencent.polaris.test.mock.discovery.NamingServer; import com.tencent.polaris.test.mock.discovery.NamingServer;
import org.junit.AfterClass; import org.junit.jupiter.api.AfterAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
@ -36,7 +36,7 @@ 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.PORT;
import static com.tencent.polaris.test.common.Consts.SERVICE_PROVIDER; import static com.tencent.polaris.test.common.Consts.SERVICE_PROVIDER;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.assertj.core.api.Assertions.assertThatCode;
import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -61,16 +61,16 @@ public class PolarisServiceRegistryTest {
.withPropertyValues("spring.cloud.polaris.discovery.namespace=" + NAMESPACE_TEST) .withPropertyValues("spring.cloud.polaris.discovery.namespace=" + NAMESPACE_TEST)
.withPropertyValues("spring.cloud.polaris.discovery.token=xxxxxx"); .withPropertyValues("spring.cloud.polaris.discovery.token=xxxxxx");
@BeforeClass @BeforeAll
public static void beforeClass() throws Exception { static void beforeAll() throws Exception {
namingServer = NamingServer.startNamingServer(10081); namingServer = NamingServer.startNamingServer(10081);
// add service // add service
namingServer.getNamingService().addService(new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER)); namingServer.getNamingService().addService(new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER));
} }
@AfterClass @AfterAll
public static void afterClass() { static void afterAll() {
if (null != namingServer) { if (null != namingServer) {
namingServer.terminate(); namingServer.terminate();
} }
@ -85,26 +85,17 @@ public class PolarisServiceRegistryTest {
when(registration.getPort()).thenReturn(PORT); when(registration.getPort()).thenReturn(PORT);
when(registration.getServiceId()).thenReturn(SERVICE_PROVIDER); when(registration.getServiceId()).thenReturn(SERVICE_PROVIDER);
try { assertThatCode(() -> {
registry.register(registration); registry.register(registration);
} }).doesNotThrowAnyException();
catch (Exception e) {
fail();
}
try { assertThatCode(() -> {
assertThat(registry.getStatus(registration)).isEqualTo("DOWN"); assertThat(registry.getStatus(registration)).isEqualTo("DOWN");
} }).doesNotThrowAnyException();
catch (Exception e) {
fail();
}
try { assertThatCode(() -> {
registry.deregister(registration); registry.deregister(registration);
} }).doesNotThrowAnyException();
catch (Exception e) {
fail();
}
}); });
} }
@ -114,12 +105,9 @@ public class PolarisServiceRegistryTest {
PolarisServiceRegistry registry = context.getBean(PolarisServiceRegistry.class); PolarisServiceRegistry registry = context.getBean(PolarisServiceRegistry.class);
PolarisRegistration registration = Mockito.mock(PolarisRegistration.class); PolarisRegistration registration = Mockito.mock(PolarisRegistration.class);
doReturn(null).when(registration).getServiceId(); doReturn(null).when(registration).getServiceId();
try { assertThatCode(() -> {
registry.deregister(registration); registry.deregister(registration);
} }).doesNotThrowAnyException();
catch (Throwable throwable) {
fail();
}
}); });
} }

@ -18,13 +18,13 @@
package com.tencent.cloud.polaris.util; package com.tencent.cloud.polaris.util;
import org.assertj.core.util.Maps; import org.assertj.core.util.Maps;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@ -35,7 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@RunWith(SpringRunner.class) @ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = OkHttpUtilTest.TestApplication.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = OkHttpUtilTest.TestApplication.class)
public class OkHttpUtilTest { public class OkHttpUtilTest {

@ -63,6 +63,12 @@
<groupId>com.tencent.polaris</groupId> <groupId>com.tencent.polaris</groupId>
<artifactId>polaris-test-mock-discovery</artifactId> <artifactId>polaris-test-mock-discovery</artifactId>
<scope>test</scope> <scope>test</scope>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<!-- Polaris dependencies end --> <!-- Polaris dependencies end -->

@ -26,8 +26,8 @@ import java.util.Set;
import com.tencent.cloud.common.util.expresstion.ExpressionLabelUtils; import com.tencent.cloud.common.util.expresstion.ExpressionLabelUtils;
import com.tencent.cloud.polaris.context.ServiceRuleManager; import com.tencent.cloud.polaris.context.ServiceRuleManager;
import com.tencent.polaris.client.pb.ModelProto; import com.tencent.polaris.specification.api.v1.model.ModelProto;
import com.tencent.polaris.client.pb.RateLimitProto; import com.tencent.polaris.specification.api.v1.traffic.manage.RateLimitProto;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;

@ -28,7 +28,7 @@ import com.tencent.cloud.common.metadata.MetadataContext;
import com.tencent.cloud.common.util.JacksonUtils; import com.tencent.cloud.common.util.JacksonUtils;
import com.tencent.cloud.polaris.context.ServiceRuleManager; import com.tencent.cloud.polaris.context.ServiceRuleManager;
import com.tencent.cloud.polaris.ratelimit.config.PolarisRateLimitProperties; import com.tencent.cloud.polaris.ratelimit.config.PolarisRateLimitProperties;
import com.tencent.polaris.client.pb.RateLimitProto; import com.tencent.polaris.specification.api.v1.traffic.manage.RateLimitProto;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;

@ -21,12 +21,12 @@ import java.util.Set;
import com.google.protobuf.StringValue; import com.google.protobuf.StringValue;
import com.tencent.cloud.polaris.context.ServiceRuleManager; import com.tencent.cloud.polaris.context.ServiceRuleManager;
import com.tencent.polaris.client.pb.ModelProto; import com.tencent.polaris.specification.api.v1.model.ModelProto;
import com.tencent.polaris.client.pb.RateLimitProto; import com.tencent.polaris.specification.api.v1.traffic.manage.RateLimitProto;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
@ -39,13 +39,13 @@ import static org.mockito.Mockito.when;
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class RateLimitRuleLabelResolverTest { public class RateLimitRuleLabelResolverTest {
private RateLimitRuleLabelResolver rateLimitRuleLabelResolver; private RateLimitRuleLabelResolver rateLimitRuleLabelResolver;
@Before @BeforeEach
public void setUp() { void setUp() {
ServiceRuleManager serviceRuleManager = mock(ServiceRuleManager.class); ServiceRuleManager serviceRuleManager = mock(ServiceRuleManager.class);
when(serviceRuleManager.getServiceRateLimitRule(any(), anyString())).thenAnswer(invocationOnMock -> { when(serviceRuleManager.getServiceRateLimitRule(any(), anyString())).thenAnswer(invocationOnMock -> {
String serviceName = invocationOnMock.getArgument(1).toString(); String serviceName = invocationOnMock.getArgument(1).toString();
@ -61,7 +61,7 @@ public class RateLimitRuleLabelResolverTest {
} }
else { else {
ModelProto.MatchString matchString = ModelProto.MatchString.newBuilder() ModelProto.MatchString matchString = ModelProto.MatchString.newBuilder()
.setType(ModelProto.Operation.EXACT) .setType(ModelProto.MatchString.MatchStringType.EXACT)
.setValue(StringValue.of("value")) .setValue(StringValue.of("value"))
.setValueType(ModelProto.MatchString.ValueType.TEXT).build(); .setValueType(ModelProto.MatchString.ValueType.TEXT).build();
RateLimitProto.Rule rule = RateLimitProto.Rule.newBuilder() RateLimitProto.Rule rule = RateLimitProto.Rule.newBuilder()

@ -22,7 +22,7 @@ import com.tencent.cloud.polaris.ratelimit.RateLimitRuleLabelResolver;
import com.tencent.cloud.polaris.ratelimit.filter.QuotaCheckReactiveFilter; import com.tencent.cloud.polaris.ratelimit.filter.QuotaCheckReactiveFilter;
import com.tencent.cloud.polaris.ratelimit.filter.QuotaCheckServletFilter; import com.tencent.cloud.polaris.ratelimit.filter.QuotaCheckServletFilter;
import com.tencent.polaris.ratelimit.api.core.LimitAPI; import com.tencent.polaris.ratelimit.api.core.LimitAPI;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ApplicationContextRunner;

@ -17,7 +17,8 @@
package com.tencent.cloud.polaris.ratelimit.config; package com.tencent.cloud.polaris.ratelimit.config;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ApplicationContextRunner;

@ -17,7 +17,7 @@
package com.tencent.cloud.polaris.ratelimit.config; package com.tencent.cloud.polaris.ratelimit.config;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ApplicationContextRunner;

@ -17,14 +17,14 @@
package com.tencent.cloud.polaris.ratelimit.config; package com.tencent.cloud.polaris.ratelimit.config;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -33,7 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@RunWith(SpringRunner.class) @ExtendWith(SpringExtension.class)
@SpringBootTest(classes = PolarisRateLimitPropertiesTest.TestApplication.class) @SpringBootTest(classes = PolarisRateLimitPropertiesTest.TestApplication.class)
@ActiveProfiles("test") @ActiveProfiles("test")
public class PolarisRateLimitPropertiesTest { public class PolarisRateLimitPropertiesTest {

@ -23,12 +23,11 @@ import com.tencent.polaris.ratelimit.api.rpc.QuotaResponse;
import com.tencent.polaris.ratelimit.api.rpc.QuotaResultCode; import com.tencent.polaris.ratelimit.api.rpc.QuotaResultCode;
import com.tencent.polaris.test.mock.discovery.NamingServer; import com.tencent.polaris.test.mock.discovery.NamingServer;
import com.tencent.polaris.test.mock.discovery.NamingService; import com.tencent.polaris.test.mock.discovery.NamingService;
import org.junit.AfterClass; import org.junit.jupiter.api.AfterAll;
import org.junit.Assert; import org.junit.jupiter.api.BeforeAll;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.BeforeClass; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@ -37,7 +36,7 @@ import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.web.client.HttpClientErrorException.TooManyRequests; import org.springframework.web.client.HttpClientErrorException.TooManyRequests;
import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
@ -45,6 +44,8 @@ import org.springframework.web.client.RestTemplate;
import static com.tencent.polaris.test.common.Consts.NAMESPACE_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.PORT;
import static com.tencent.polaris.test.common.Consts.SERVICE_PROVIDER; import static com.tencent.polaris.test.common.Consts.SERVICE_PROVIDER;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Fail.fail;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -54,7 +55,7 @@ import static org.mockito.Mockito.when;
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@RunWith(SpringRunner.class) @ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = {CalleeControllerTests.Config.class, TestController.class}, classes = {CalleeControllerTests.Config.class, TestController.class},
properties = {"spring.application.name=java_provider_test", "spring.cloud.polaris.discovery.namespace=Test", properties = {"spring.application.name=java_provider_test", "spring.cloud.polaris.discovery.namespace=Test",
@ -72,8 +73,8 @@ public class CalleeControllerTests {
@MockBean @MockBean
private LimitAPI limitAPI; private LimitAPI limitAPI;
@BeforeClass @BeforeAll
public static void beforeClass() throws Exception { static void beforeAll() throws Exception {
namingServer = NamingServer.startNamingServer(10081); namingServer = NamingServer.startNamingServer(10081);
// add service with 3 instances // add service with 3 instances
@ -85,15 +86,15 @@ public class CalleeControllerTests {
namingServer.getNamingService().batchAddInstances(serviceKey, PORT, 3, instanceParameter); namingServer.getNamingService().batchAddInstances(serviceKey, PORT, 3, instanceParameter);
} }
@AfterClass @AfterAll
public static void afterClass() { static void afterAll() {
if (null != namingServer) { if (null != namingServer) {
namingServer.terminate(); namingServer.terminate();
} }
} }
@Before @BeforeEach
public void setUp() { void setUp() {
QuotaResponse quotaResponse = mock(QuotaResponse.class); QuotaResponse quotaResponse = mock(QuotaResponse.class);
when(quotaResponse.getCode()).thenReturn(QuotaResultCode.QuotaResultOk); when(quotaResponse.getCode()).thenReturn(QuotaResultCode.QuotaResultOk);
when(limitAPI.getQuota(any())).thenReturn(quotaResponse); when(limitAPI.getQuota(any())).thenReturn(quotaResponse);
@ -124,12 +125,12 @@ public class CalleeControllerTests {
} }
else { else {
e.printStackTrace(); e.printStackTrace();
Assert.fail(e.getMessage()); fail(e.getMessage());
} }
} }
} }
Assert.assertTrue(hasPassed); assertThat(hasPassed).isTrue();
Assert.assertTrue(hasLimited); assertThat(hasLimited).isTrue();
} }
@Configuration @Configuration

@ -22,12 +22,12 @@ import java.util.Map;
import com.google.protobuf.StringValue; import com.google.protobuf.StringValue;
import com.tencent.cloud.polaris.context.ServiceRuleManager; import com.tencent.cloud.polaris.context.ServiceRuleManager;
import com.tencent.cloud.polaris.ratelimit.config.PolarisRateLimitProperties; import com.tencent.cloud.polaris.ratelimit.config.PolarisRateLimitProperties;
import com.tencent.polaris.client.pb.ModelProto; import com.tencent.polaris.specification.api.v1.model.ModelProto;
import com.tencent.polaris.client.pb.RateLimitProto; import com.tencent.polaris.specification.api.v1.traffic.manage.RateLimitProto;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@ -48,7 +48,7 @@ import static org.mockito.Mockito.when;
* *
* @author shuiqingliu * @author shuiqingliu
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class PolarisRateLimitRuleEndpointTests { public class PolarisRateLimitRuleEndpointTests {
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
@ -66,8 +66,8 @@ public class PolarisRateLimitRuleEndpointTests {
private ServiceRuleManager serviceRuleManager; private ServiceRuleManager serviceRuleManager;
private PolarisRateLimitProperties polarisRateLimitProperties; private PolarisRateLimitProperties polarisRateLimitProperties;
@Before @BeforeEach
public void setUp() { void setUp() {
serviceRuleManager = mock(ServiceRuleManager.class); serviceRuleManager = mock(ServiceRuleManager.class);
when(serviceRuleManager.getServiceRateLimitRule(any(), anyString())).thenAnswer(invocationOnMock -> { when(serviceRuleManager.getServiceRateLimitRule(any(), anyString())).thenAnswer(invocationOnMock -> {
String serviceName = invocationOnMock.getArgument(1).toString(); String serviceName = invocationOnMock.getArgument(1).toString();
@ -83,7 +83,7 @@ public class PolarisRateLimitRuleEndpointTests {
} }
else { else {
ModelProto.MatchString matchString = ModelProto.MatchString.newBuilder() ModelProto.MatchString matchString = ModelProto.MatchString.newBuilder()
.setType(ModelProto.Operation.EXACT) .setType(ModelProto.MatchString.MatchStringType.EXACT)
.setValue(StringValue.of("value")) .setValue(StringValue.of("value"))
.setValueType(ModelProto.MatchString.ValueType.TEXT).build(); .setValueType(ModelProto.MatchString.ValueType.TEXT).build();
RateLimitProto.Rule rule = RateLimitProto.Rule.newBuilder() RateLimitProto.Rule rule = RateLimitProto.Rule.newBuilder()

@ -36,14 +36,16 @@ import com.tencent.polaris.api.plugin.ratelimiter.QuotaResult;
import com.tencent.polaris.ratelimit.api.core.LimitAPI; import com.tencent.polaris.ratelimit.api.core.LimitAPI;
import com.tencent.polaris.ratelimit.api.rpc.QuotaRequest; import com.tencent.polaris.ratelimit.api.rpc.QuotaRequest;
import com.tencent.polaris.ratelimit.api.rpc.QuotaResponse; import com.tencent.polaris.ratelimit.api.rpc.QuotaResponse;
import org.junit.AfterClass; import org.junit.jupiter.api.AfterAll;
import org.junit.Before; import org.junit.jupiter.api.BeforeAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.MockedStatic; import org.mockito.MockedStatic;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import reactor.core.publisher.Mono; import reactor.core.publisher.Mono;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
@ -69,7 +71,8 @@ import static org.mockito.Mockito.when;
* *
* @author Haotian Zhang, kaiy * @author Haotian Zhang, kaiy
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@SpringBootTest(classes = QuotaCheckReactiveFilterTest.TestApplication.class, @SpringBootTest(classes = QuotaCheckReactiveFilterTest.TestApplication.class,
properties = {"spring.cloud.polaris.namespace=Test", "spring.cloud.polaris.service=TestApp"}) properties = {"spring.cloud.polaris.namespace=Test", "spring.cloud.polaris.service=TestApp"})
public class QuotaCheckReactiveFilterTest { public class QuotaCheckReactiveFilterTest {
@ -82,8 +85,8 @@ public class QuotaCheckReactiveFilterTest {
private QuotaCheckReactiveFilter quotaCheckWithRateLimiterLimitedFallbackReactiveFilter; private QuotaCheckReactiveFilter quotaCheckWithRateLimiterLimitedFallbackReactiveFilter;
private PolarisRateLimiterLimitedFallback polarisRateLimiterLimitedFallback; private PolarisRateLimiterLimitedFallback polarisRateLimiterLimitedFallback;
@BeforeClass @BeforeAll
public static void beforeClass() { static void beforeAll() {
expressionLabelUtilsMockedStatic = mockStatic(SpringWebExpressionLabelUtils.class); expressionLabelUtilsMockedStatic = mockStatic(SpringWebExpressionLabelUtils.class);
when(SpringWebExpressionLabelUtils.resolve(any(ServerWebExchange.class), anySet())) when(SpringWebExpressionLabelUtils.resolve(any(ServerWebExchange.class), anySet()))
.thenReturn(Collections.singletonMap("RuleLabelResolver", "RuleLabelResolver")); .thenReturn(Collections.singletonMap("RuleLabelResolver", "RuleLabelResolver"));
@ -93,14 +96,14 @@ public class QuotaCheckReactiveFilterTest {
.thenReturn("unit-test"); .thenReturn("unit-test");
} }
@AfterClass @AfterAll
public static void afterClass() { static void afterAll() {
mockedApplicationContextAwareUtils.close(); mockedApplicationContextAwareUtils.close();
expressionLabelUtilsMockedStatic.close(); expressionLabelUtilsMockedStatic.close();
} }
@Before @BeforeEach
public void setUp() { void setUp() {
MetadataContext.LOCAL_NAMESPACE = "TEST"; MetadataContext.LOCAL_NAMESPACE = "TEST";
polarisRateLimiterLimitedFallback = new JsonPolarisRateLimiterLimitedFallback(); polarisRateLimiterLimitedFallback = new JsonPolarisRateLimiterLimitedFallback();

@ -38,14 +38,16 @@ import com.tencent.polaris.ratelimit.api.rpc.QuotaResponse;
import jakarta.servlet.FilterChain; import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException; import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import org.junit.AfterClass; import org.junit.jupiter.api.AfterAll;
import org.junit.Before; import org.junit.jupiter.api.BeforeAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.MockedStatic; import org.mockito.MockedStatic;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
@ -68,7 +70,8 @@ import static org.mockito.Mockito.when;
* *
* @author Haotian Zhang, cheese8 * @author Haotian Zhang, cheese8
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@SpringBootTest(classes = QuotaCheckServletFilterTest.TestApplication.class, properties = { @SpringBootTest(classes = QuotaCheckServletFilterTest.TestApplication.class, properties = {
"spring.cloud.polaris.namespace=Test", "spring.cloud.polaris.service=TestApp" "spring.cloud.polaris.namespace=Test", "spring.cloud.polaris.service=TestApp"
}) })
@ -83,8 +86,8 @@ public class QuotaCheckServletFilterTest {
private QuotaCheckServletFilter quotaCheckWithRateLimiterLimitedFallbackFilter; private QuotaCheckServletFilter quotaCheckWithRateLimiterLimitedFallbackFilter;
private PolarisRateLimiterLimitedFallback polarisRateLimiterLimitedFallback; private PolarisRateLimiterLimitedFallback polarisRateLimiterLimitedFallback;
@BeforeClass @BeforeAll
public static void beforeClass() { static void beforeAll() {
expressionLabelUtilsMockedStatic = mockStatic(SpringWebExpressionLabelUtils.class); expressionLabelUtilsMockedStatic = mockStatic(SpringWebExpressionLabelUtils.class);
when(SpringWebExpressionLabelUtils.resolve(any(ServerWebExchange.class), anySet())) when(SpringWebExpressionLabelUtils.resolve(any(ServerWebExchange.class), anySet()))
.thenReturn(Collections.singletonMap("RuleLabelResolver", "RuleLabelResolver")); .thenReturn(Collections.singletonMap("RuleLabelResolver", "RuleLabelResolver"));
@ -94,14 +97,14 @@ public class QuotaCheckServletFilterTest {
.thenReturn("unit-test"); .thenReturn("unit-test");
} }
@AfterClass @AfterAll
public static void afterClass() { static void afterAll() {
mockedApplicationContextAwareUtils.close(); mockedApplicationContextAwareUtils.close();
expressionLabelUtilsMockedStatic.close(); expressionLabelUtilsMockedStatic.close();
} }
@Before @BeforeEach
public void setUp() { void setUp() {
MetadataContext.LOCAL_NAMESPACE = "TEST"; MetadataContext.LOCAL_NAMESPACE = "TEST";
LimitAPI limitAPI = mock(LimitAPI.class); LimitAPI limitAPI = mock(LimitAPI.class);
@ -238,6 +241,7 @@ public class QuotaCheckServletFilterTest {
fail("Exception encountered.", e); fail("Exception encountered.", e);
} }
} }
@Test @Test
public void polarisRateLimiterLimitedFallbackTest() { public void polarisRateLimiterLimitedFallbackTest() {
// Create mock FilterChain // Create mock FilterChain

@ -22,10 +22,10 @@ import com.tencent.polaris.ratelimit.api.core.LimitAPI;
import com.tencent.polaris.ratelimit.api.rpc.QuotaRequest; import com.tencent.polaris.ratelimit.api.rpc.QuotaRequest;
import com.tencent.polaris.ratelimit.api.rpc.QuotaResponse; import com.tencent.polaris.ratelimit.api.rpc.QuotaResponse;
import com.tencent.polaris.ratelimit.api.rpc.QuotaResultCode; import com.tencent.polaris.ratelimit.api.rpc.QuotaResultCode;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
@ -37,13 +37,13 @@ import static org.mockito.Mockito.when;
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class QuotaCheckUtilsTest { public class QuotaCheckUtilsTest {
private LimitAPI limitAPI; private LimitAPI limitAPI;
@Before @BeforeEach
public void setUp() { void setUp() {
limitAPI = mock(LimitAPI.class); limitAPI = mock(LimitAPI.class);
when(limitAPI.getQuota(any(QuotaRequest.class))).thenAnswer(invocationOnMock -> { when(limitAPI.getQuota(any(QuotaRequest.class))).thenAnswer(invocationOnMock -> {
String serviceName = ((QuotaRequest) invocationOnMock.getArgument(0)).getService(); String serviceName = ((QuotaRequest) invocationOnMock.getArgument(0)).getService();

@ -21,10 +21,12 @@ import java.io.IOException;
import com.tencent.cloud.common.util.ResourceFileUtils; import com.tencent.cloud.common.util.ResourceFileUtils;
import com.tencent.cloud.polaris.ratelimit.config.PolarisRateLimitProperties; import com.tencent.cloud.polaris.ratelimit.config.PolarisRateLimitProperties;
import org.junit.BeforeClass; import org.junit.jupiter.api.AfterAll;
import org.junit.Test; import org.junit.jupiter.api.BeforeAll;
import org.junit.runner.RunWith; import org.junit.jupiter.api.Test;
import org.mockito.junit.MockitoJUnitRunner; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import static com.tencent.cloud.polaris.ratelimit.constant.RateLimitConstant.QUOTA_LIMITED_INFO; import static com.tencent.cloud.polaris.ratelimit.constant.RateLimitConstant.QUOTA_LIMITED_INFO;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -37,12 +39,14 @@ import static org.mockito.Mockito.when;
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class RateLimitUtilsTest { public class RateLimitUtilsTest {
@BeforeClass private static MockedStatic<ResourceFileUtils> mockedResourceFileUtils;
public static void beforeClass() throws IOException {
mockStatic(ResourceFileUtils.class); @BeforeAll
static void beforeAll() throws IOException {
mockedResourceFileUtils = mockStatic(ResourceFileUtils.class);
when(ResourceFileUtils.readFile(anyString())).thenAnswer(invocation -> { when(ResourceFileUtils.readFile(anyString())).thenAnswer(invocation -> {
String rejectFilePath = invocation.getArgument(0).toString(); String rejectFilePath = invocation.getArgument(0).toString();
if (rejectFilePath.equals("exception.html")) { if (rejectFilePath.equals("exception.html")) {
@ -54,6 +58,11 @@ public class RateLimitUtilsTest {
}); });
} }
@AfterAll
static void afterAll() {
mockedResourceFileUtils.close();
}
@Test @Test
public void testGetRejectTips() { public void testGetRejectTips() {
PolarisRateLimitProperties polarisRateLimitProperties = new PolarisRateLimitProperties(); PolarisRateLimitProperties polarisRateLimitProperties = new PolarisRateLimitProperties();

@ -29,6 +29,12 @@
<dependency> <dependency>
<groupId>com.tencent.polaris</groupId> <groupId>com.tencent.polaris</groupId>
<artifactId>router-rule</artifactId> <artifactId>router-rule</artifactId>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.tencent.polaris</groupId> <groupId>com.tencent.polaris</groupId>

@ -26,8 +26,8 @@ import java.util.Set;
import com.tencent.cloud.common.util.expresstion.ExpressionLabelUtils; import com.tencent.cloud.common.util.expresstion.ExpressionLabelUtils;
import com.tencent.cloud.polaris.context.ServiceRuleManager; import com.tencent.cloud.polaris.context.ServiceRuleManager;
import com.tencent.polaris.client.pb.ModelProto; import com.tencent.polaris.specification.api.v1.model.ModelProto;
import com.tencent.polaris.client.pb.RoutingProto; import com.tencent.polaris.specification.api.v1.traffic.manage.RoutingProto;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;

@ -28,7 +28,7 @@ import com.google.protobuf.util.JsonFormat;
import com.tencent.cloud.common.metadata.MetadataContext; import com.tencent.cloud.common.metadata.MetadataContext;
import com.tencent.cloud.common.util.JacksonUtils; import com.tencent.cloud.common.util.JacksonUtils;
import com.tencent.cloud.polaris.context.ServiceRuleManager; import com.tencent.cloud.polaris.context.ServiceRuleManager;
import com.tencent.polaris.client.pb.RoutingProto; import com.tencent.polaris.specification.api.v1.traffic.manage.RoutingProto;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;

@ -24,8 +24,9 @@ import java.util.Set;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.tencent.cloud.common.constant.RouterConstant; import com.tencent.cloud.common.constant.RouterConstant;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
/** /**
* test for {@link PolarisRouterContext}. * test for {@link PolarisRouterContext}.
@ -43,26 +44,26 @@ public class PolarisRouterContextTest {
PolarisRouterContext routerContext = new PolarisRouterContext(); PolarisRouterContext routerContext = new PolarisRouterContext();
routerContext.putLabels(RouterConstant.ROUTER_LABELS, labels); routerContext.putLabels(RouterConstant.ROUTER_LABELS, labels);
Assert.assertEquals(0, routerContext.getLabels(RouterConstant.TRANSITIVE_LABELS).size()); assertThat(routerContext.getLabels(RouterConstant.TRANSITIVE_LABELS).size()).isEqualTo(0);
Assert.assertEquals(2, routerContext.getLabels(RouterConstant.ROUTER_LABELS).size()); assertThat(routerContext.getLabels(RouterConstant.ROUTER_LABELS).size()).isEqualTo(2);
Assert.assertEquals("v1", routerContext.getLabels(RouterConstant.ROUTER_LABELS).get("k1")); assertThat(routerContext.getLabels(RouterConstant.ROUTER_LABELS).get("k1")).isEqualTo("v1");
Assert.assertEquals("v2", routerContext.getLabels(RouterConstant.ROUTER_LABELS).get("k2")); assertThat(routerContext.getLabels(RouterConstant.ROUTER_LABELS).get("k2")).isEqualTo("v2");
Assert.assertNull(routerContext.getLabels(RouterConstant.ROUTER_LABELS).get("k3")); assertThat(routerContext.getLabels(RouterConstant.ROUTER_LABELS).get("k3")).isNull();
} }
@Test @Test
public void testSetNull() { public void testSetNull() {
PolarisRouterContext routerContext = new PolarisRouterContext(); PolarisRouterContext routerContext = new PolarisRouterContext();
routerContext.putLabels(RouterConstant.ROUTER_LABELS, null); routerContext.putLabels(RouterConstant.ROUTER_LABELS, null);
Assert.assertEquals(0, routerContext.getLabels(RouterConstant.TRANSITIVE_LABELS).size()); assertThat(routerContext.getLabels(RouterConstant.TRANSITIVE_LABELS).size()).isEqualTo(0);
Assert.assertEquals(0, routerContext.getLabels(RouterConstant.ROUTER_LABELS).size()); assertThat(routerContext.getLabels(RouterConstant.ROUTER_LABELS).size()).isEqualTo(0);
} }
@Test @Test
public void testGetEmptyRouterContext() { public void testGetEmptyRouterContext() {
PolarisRouterContext routerContext = new PolarisRouterContext(); PolarisRouterContext routerContext = new PolarisRouterContext();
Assert.assertEquals(0, routerContext.getLabels(RouterConstant.TRANSITIVE_LABELS).size()); assertThat(routerContext.getLabels(RouterConstant.TRANSITIVE_LABELS).size()).isEqualTo(0);
Assert.assertEquals(0, routerContext.getLabels(RouterConstant.ROUTER_LABELS).size()); assertThat(routerContext.getLabels(RouterConstant.ROUTER_LABELS).size()).isEqualTo(0);
} }
@Test @Test
@ -78,9 +79,9 @@ public class PolarisRouterContextTest {
Map<String, String> resolvedLabels = routerContext.getLabels(RouterConstant.ROUTER_LABELS, Map<String, String> resolvedLabels = routerContext.getLabels(RouterConstant.ROUTER_LABELS,
Sets.newHashSet("k1", "k2", "k4")); Sets.newHashSet("k1", "k2", "k4"));
Assert.assertEquals(2, resolvedLabels.size()); assertThat(resolvedLabels.size()).isEqualTo(2);
Assert.assertEquals("v1", resolvedLabels.get("k1")); assertThat(resolvedLabels.get("k1")).isEqualTo("v1");
Assert.assertEquals("v2", resolvedLabels.get("k2")); assertThat(resolvedLabels.get("k2")).isEqualTo("v2");
} }
@Test @Test
@ -94,8 +95,7 @@ public class PolarisRouterContextTest {
routerContext.putLabels(RouterConstant.ROUTER_LABELS, labels); routerContext.putLabels(RouterConstant.ROUTER_LABELS, labels);
String resolvedLabel = routerContext.getLabel("k1"); String resolvedLabel = routerContext.getLabel("k1");
assertThat(resolvedLabel).isEqualTo("v1");
Assert.assertEquals("v1", resolvedLabel);
} }
@Test @Test
@ -108,9 +108,9 @@ public class PolarisRouterContextTest {
Set<String> resolvedLabels = routerContext.getLabelAsSet("k1"); Set<String> resolvedLabels = routerContext.getLabelAsSet("k1");
Assert.assertEquals(3, resolvedLabels.size()); assertThat(resolvedLabels.size()).isEqualTo(3);
Assert.assertTrue(resolvedLabels.contains("v1")); assertThat(resolvedLabels).contains("v1");
Assert.assertTrue(resolvedLabels.contains("v2")); assertThat(resolvedLabels).contains("v2");
Assert.assertTrue(resolvedLabels.contains("v3")); assertThat(resolvedLabels).contains("v3");
} }
} }

@ -52,15 +52,13 @@ import com.tencent.polaris.plugins.router.rule.RuleBasedRouter;
import com.tencent.polaris.router.api.core.RouterAPI; import com.tencent.polaris.router.api.core.RouterAPI;
import com.tencent.polaris.router.api.rpc.ProcessRoutersRequest; import com.tencent.polaris.router.api.rpc.ProcessRoutersRequest;
import com.tencent.polaris.router.api.rpc.ProcessRoutersResponse; import com.tencent.polaris.router.api.rpc.ProcessRoutersResponse;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.Assertions;
import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockedStatic; import org.mockito.MockedStatic;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Flux; import reactor.core.publisher.Flux;
import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.ServiceInstance;
@ -71,6 +69,7 @@ import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
@ -81,7 +80,7 @@ import static org.mockito.Mockito.when;
* *
* @author lepdou 2022-05-26 * @author lepdou 2022-05-26
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class PolarisRouterServiceInstanceListSupplierTest { public class PolarisRouterServiceInstanceListSupplierTest {
private static final AtomicBoolean initTransitiveMetadata = new AtomicBoolean(false); private static final AtomicBoolean initTransitiveMetadata = new AtomicBoolean(false);
@ -100,8 +99,8 @@ public class PolarisRouterServiceInstanceListSupplierTest {
@Mock @Mock
private RouterAPI routerAPI; private RouterAPI routerAPI;
@Before @BeforeEach
public void before() { void setUp() {
requestInterceptors.add(new MetadataRouterRequestInterceptor(polarisMetadataRouterProperties)); requestInterceptors.add(new MetadataRouterRequestInterceptor(polarisMetadataRouterProperties));
requestInterceptors.add(new NearbyRouterRequestInterceptor(polarisNearByRouterProperties)); requestInterceptors.add(new NearbyRouterRequestInterceptor(polarisNearByRouterProperties));
requestInterceptors.add(new RuleBasedRouterRequestInterceptor(polarisRuleBasedRouterProperties)); requestInterceptors.add(new RuleBasedRouterRequestInterceptor(polarisRuleBasedRouterProperties));
@ -133,13 +132,13 @@ public class PolarisRouterServiceInstanceListSupplierTest {
Set<RouteArgument> routerMetadata = request.getRouterArguments(MetadataRouter.ROUTER_TYPE_METADATA); Set<RouteArgument> routerMetadata = request.getRouterArguments(MetadataRouter.ROUTER_TYPE_METADATA);
Assert.assertEquals(1, routerMetadata.size()); assertThat(routerMetadata.size()).isEqualTo(1);
Assert.assertEquals(0, request.getRouterArguments(NearbyRouter.ROUTER_TYPE_NEAR_BY).size()); assertThat(request.getRouterArguments(NearbyRouter.ROUTER_TYPE_NEAR_BY).size()).isEqualTo(0);
Assert.assertEquals(1, request.getRouterArguments(RuleBasedRouter.ROUTER_TYPE_RULE_BASED).size()); assertThat(request.getRouterArguments(RuleBasedRouter.ROUTER_TYPE_RULE_BASED).size()).isEqualTo(1);
for (RouteArgument routeArgument : request.getRouterArguments(RuleBasedRouter.ROUTER_TYPE_RULE_BASED)) { for (RouteArgument routeArgument : request.getRouterArguments(RuleBasedRouter.ROUTER_TYPE_RULE_BASED)) {
Assert.assertEquals(RuleBasedRouter.ROUTER_ENABLED, routeArgument.getKey()); assertThat(routeArgument.getKey()).isEqualTo(RuleBasedRouter.ROUTER_ENABLED);
Assert.assertEquals("false", routeArgument.getValue()); assertThat(routeArgument.getValue()).isEqualTo("false");
} }
} }
} }
@ -165,19 +164,19 @@ public class PolarisRouterServiceInstanceListSupplierTest {
Set<RouteArgument> routerMetadata = request.getRouterArguments(NearbyRouter.ROUTER_TYPE_NEAR_BY); Set<RouteArgument> routerMetadata = request.getRouterArguments(NearbyRouter.ROUTER_TYPE_NEAR_BY);
Assert.assertEquals(0, request.getRouterArguments(MetadataRouter.ROUTER_TYPE_METADATA).size()); assertThat(request.getRouterArguments(MetadataRouter.ROUTER_TYPE_METADATA).size()).isEqualTo(0);
Assert.assertEquals(1, routerMetadata.size()); assertThat(routerMetadata.size()).isEqualTo(1);
for (RouteArgument routeArgument : routerMetadata) { for (RouteArgument routeArgument : routerMetadata) {
Assert.assertEquals(NearbyRouter.ROUTER_ENABLED, routeArgument.getKey()); assertThat(routeArgument.getKey()).isEqualTo(RuleBasedRouter.ROUTER_ENABLED);
Assert.assertEquals("true", routeArgument.getValue()); assertThat(routeArgument.getValue()).isEqualTo("true");
} }
Assert.assertEquals(1, request.getRouterArguments(RuleBasedRouter.ROUTER_TYPE_RULE_BASED).size()); assertThat(request.getRouterArguments(RuleBasedRouter.ROUTER_TYPE_RULE_BASED).size()).isEqualTo(1);
for (RouteArgument routeArgument : request.getRouterArguments(RuleBasedRouter.ROUTER_TYPE_RULE_BASED)) { for (RouteArgument routeArgument : request.getRouterArguments(RuleBasedRouter.ROUTER_TYPE_RULE_BASED)) {
Assert.assertEquals(RuleBasedRouter.ROUTER_ENABLED, routeArgument.getKey()); assertThat(routeArgument.getKey()).isEqualTo(RuleBasedRouter.ROUTER_ENABLED);
Assert.assertEquals("false", routeArgument.getValue()); assertThat(routeArgument.getValue()).isEqualTo("false");
} }
} }
} }
@ -203,9 +202,9 @@ public class PolarisRouterServiceInstanceListSupplierTest {
Set<RouteArgument> routerMetadata = request.getRouterArguments(RuleBasedRouter.ROUTER_TYPE_RULE_BASED); Set<RouteArgument> routerMetadata = request.getRouterArguments(RuleBasedRouter.ROUTER_TYPE_RULE_BASED);
Assert.assertEquals(3, routerMetadata.size()); assertThat(routerMetadata.size()).isEqualTo(3);
Assert.assertEquals(0, request.getRouterArguments(MetadataRouter.ROUTER_TYPE_METADATA).size()); assertThat(request.getRouterArguments(MetadataRouter.ROUTER_TYPE_METADATA).size()).isEqualTo(0);
Assert.assertEquals(0, request.getRouterArguments(NearbyRouter.ROUTER_TYPE_NEAR_BY).size()); assertThat(request.getRouterArguments(NearbyRouter.ROUTER_TYPE_NEAR_BY).size()).isEqualTo(0);
} }
} }
@ -227,9 +226,8 @@ public class PolarisRouterServiceInstanceListSupplierTest {
Flux<List<ServiceInstance>> servers = polarisSupplier.doRouter(assembleServers(), assembleRouterContext()); Flux<List<ServiceInstance>> servers = polarisSupplier.doRouter(assembleServers(), assembleRouterContext());
assertThat(servers.toStream().mapToLong(List::size).sum()).isEqualTo(assembleResponse.getServiceInstances()
Assert.assertEquals(assembleResponse.getServiceInstances().getInstances().size(), .getInstances().size());
servers.toStream().mapToLong(List::size).sum());
} }
} }
@ -240,7 +238,7 @@ public class PolarisRouterServiceInstanceListSupplierTest {
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
PolarisRouterContext context = polarisSupplier.buildRouterContext(headers); PolarisRouterContext context = polarisSupplier.buildRouterContext(headers);
Assert.assertNull(context); assertThat(context).isNull();
// mock // mock
try (MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class)) { try (MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class)) {
@ -259,7 +257,7 @@ public class PolarisRouterServiceInstanceListSupplierTest {
public void testGet01() { public void testGet01() {
PolarisRouterServiceInstanceListSupplier polarisSupplier = new PolarisRouterServiceInstanceListSupplier( PolarisRouterServiceInstanceListSupplier polarisSupplier = new PolarisRouterServiceInstanceListSupplier(
delegate, routerAPI, requestInterceptors, null); delegate, routerAPI, requestInterceptors, null);
Assertions.assertThrows(PolarisException.class, () -> polarisSupplier.get()); assertThatThrownBy(() -> polarisSupplier.get()).isInstanceOf(PolarisException.class);
} }
@Test @Test
@ -277,7 +275,7 @@ public class PolarisRouterServiceInstanceListSupplierTest {
.build(); .build();
RequestDataContext requestDataContext = new RequestDataContext(new RequestData(httpRequest), "blue"); RequestDataContext requestDataContext = new RequestDataContext(new RequestData(httpRequest), "blue");
DefaultRequest request = new DefaultRequest(requestDataContext); DefaultRequest request = new DefaultRequest(requestDataContext);
Assert.assertNull(polarisSupplier.get(request)); assertThat(polarisSupplier.get(request)).isNull();
} }
} }

@ -24,31 +24,30 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import com.google.common.collect.Lists;
import com.tencent.cloud.polaris.context.ServiceRuleManager; import com.tencent.cloud.polaris.context.ServiceRuleManager;
import com.tencent.polaris.client.pb.ModelProto; import com.tencent.polaris.specification.api.v1.model.ModelProto;
import com.tencent.polaris.client.pb.RoutingProto; import com.tencent.polaris.specification.api.v1.traffic.manage.RoutingProto;
import org.junit.Assert; import org.assertj.core.util.Lists;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
/** /**
* test for {@link RouterRuleLabelResolver}. * test for {@link RouterRuleLabelResolver}.
*@author lepdou 2022-05-26 *@author lepdou 2022-05-26
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class RouterRuleLabelResolverTest { public class RouterRuleLabelResolverTest {
@Mock
private ServiceRuleManager serviceRuleManager;
private final String testNamespace = "testNamespace"; private final String testNamespace = "testNamespace";
private final String testSourceService = "sourceService"; private final String testSourceService = "sourceService";
private final String testDstService = "dstService"; private final String testDstService = "dstService";
@Mock
private ServiceRuleManager serviceRuleManager;
@Test @Test
public void test() { public void test() {
@ -73,7 +72,7 @@ public class RouterRuleLabelResolverTest {
List<RoutingProto.Route> routes = new LinkedList<>(); List<RoutingProto.Route> routes = new LinkedList<>();
RoutingProto.Route route = RoutingProto.Route.newBuilder() RoutingProto.Route route = RoutingProto.Route.newBuilder()
.addAllSources(Lists.newArrayList(source1, source2, source3)) .addAllSources(Lists.list(source1, source2, source3))
.build(); .build();
routes.add(route); routes.add(route);
@ -83,13 +82,13 @@ public class RouterRuleLabelResolverTest {
Set<String> resolvedExpressionLabelKeys = resolver.getExpressionLabelKeys(testNamespace, testSourceService, testDstService); Set<String> resolvedExpressionLabelKeys = resolver.getExpressionLabelKeys(testNamespace, testSourceService, testDstService);
Assert.assertNotNull(resolvedExpressionLabelKeys); assertThat(resolvedExpressionLabelKeys).isNotNull();
Assert.assertEquals(6, resolvedExpressionLabelKeys.size()); assertThat(resolvedExpressionLabelKeys.size()).isEqualTo(6);
Assert.assertTrue(resolvedExpressionLabelKeys.contains(validKey1)); assertThat(resolvedExpressionLabelKeys).contains(validKey1);
Assert.assertTrue(resolvedExpressionLabelKeys.contains(validKey2)); assertThat(resolvedExpressionLabelKeys).contains(validKey2);
Assert.assertTrue(resolvedExpressionLabelKeys.contains(validKey3)); assertThat(resolvedExpressionLabelKeys).contains(validKey3);
Assert.assertTrue(resolvedExpressionLabelKeys.contains(validKey4)); assertThat(resolvedExpressionLabelKeys).contains(validKey4);
Assert.assertTrue(resolvedExpressionLabelKeys.contains(validKey5)); assertThat(resolvedExpressionLabelKeys).contains(validKey5);
Assert.assertTrue(resolvedExpressionLabelKeys.contains(invalidKey)); assertThat(resolvedExpressionLabelKeys).contains(invalidKey);
} }
} }

@ -27,58 +27,47 @@ import com.tencent.cloud.common.util.ApplicationContextAwareUtils;
import com.tencent.polaris.api.pojo.DefaultInstance; import com.tencent.polaris.api.pojo.DefaultInstance;
import com.tencent.polaris.api.pojo.Instance; import com.tencent.polaris.api.pojo.Instance;
import com.tencent.polaris.api.pojo.ServiceInstances; import com.tencent.polaris.api.pojo.ServiceInstances;
import org.junit.AfterClass; import org.junit.jupiter.api.Test;
import org.junit.Assert; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockedStatic; import org.mockito.MockedStatic;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Flux; import reactor.core.publisher.Flux;
import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.ServiceInstance;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mockStatic;
/** /**
* Test for ${@link RouterUtils}. * Test for ${@link RouterUtils}.
* *
* @author lepdou 2022-07-04 * @author lepdou 2022-07-04
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class RouterUtilsTest { public class RouterUtilsTest {
private static final String testNamespaceAndService = "testNamespaceAndService"; private static final String testNamespaceAndService = "testNamespaceAndService";
private static MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils;
private static MockedStatic<MetadataContextHolder> mockedMetadataContextHolder;
@BeforeClass
public static void beforeClass() {
mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class);
mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString()))
.thenReturn(testNamespaceAndService);
MetadataContext metadataContext = Mockito.mock(MetadataContext.class);
mockedMetadataContextHolder = Mockito.mockStatic(MetadataContextHolder.class);
mockedMetadataContextHolder.when(MetadataContextHolder::get).thenReturn(metadataContext);
}
@AfterClass
public static void afterClass() {
mockedApplicationContextAwareUtils.close();
mockedMetadataContextHolder.close();
}
@Test @Test
public void testTransferEmptyInstances() { public void testTransferEmptyInstances() {
ServiceInstances serviceInstances = RouterUtils.transferServersToServiceInstances(Flux.empty()); ServiceInstances serviceInstances = RouterUtils.transferServersToServiceInstances(Flux.empty());
Assert.assertNotNull(serviceInstances.getInstances()); assertThat(serviceInstances.getInstances()).isNotNull();
Assert.assertEquals(0, serviceInstances.getInstances().size()); assertThat(serviceInstances.getInstances()).isEmpty();
} }
@Test @Test
public void testTransferNotEmptyInstances() { public void testTransferNotEmptyInstances() {
try (
MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils = mockStatic(ApplicationContextAwareUtils.class);
MockedStatic<MetadataContextHolder> mockedMetadataContextHolder = mockStatic(MetadataContextHolder.class)
) {
mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString()))
.thenReturn(testNamespaceAndService);
MetadataContext metadataContext = Mockito.mock(MetadataContext.class);
mockedMetadataContextHolder.when(MetadataContextHolder::get).thenReturn(metadataContext);
int instanceSize = 100; int instanceSize = 100;
int weight = 50; int weight = 50;
@ -95,18 +84,19 @@ public class RouterUtilsTest {
ServiceInstances serviceInstances = RouterUtils.transferServersToServiceInstances(Flux.just(instances)); ServiceInstances serviceInstances = RouterUtils.transferServersToServiceInstances(Flux.just(instances));
Assert.assertNotNull(serviceInstances.getInstances()); assertThat(serviceInstances.getInstances()).isNotNull();
Assert.assertEquals(instanceSize, serviceInstances.getInstances().size()); assertThat(serviceInstances.getInstances().size()).isEqualTo(instanceSize);
List<Instance> polarisInstances = serviceInstances.getInstances(); List<Instance> polarisInstances = serviceInstances.getInstances();
for (int i = 0; i < instanceSize; i++) { for (int i = 0; i < instanceSize; i++) {
Instance instance = polarisInstances.get(i); Instance instance = polarisInstances.get(i);
Assert.assertEquals(testNamespaceAndService, instance.getNamespace()); assertThat(instance.getNamespace()).isEqualTo(testNamespaceAndService);
Assert.assertEquals(testNamespaceAndService, instance.getService()); assertThat(instance.getService()).isEqualTo(testNamespaceAndService);
Assert.assertEquals("ins" + i, instance.getId()); assertThat(instance.getId()).isEqualTo("ins" + i);
Assert.assertEquals("127.0.0." + i, instance.getHost()); assertThat(instance.getHost()).isEqualTo("127.0.0." + i);
Assert.assertEquals(8080, instance.getPort()); assertThat(instance.getPort()).isEqualTo(8080);
Assert.assertEquals(weight, instance.getWeight()); assertThat(instance.getWeight()).isEqualTo(weight);
}
} }
} }
} }

@ -22,19 +22,19 @@ import com.tencent.cloud.common.util.BeanFactoryUtils;
import com.tencent.cloud.polaris.router.RouterRuleLabelResolver; import com.tencent.cloud.polaris.router.RouterRuleLabelResolver;
import com.tencent.cloud.polaris.router.scg.PolarisReactiveLoadBalancerClientFilter; import com.tencent.cloud.polaris.router.scg.PolarisReactiveLoadBalancerClientFilter;
import com.tencent.cloud.polaris.router.spi.SpringWebRouterLabelResolver; import com.tencent.cloud.polaris.router.spi.SpringWebRouterLabelResolver;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockedStatic; import org.mockito.MockedStatic;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactory;
import org.springframework.cloud.gateway.config.GatewayLoadBalancerProperties; import org.springframework.cloud.gateway.config.GatewayLoadBalancerProperties;
import org.springframework.cloud.gateway.filter.ReactiveLoadBalancerClientFilter; import org.springframework.cloud.gateway.filter.ReactiveLoadBalancerClientFilter;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory; import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -43,7 +43,7 @@ import static org.mockito.Mockito.when;
* *
* @author lepdou 2022-07-04 * @author lepdou 2022-07-04
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class ReactiveLoadBalancerClientFilterBeanPostProcessorTest { public class ReactiveLoadBalancerClientFilterBeanPostProcessorTest {
@Mock @Mock
@ -75,8 +75,7 @@ public class ReactiveLoadBalancerClientFilterBeanPostProcessorTest {
processor.setBeanFactory(beanFactory); processor.setBeanFactory(beanFactory);
Object bean = processor.postProcessBeforeInitialization(reactiveLoadBalancerClientFilter, ""); Object bean = processor.postProcessBeforeInitialization(reactiveLoadBalancerClientFilter, "");
assertThat(bean).isInstanceOf(PolarisReactiveLoadBalancerClientFilter.class);
Assert.assertTrue(bean instanceof PolarisReactiveLoadBalancerClientFilter);
} }
} }
@ -87,8 +86,8 @@ public class ReactiveLoadBalancerClientFilterBeanPostProcessorTest {
OtherBean otherBean = new OtherBean(); OtherBean otherBean = new OtherBean();
Object bean = processor.postProcessBeforeInitialization(otherBean, ""); Object bean = processor.postProcessBeforeInitialization(otherBean, "");
Assert.assertFalse(bean instanceof PolarisReactiveLoadBalancerClientFilter); assertThat(bean).isNotInstanceOf(PolarisReactiveLoadBalancerClientFilter.class);
Assert.assertTrue(bean instanceof OtherBean); assertThat(bean).isInstanceOf(OtherBean.class);
} }
static class OtherBean { static class OtherBean {

@ -21,7 +21,7 @@ package com.tencent.cloud.polaris.router.config;
import com.tencent.cloud.common.metadata.config.MetadataAutoConfiguration; import com.tencent.cloud.common.metadata.config.MetadataAutoConfiguration;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.router.feign.RouterLabelFeignInterceptor; import com.tencent.cloud.polaris.router.feign.RouterLabelFeignInterceptor;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.boot.test.context.runner.WebApplicationContextRunner;

@ -18,11 +18,10 @@
package com.tencent.cloud.polaris.router.config; package com.tencent.cloud.polaris.router.config;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.router.PolarisRouterServiceInstanceListSupplier; import com.tencent.cloud.polaris.router.PolarisRouterServiceInstanceListSupplier;
import com.tencent.polaris.router.api.core.RouterAPI; import com.tencent.polaris.router.api.core.RouterAPI;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ApplicationContextRunner;

@ -20,7 +20,7 @@ package com.tencent.cloud.polaris.router.config;
import com.tencent.cloud.common.metadata.config.MetadataAutoConfiguration; import com.tencent.cloud.common.metadata.config.MetadataAutoConfiguration;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.boot.test.context.runner.WebApplicationContextRunner;

@ -18,8 +18,8 @@
package com.tencent.cloud.polaris.router.config.properties; package com.tencent.cloud.polaris.router.config.properties;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -30,8 +30,8 @@ public class PolarisMetadataRouterPropertiesTest {
PolarisMetadataRouterProperties properties; PolarisMetadataRouterProperties properties;
@Before @BeforeEach
public void setUp() { void setUp() {
properties = new PolarisMetadataRouterProperties(); properties = new PolarisMetadataRouterProperties();
} }
@ -48,7 +48,6 @@ public class PolarisMetadataRouterPropertiesTest {
@Test @Test
public void testToString() { public void testToString() {
assertThat(properties.toString()) assertThat(properties.toString()).isEqualTo("PolarisMetadataRouterProperties{enabled=true}");
.isEqualTo("PolarisMetadataRouterProperties{enabled=true}");
} }
} }

@ -18,13 +18,11 @@
package com.tencent.cloud.polaris.router.config.properties; package com.tencent.cloud.polaris.router.config.properties;
import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
/** /**
* test for {@link PolarisNearByRouterProperties}. * test for {@link PolarisNearByRouterProperties}.
*/ */
@ -32,8 +30,8 @@ public class PolarisNearByRouterPropertiesTest {
PolarisNearByRouterProperties properties; PolarisNearByRouterProperties properties;
@Before @BeforeEach
public void setUp() { void setUp() {
properties = new PolarisNearByRouterProperties(); properties = new PolarisNearByRouterProperties();
} }

@ -18,8 +18,8 @@
package com.tencent.cloud.polaris.router.config.properties; package com.tencent.cloud.polaris.router.config.properties;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -30,8 +30,8 @@ public class PolarisRuleBasedRouterPropertiesTest {
PolarisRuleBasedRouterProperties properties; PolarisRuleBasedRouterProperties properties;
@Before @BeforeEach
public void setUp() { void setUp() {
properties = new PolarisRuleBasedRouterProperties(); properties = new PolarisRuleBasedRouterProperties();
} }

@ -19,7 +19,7 @@ package com.tencent.cloud.polaris.router.endpoint;
import com.tencent.cloud.polaris.context.ServiceRuleManager; import com.tencent.cloud.polaris.context.ServiceRuleManager;
import com.tencent.polaris.client.api.SDKContext; import com.tencent.polaris.client.api.SDKContext;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
@ -34,13 +34,12 @@ import static org.assertj.core.api.Assertions.assertThat;
*/ */
public class PolarisRouterEndpointAutoConfigurationTests { public class PolarisRouterEndpointAutoConfigurationTests {
private ServiceRuleManager serviceRuleManager;
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of( .withConfiguration(AutoConfigurations.of(
TestServiceRuleManagerConfiguration.class, TestServiceRuleManagerConfiguration.class,
PolarisRouterEndpointAutoConfiguration.class)) PolarisRouterEndpointAutoConfiguration.class))
.withPropertyValues("endpoints.polaris-router.enabled=true"); .withPropertyValues("endpoints.polaris-router.enabled=true");
private ServiceRuleManager serviceRuleManager;
@Test @Test
public void polarisRouterEndpoint() { public void polarisRouterEndpoint() {

@ -22,22 +22,22 @@ import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import com.google.common.collect.Lists;
import com.tencent.cloud.common.util.ApplicationContextAwareUtils; import com.tencent.cloud.common.util.ApplicationContextAwareUtils;
import com.tencent.cloud.polaris.context.ServiceRuleManager; import com.tencent.cloud.polaris.context.ServiceRuleManager;
import com.tencent.polaris.client.pb.ModelProto; import com.tencent.polaris.specification.api.v1.model.ModelProto;
import com.tencent.polaris.client.pb.RoutingProto; import com.tencent.polaris.specification.api.v1.traffic.manage.RoutingProto;
import org.junit.AfterClass; import org.assertj.core.util.Lists;
import org.junit.Assert; import org.junit.jupiter.api.AfterAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockedStatic; import org.mockito.MockedStatic;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -46,7 +46,7 @@ import static org.mockito.Mockito.when;
* *
* @author lepdou 2022-07-25 * @author lepdou 2022-07-25
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class PolarisRouterEndpointTest { public class PolarisRouterEndpointTest {
private static final String testDestService = "dstService"; private static final String testDestService = "dstService";
@ -57,15 +57,15 @@ public class PolarisRouterEndpointTest {
@InjectMocks @InjectMocks
private PolarisRouterEndpoint polarisRouterEndpoint; private PolarisRouterEndpoint polarisRouterEndpoint;
@BeforeClass @BeforeAll
public static void beforeClass() { static void beforeAll() {
mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class); mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class);
mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString())) mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString()))
.thenReturn(testDestService); .thenReturn(testDestService);
} }
@AfterClass @AfterAll
public static void afterClass() { static void afterAll() {
mockedApplicationContextAwareUtils.close(); mockedApplicationContextAwareUtils.close();
} }
@ -92,27 +92,27 @@ public class PolarisRouterEndpointTest {
List<RoutingProto.Route> routes = new LinkedList<>(); List<RoutingProto.Route> routes = new LinkedList<>();
RoutingProto.Route route = RoutingProto.Route.newBuilder() RoutingProto.Route route = RoutingProto.Route.newBuilder()
.addAllSources(Lists.newArrayList(source1, source2, source3)) .addAllSources(Lists.list(source1, source2, source3))
.build(); .build();
routes.add(route); routes.add(route);
when(serviceRuleManager.getServiceRouterRule(testDestService, testDestService, testDestService)).thenReturn(routes); when(serviceRuleManager.getServiceRouterRule(anyString(), anyString(), anyString())).thenReturn(routes);
Map<String, Object> actuator = polarisRouterEndpoint.router(testDestService); Map<String, Object> actuator = polarisRouterEndpoint.router(testDestService);
Assert.assertNotNull(actuator.get("routerRules")); assertThat(actuator.get("routerRules")).isNotNull();
Assert.assertEquals(1, ((List<?>) actuator.get("routerRules")).size()); assertThat(((List<?>) actuator.get("routerRules")).size()).isEqualTo(1);
} }
@Test @Test
public void testHasNotRouterRule() { public void testHasNotRouterRule() {
List<RoutingProto.Route> routes = new LinkedList<>(); List<RoutingProto.Route> routes = new LinkedList<>();
when(serviceRuleManager.getServiceRouterRule(testDestService, testDestService, testDestService)).thenReturn(routes); when(serviceRuleManager.getServiceRouterRule(anyString(), anyString(), anyString())).thenReturn(routes);
Map<String, Object> actuator = polarisRouterEndpoint.router(testDestService); Map<String, Object> actuator = polarisRouterEndpoint.router(testDestService);
Assert.assertNotNull(actuator.get("routerRules")); assertThat(actuator.get("routerRules")).isNotNull();
Assert.assertEquals(0, ((List) actuator.get("routerRules")).size()); assertThat(((List<?>) actuator.get("routerRules")).size()).isEqualTo(0);
} }
} }

@ -20,14 +20,14 @@ package com.tencent.cloud.polaris.router.feign;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.stream.Stream;
import com.google.common.collect.Sets;
import feign.Request; import feign.Request;
import feign.RequestTemplate; import feign.RequestTemplate;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.springframework.util.StringUtils; import static java.util.stream.Collectors.toSet;
import static org.assertj.core.api.Assertions.assertThat;
/** /**
* Test for {@link FeignExpressionLabelUtils}. * Test for {@link FeignExpressionLabelUtils}.
@ -52,14 +52,14 @@ public class FeignExpressionLabelUtilsTest {
String labelKey4 = "${http.header.}"; String labelKey4 = "${http.header.}";
String labelKey5 = "${http.header.teacher.age}"; String labelKey5 = "${http.header.teacher.age}";
Map<String, String> result = FeignExpressionLabelUtils.resolve(requestTemplate, Map<String, String> result = FeignExpressionLabelUtils.resolve(requestTemplate,
Sets.newHashSet(labelKey1, labelKey2, labelKey3, labelKey4, labelKey5)); Stream.of(labelKey1, labelKey2, labelKey3, labelKey4, labelKey5).collect(toSet()));
Assert.assertFalse(result.isEmpty()); assertThat(result).isNotEmpty();
Assert.assertEquals(headerValue, result.get(labelKey1)); assertThat(result.get(labelKey1)).isEqualTo(headerValue);
Assert.assertEquals(headerValue2, result.get(labelKey5)); assertThat(result.get(labelKey5)).isEqualTo(headerValue2);
Assert.assertTrue(StringUtils.isEmpty(result.get(labelKey2))); assertThat(result.get(labelKey2)).isBlank();
Assert.assertTrue(StringUtils.isEmpty(result.get(labelKey3))); assertThat(result.get(labelKey3)).isBlank();
Assert.assertTrue(StringUtils.isEmpty(result.get(labelKey4))); assertThat(result.get(labelKey4)).isBlank();
} }
@Test @Test
@ -79,14 +79,14 @@ public class FeignExpressionLabelUtilsTest {
String labelKey4 = "${http.query.}"; String labelKey4 = "${http.query.}";
String labelKey5 = "${http.query.teacher.age}"; String labelKey5 = "${http.query.teacher.age}";
Map<String, String> result = FeignExpressionLabelUtils.resolve(requestTemplate, Map<String, String> result = FeignExpressionLabelUtils.resolve(requestTemplate,
Sets.newHashSet(labelKey1, labelKey2, labelKey3, labelKey4, labelKey5)); Stream.of(labelKey1, labelKey2, labelKey3, labelKey4, labelKey5).collect(toSet()));
Assert.assertFalse(result.isEmpty()); assertThat(result).isNotEmpty();
Assert.assertEquals(headerValue, result.get(labelKey1)); assertThat(result.get(labelKey1)).isEqualTo(headerValue);
Assert.assertEquals(headerValue2, result.get(labelKey5)); assertThat(result.get(labelKey5)).isEqualTo(headerValue2);
Assert.assertTrue(StringUtils.isEmpty(result.get(labelKey2))); assertThat(result.get(labelKey2)).isBlank();
Assert.assertTrue(StringUtils.isEmpty(result.get(labelKey3))); assertThat(result.get(labelKey3)).isBlank();
Assert.assertTrue(StringUtils.isEmpty(result.get(labelKey4))); assertThat(result.get(labelKey4)).isBlank();
} }
@Test @Test
@ -95,11 +95,11 @@ public class FeignExpressionLabelUtilsTest {
requestTemplate.method(Request.HttpMethod.GET); requestTemplate.method(Request.HttpMethod.GET);
String labelKey1 = "${http.method}"; String labelKey1 = "${http.method}";
Map<String, String> result = FeignExpressionLabelUtils.resolve(requestTemplate, Map<String, String> result = FeignExpressionLabelUtils.resolve(requestTemplate, Stream.of(labelKey1)
Sets.newHashSet(labelKey1)); .collect(toSet()));
Assert.assertFalse(result.isEmpty()); assertThat(result).isNotEmpty();
Assert.assertEquals("GET", result.get(labelKey1)); assertThat(result.get(labelKey1)).isEqualTo("GET");
} }
@Test @Test
@ -113,11 +113,11 @@ public class FeignExpressionLabelUtilsTest {
requestTemplate = requestTemplate.resolve(new HashMap<>()); requestTemplate = requestTemplate.resolve(new HashMap<>());
String labelKey1 = "${http.uri}"; String labelKey1 = "${http.uri}";
Map<String, String> result = FeignExpressionLabelUtils.resolve(requestTemplate, Map<String, String> result = FeignExpressionLabelUtils.resolve(requestTemplate, Stream.of(labelKey1)
Sets.newHashSet(labelKey1)); .collect(toSet()));
Assert.assertFalse(result.isEmpty()); assertThat(result).isNotEmpty();
Assert.assertEquals(uri, result.get(labelKey1)); assertThat(result.get(labelKey1)).isEqualTo(uri);
} }
@Test @Test
@ -131,10 +131,10 @@ public class FeignExpressionLabelUtilsTest {
requestTemplate = requestTemplate.resolve(new HashMap<>()); requestTemplate = requestTemplate.resolve(new HashMap<>());
String labelKey1 = "${http.uri}"; String labelKey1 = "${http.uri}";
Map<String, String> result = FeignExpressionLabelUtils.resolve(requestTemplate, Map<String, String> result = FeignExpressionLabelUtils.resolve(requestTemplate, Stream.of(labelKey1)
Sets.newHashSet(labelKey1)); .collect(toSet()));
Assert.assertFalse(result.isEmpty()); assertThat(result).isNotEmpty();
Assert.assertEquals(uri, result.get(labelKey1)); assertThat(result.get(labelKey1)).isEqualTo(uri);
} }
} }

@ -38,13 +38,12 @@ import com.tencent.cloud.polaris.router.RouterRuleLabelResolver;
import com.tencent.cloud.polaris.router.spi.FeignRouterLabelResolver; import com.tencent.cloud.polaris.router.spi.FeignRouterLabelResolver;
import feign.RequestTemplate; import feign.RequestTemplate;
import feign.Target; import feign.Target;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockedStatic; import org.mockito.MockedStatic;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
@ -54,7 +53,7 @@ import static org.mockito.Mockito.when;
* test for {@link RouterLabelFeignInterceptor}. * test for {@link RouterLabelFeignInterceptor}.
* @author lepdou 2022-05-26 * @author lepdou 2022-05-26
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class RouterLabelFeignInterceptorTest { public class RouterLabelFeignInterceptorTest {
@Mock @Mock
@ -123,16 +122,16 @@ public class RouterLabelFeignInterceptorTest {
Collection<String> routerLabels = requestTemplate.headers().get(RouterConstant.ROUTER_LABEL_HEADER); Collection<String> routerLabels = requestTemplate.headers().get(RouterConstant.ROUTER_LABEL_HEADER);
Assert.assertNotNull(routerLabels); assertThat(routerLabels).isNotNull();
for (String value : routerLabels) { for (String value : routerLabels) {
Map<String, String> labels = JacksonUtils.deserialize2Map(URLDecoder.decode(value, "UTF-8")); Map<String, String> labels = JacksonUtils.deserialize2Map(URLDecoder.decode(value, "UTF-8"));
Assert.assertEquals("v1", labels.get("k1")); assertThat(labels.get("k1")).isEqualTo("v1");
Assert.assertEquals("v22", labels.get("k2")); assertThat(labels.get("k2")).isEqualTo("v22");
Assert.assertEquals("v3", labels.get("k3")); assertThat(labels.get("k3")).isEqualTo("v3");
Assert.assertEquals("v4", labels.get("k4")); assertThat(labels.get("k4")).isEqualTo("v4");
Assert.assertEquals(headerUidValue, labels.get("${http.header.uid}")); assertThat(labels.get("${http.header.uid}")).isEqualTo(headerUidValue);
Assert.assertEquals("", labels.get("${http.header.name}")); assertThat(labels.get("${http.header.name}")).isEqualTo("");
} }
} }
} }

@ -18,7 +18,7 @@
package com.tencent.cloud.polaris.router.resttemplate; package com.tencent.cloud.polaris.router.resttemplate;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.cloud.client.DefaultServiceInstance; import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.ServiceInstance;

@ -18,7 +18,6 @@
package com.tencent.cloud.polaris.router.resttemplate; package com.tencent.cloud.polaris.router.resttemplate;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URI; import java.net.URI;
import java.net.URLDecoder; import java.net.URLDecoder;
@ -40,14 +39,12 @@ import com.tencent.cloud.common.util.expresstion.SpringWebExpressionLabelUtils;
import com.tencent.cloud.polaris.context.config.PolarisContextProperties; import com.tencent.cloud.polaris.context.config.PolarisContextProperties;
import com.tencent.cloud.polaris.router.RouterRuleLabelResolver; import com.tencent.cloud.polaris.router.RouterRuleLabelResolver;
import com.tencent.cloud.polaris.router.spi.SpringWebRouterLabelResolver; import com.tencent.cloud.polaris.router.spi.SpringWebRouterLabelResolver;
import org.junit.AfterClass; import org.junit.jupiter.api.Test;
import org.junit.BeforeClass; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockedStatic; import org.mockito.MockedStatic;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.core.Ordered; import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
@ -63,6 +60,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -71,12 +69,12 @@ import static org.mockito.Mockito.when;
* *
* @author liuye, Haotian Zhang * @author liuye, Haotian Zhang
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class RouterLabelRestTemplateInterceptorTest { public class RouterLabelRestTemplateInterceptorTest {
private static MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils; private static final String testNamespaceAndService = "testNamespaceAndService";
private static MockedStatic<MetadataContextHolder> mockedMetadataContextHolder;
@Mock @Mock
private SpringWebRouterLabelResolver routerLabelResolver; private SpringWebRouterLabelResolver routerLabelResolver;
@Mock @Mock
private StaticMetadataManager staticMetadataManager; private StaticMetadataManager staticMetadataManager;
@ -88,24 +86,16 @@ public class RouterLabelRestTemplateInterceptorTest {
@Mock @Mock
private ClientHttpRequestExecution clientHttpRequestExecution; private ClientHttpRequestExecution clientHttpRequestExecution;
@BeforeClass
public static void beforeClass() {
mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class);
mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString()))
.thenReturn("callerService");
mockedMetadataContextHolder = Mockito.mockStatic(MetadataContextHolder.class);
}
@AfterClass
public static void afterClass() {
mockedApplicationContextAwareUtils.close();
mockedMetadataContextHolder.close();
}
@Test @Test
public void testRouterContext() throws Exception { public void testRouterContext() throws Exception {
String callerService = "callerService"; try (
MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils = mockStatic(ApplicationContextAwareUtils.class);
MockedStatic<MetadataContextHolder> mockedMetadataContextHolder = mockStatic(MetadataContextHolder.class)
) {
mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString()))
.thenReturn(testNamespaceAndService);
String calleeService = "calleeService"; String calleeService = "calleeService";
HttpRequest request = new MockedHttpRequest("http://" + calleeService + "/user/get"); HttpRequest request = new MockedHttpRequest("http://" + calleeService + "/user/get");
@ -120,7 +110,7 @@ public class RouterLabelRestTemplateInterceptorTest {
Set<String> expressionKeys = new HashSet<>(); Set<String> expressionKeys = new HashSet<>();
expressionKeys.add("${http.method}"); expressionKeys.add("${http.method}");
expressionKeys.add("${http.uri}"); expressionKeys.add("${http.uri}");
when(routerRuleLabelResolver.getExpressionLabelKeys(callerService, callerService, calleeService)).thenReturn(expressionKeys); when(routerRuleLabelResolver.getExpressionLabelKeys(testNamespaceAndService, testNamespaceAndService, calleeService)).thenReturn(expressionKeys);
routerLabels.putAll(SpringWebExpressionLabelUtils.resolve(request, expressionKeys)); routerLabels.putAll(SpringWebExpressionLabelUtils.resolve(request, expressionKeys));
// mock custom resolved from request // mock custom resolved from request
@ -152,7 +142,7 @@ public class RouterLabelRestTemplateInterceptorTest {
routerLabelRestTemplateInterceptor.intercept(request, null, clientHttpRequestExecution); routerLabelRestTemplateInterceptor.intercept(request, null, clientHttpRequestExecution);
verify(staticMetadataManager).getMergedStaticMetadata(); verify(staticMetadataManager).getMergedStaticMetadata();
verify(routerRuleLabelResolver).getExpressionLabelKeys(callerService, callerService, calleeService); verify(routerRuleLabelResolver).getExpressionLabelKeys(testNamespaceAndService, testNamespaceAndService, calleeService);
verify(routerLabelResolver).resolve(request, null, expressionKeys); verify(routerLabelResolver).resolve(request, null, expressionKeys);
@ -172,7 +162,7 @@ public class RouterLabelRestTemplateInterceptorTest {
} }
assertThat(mockedResponse.getHeaders().get(RouterConstant.ROUTER_LABEL_HEADER).get(0)) assertThat(mockedResponse.getHeaders().get(RouterConstant.ROUTER_LABEL_HEADER).get(0))
.isEqualTo(encodedLabelsContent); .isEqualTo(encodedLabelsContent);
}
} }
static class MockedHttpRequest implements HttpRequest { static class MockedHttpRequest implements HttpRequest {

@ -21,13 +21,12 @@ package com.tencent.cloud.polaris.router.scg;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URI; import java.net.URI;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.tencent.cloud.common.constant.RouterConstant; import com.tencent.cloud.common.constant.RouterConstant;
import com.tencent.cloud.common.metadata.MetadataContext; import com.tencent.cloud.common.metadata.MetadataContext;
import com.tencent.cloud.common.metadata.MetadataContextHolder; import com.tencent.cloud.common.metadata.MetadataContextHolder;
@ -37,15 +36,13 @@ import com.tencent.cloud.common.util.JacksonUtils;
import com.tencent.cloud.polaris.context.config.PolarisContextProperties; import com.tencent.cloud.polaris.context.config.PolarisContextProperties;
import com.tencent.cloud.polaris.router.RouterRuleLabelResolver; import com.tencent.cloud.polaris.router.RouterRuleLabelResolver;
import com.tencent.cloud.polaris.router.spi.SpringWebRouterLabelResolver; import com.tencent.cloud.polaris.router.spi.SpringWebRouterLabelResolver;
import org.junit.AfterClass; import org.assertj.core.util.Lists;
import org.junit.Assert; import org.assertj.core.util.Sets;
import org.junit.BeforeClass; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockedStatic; import org.mockito.MockedStatic;
import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.MockitoJUnitRunner;
import reactor.core.publisher.Mono; import reactor.core.publisher.Mono;
import org.springframework.cloud.client.loadbalancer.LoadBalancerProperties; import org.springframework.cloud.client.loadbalancer.LoadBalancerProperties;
@ -59,27 +56,27 @@ import org.springframework.cloud.loadbalancer.support.SimpleObjectProvider;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ServerWebExchange;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8; import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.when; 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_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR; import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR;
/** /**
* Test for ${@link PolarisReactiveLoadBalancerClientFilter}. * Test for ${@link PolarisReactiveLoadBalancerClientFilter}.
*
* @author lepdou 2022-07-04 * @author lepdou 2022-07-04
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class PolarisReactiveLoadBalancerClientFilterTest { public class PolarisReactiveLoadBalancerClientFilterTest {
private static final String callerService = "callerService"; private static final String testNamespaceAndService = "testNamespaceAndService";
private static final String calleeService = "calleeService"; private static final String calleeService = "calleeService";
private static MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils;
private static MockedStatic<MetadataContextHolder> mockedMetadataContextHolder;
@Mock @Mock
private StaticMetadataManager staticMetadataManager; private StaticMetadataManager staticMetadataManager;
@ -94,11 +91,14 @@ public class PolarisReactiveLoadBalancerClientFilterTest {
@Mock @Mock
private PolarisContextProperties polarisContextProperties; private PolarisContextProperties polarisContextProperties;
@BeforeClass @Test
public static void beforeClass() { public void testGenRouterHttpHeaders() throws UnsupportedEncodingException {
mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class); try (
MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils = mockStatic(ApplicationContextAwareUtils.class);
MockedStatic<MetadataContextHolder> mockedMetadataContextHolder = mockStatic(MetadataContextHolder.class)
) {
mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString())) mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString()))
.thenReturn(callerService); .thenReturn(testNamespaceAndService);
MetadataContext metadataContext = mock(MetadataContext.class); MetadataContext metadataContext = mock(MetadataContext.class);
@ -107,28 +107,17 @@ public class PolarisReactiveLoadBalancerClientFilterTest {
transitiveLabels.put("t1", "v1"); transitiveLabels.put("t1", "v1");
transitiveLabels.put("t2", "v2"); transitiveLabels.put("t2", "v2");
when(metadataContext.getTransitiveMetadata()).thenReturn(transitiveLabels); when(metadataContext.getTransitiveMetadata()).thenReturn(transitiveLabels);
mockedMetadataContextHolder = Mockito.mockStatic(MetadataContextHolder.class);
mockedMetadataContextHolder.when(MetadataContextHolder::get).thenReturn(metadataContext); mockedMetadataContextHolder.when(MetadataContextHolder::get).thenReturn(metadataContext);
}
@AfterClass
public static void afterClass() {
mockedApplicationContextAwareUtils.close();
mockedMetadataContextHolder.close();
}
@Test
public void testGenRouterHttpHeaders() throws UnsupportedEncodingException {
PolarisReactiveLoadBalancerClientFilter filter = new PolarisReactiveLoadBalancerClientFilter(loadBalancerClientFactory, PolarisReactiveLoadBalancerClientFilter filter = new PolarisReactiveLoadBalancerClientFilter(loadBalancerClientFactory,
gatewayLoadBalancerProperties, staticMetadataManager, routerRuleLabelResolver, gatewayLoadBalancerProperties, staticMetadataManager, routerRuleLabelResolver,
Lists.newArrayList(routerLabelResolver), polarisContextProperties); Collections.singletonList(routerLabelResolver), polarisContextProperties);
Map<String, String> localMetadata = new HashMap<>(); Map<String, String> localMetadata = new HashMap<>();
localMetadata.put("env", "blue"); localMetadata.put("env", "blue");
when(staticMetadataManager.getMergedStaticMetadata()).thenReturn(localMetadata); when(staticMetadataManager.getMergedStaticMetadata()).thenReturn(localMetadata);
Set<String> expressionLabelKeys = Sets.newHashSet("${http.header.k1}", "${http.query.userid}"); Set<String> expressionLabelKeys = Sets.set("${http.header.k1}", "${http.query.userid}");
when(routerRuleLabelResolver.getExpressionLabelKeys(anyString(), anyString(), anyString())).thenReturn(expressionLabelKeys); when(routerRuleLabelResolver.getExpressionLabelKeys(anyString(), anyString(), anyString())).thenReturn(expressionLabelKeys);
MockServerHttpRequest request = MockServerHttpRequest.get("/" + calleeService + "/users") MockServerHttpRequest request = MockServerHttpRequest.get("/" + calleeService + "/users")
@ -143,23 +132,41 @@ public class PolarisReactiveLoadBalancerClientFilterTest {
HttpHeaders headers = filter.genRouterHttpHeaders(webExchange, calleeService); HttpHeaders headers = filter.genRouterHttpHeaders(webExchange, calleeService);
Assert.assertNotNull(headers); assertThat(headers).isNotNull();
List<String> routerHeaders = headers.get(RouterConstant.ROUTER_LABEL_HEADER); List<String> routerHeaders = headers.get(RouterConstant.ROUTER_LABEL_HEADER);
Assert.assertFalse(CollectionUtils.isEmpty(routerHeaders)); assertThat(routerHeaders).isNotNull();
Map<String, String> routerLabels = JacksonUtils.deserialize2Map(URLDecoder.decode(routerHeaders.get(0), UTF_8)); Map<String, String> routerLabels = JacksonUtils.deserialize2Map(URLDecoder.decode(routerHeaders.get(0), UTF_8));
Assert.assertEquals("v1", routerLabels.get("${http.header.k1}")); assertThat(routerLabels.get("${http.header.k1}")).isEqualTo("v1");
Assert.assertEquals("zhangsan", routerLabels.get("${http.query.userid}")); assertThat(routerLabels.get("${http.query.userid}")).isEqualTo("zhangsan");
Assert.assertEquals("blue", routerLabels.get("env")); assertThat(routerLabels.get("env")).isEqualTo("blue");
Assert.assertEquals("v1", routerLabels.get("t1")); assertThat(routerLabels.get("t1")).isEqualTo("v1");
Assert.assertEquals("v2", routerLabels.get("t2")); assertThat(routerLabels.get("t2")).isEqualTo("v2");
}
} }
@Test @Test
public void testFilter01() throws Exception { public void testFilter01() throws Exception {
try (
MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils = mockStatic(ApplicationContextAwareUtils.class);
MockedStatic<MetadataContextHolder> mockedMetadataContextHolder = mockStatic(MetadataContextHolder.class)
) {
mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString()))
.thenReturn(testNamespaceAndService);
MetadataContext metadataContext = mock(MetadataContext.class);
// mock transitive metadata
Map<String, String> transitiveLabels = new HashMap<>();
transitiveLabels.put("t1", "v1");
transitiveLabels.put("t2", "v2");
when(metadataContext.getTransitiveMetadata()).thenReturn(transitiveLabels);
mockedMetadataContextHolder.when(MetadataContextHolder::get).thenReturn(metadataContext);
PolarisReactiveLoadBalancerClientFilter filter = new PolarisReactiveLoadBalancerClientFilter(loadBalancerClientFactory, PolarisReactiveLoadBalancerClientFilter filter = new PolarisReactiveLoadBalancerClientFilter(loadBalancerClientFactory,
gatewayLoadBalancerProperties, staticMetadataManager, routerRuleLabelResolver, gatewayLoadBalancerProperties, staticMetadataManager, routerRuleLabelResolver,
Lists.newArrayList(routerLabelResolver), polarisContextProperties); Lists.list(routerLabelResolver), polarisContextProperties);
MockServerHttpRequest request = MockServerHttpRequest.get("/" + calleeService + "/users").build(); MockServerHttpRequest request = MockServerHttpRequest.get("/" + calleeService + "/users").build();
MockServerWebExchange exchange = new MockServerWebExchange.Builder(request).build(); MockServerWebExchange exchange = new MockServerWebExchange.Builder(request).build();
@ -167,7 +174,7 @@ public class PolarisReactiveLoadBalancerClientFilterTest {
// mock no lb // mock no lb
EmptyGatewayFilterChain chain = new EmptyGatewayFilterChain(); EmptyGatewayFilterChain chain = new EmptyGatewayFilterChain();
Mono<Void> ret = filter.filter(exchange, chain); Mono<Void> ret = filter.filter(exchange, chain);
Assert.assertEquals(ret, Mono.empty()); assertThat(ret).isEqualTo(Mono.empty());
// mock with lb // mock with lb
exchange = new MockServerWebExchange.Builder(request).build(); exchange = new MockServerWebExchange.Builder(request).build();
@ -182,7 +189,7 @@ public class PolarisReactiveLoadBalancerClientFilterTest {
when(loadBalancerProperties.getHint()).thenReturn(new HashMap<>()); when(loadBalancerProperties.getHint()).thenReturn(new HashMap<>());
when(loadBalancerClientFactory.getProperties(calleeService)).thenReturn(loadBalancerProperties); when(loadBalancerClientFactory.getProperties(calleeService)).thenReturn(loadBalancerProperties);
filter.filter(exchange, chain); filter.filter(exchange, chain);
}
} }
static class EmptyGatewayFilterChain implements GatewayFilterChain { static class EmptyGatewayFilterChain implements GatewayFilterChain {
@ -192,5 +199,4 @@ public class PolarisReactiveLoadBalancerClientFilterTest {
return Mono.empty(); return Mono.empty();
} }
} }
} }

@ -102,7 +102,7 @@
<dependency> <dependency>
<groupId>uk.org.webcompere</groupId> <groupId>uk.org.webcompere</groupId>
<artifactId>system-stubs-junit4</artifactId> <artifactId>system-stubs-jupiter</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>

@ -21,19 +21,19 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.assertj.core.api.Assertions; import org.assertj.core.api.Assertions;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit.jupiter.SpringExtension;
/** /**
* Test for {@link MetadataContextHolder}. * Test for {@link MetadataContextHolder}.
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@RunWith(SpringRunner.class) @ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = MetadataContextHolderTest.TestApplication.class, classes = MetadataContextHolderTest.TestApplication.class,
properties = {"spring.config.location = classpath:application-test.yml"}) properties = {"spring.config.location = classpath:application-test.yml"})

@ -26,35 +26,32 @@ import java.util.Set;
import com.tencent.cloud.common.metadata.config.MetadataLocalProperties; import com.tencent.cloud.common.metadata.config.MetadataLocalProperties;
import com.tencent.cloud.common.spi.InstanceMetadataProvider; import com.tencent.cloud.common.spi.InstanceMetadataProvider;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Rule; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import uk.org.webcompere.systemstubs.rules.EnvironmentVariablesRule; import uk.org.webcompere.systemstubs.environment.EnvironmentVariables;
import uk.org.webcompere.systemstubs.jupiter.SystemStub;
import org.springframework.util.CollectionUtils; import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
/** /**
* test for {@link StaticMetadataManager}. * test for {@link StaticMetadataManager}.
* *
* @author lepdou 2022-06-27 * @author lepdou 2022-06-27
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith({MockitoExtension.class, SystemStubsExtension.class})
public class StaticMetadataManagerTest { public class StaticMetadataManagerTest {
@Mock
private MetadataLocalProperties metadataLocalProperties;
/** /**
* EnvironmentVariablesRule. * EnvironmentVariablesRule.
*/ */
@Rule @SystemStub
public EnvironmentVariablesRule rule = new EnvironmentVariablesRule(); public EnvironmentVariables environmentVariables = new EnvironmentVariables();
@Mock
private MetadataLocalProperties metadataLocalProperties;
@Test @Test
public void testParseConfigMetadata() { public void testParseConfigMetadata() {
@ -70,20 +67,20 @@ public class StaticMetadataManagerTest {
StaticMetadataManager metadataManager = new StaticMetadataManager(metadataLocalProperties, null); StaticMetadataManager metadataManager = new StaticMetadataManager(metadataLocalProperties, null);
Map<String, String> metadata = metadataManager.getAllConfigMetadata(); Map<String, String> metadata = metadataManager.getAllConfigMetadata();
Assert.assertEquals(4, metadata.size()); assertThat(metadata.size()).isEqualTo(4);
Assert.assertEquals("v1", metadata.get("k1")); assertThat(metadata.get("k1")).isEqualTo("v1");
Assert.assertEquals("v22", metadata.get("k2")); assertThat(metadata.get("k2")).isEqualTo("v22");
Map<String, String> transitiveMetadata = metadataManager.getConfigTransitiveMetadata(); Map<String, String> transitiveMetadata = metadataManager.getConfigTransitiveMetadata();
Assert.assertEquals(1, transitiveMetadata.size()); assertThat(transitiveMetadata.size()).isEqualTo(1);
Assert.assertEquals("v1", transitiveMetadata.get("k1")); assertThat(transitiveMetadata.get("k1")).isEqualTo("v1");
Assert.assertEquals("zone1", metadataManager.getZone()); assertThat(metadataManager.getZone()).isEqualTo("zone1");
Assert.assertEquals("region1", metadataManager.getRegion()); assertThat(metadataManager.getRegion()).isEqualTo("region1");
Map<String, String> locationInfo = metadataManager.getLocationMetadata(); Map<String, String> locationInfo = metadataManager.getLocationMetadata();
Assert.assertEquals("zone1", locationInfo.get("zone")); assertThat(locationInfo.get("zone")).isEqualTo("zone1");
Assert.assertEquals("region1", locationInfo.get("region")); assertThat(locationInfo.get("region")).isEqualTo("region1");
} }
@Test @Test
@ -99,21 +96,21 @@ public class StaticMetadataManagerTest {
new MockedMetadataProvider()); new MockedMetadataProvider());
Map<String, String> metadata = metadataManager.getAllCustomMetadata(); Map<String, String> metadata = metadataManager.getAllCustomMetadata();
Assert.assertEquals(3, metadata.size()); assertThat(metadata.size()).isEqualTo(3);
Assert.assertEquals("v1", metadata.get("k1")); assertThat(metadata.get("k1")).isEqualTo("v1");
Assert.assertEquals("v22", metadata.get("k2")); assertThat(metadata.get("k2")).isEqualTo("v22");
Assert.assertEquals("v33", metadata.get("k3")); assertThat(metadata.get("k3")).isEqualTo("v33");
Map<String, String> transitiveMetadata = metadataManager.getCustomSPITransitiveMetadata(); Map<String, String> transitiveMetadata = metadataManager.getCustomSPITransitiveMetadata();
Assert.assertEquals(1, transitiveMetadata.size()); assertThat(transitiveMetadata.size()).isEqualTo(1);
Assert.assertEquals("v22", metadata.get("k2")); assertThat(metadata.get("k2")).isEqualTo("v22");
Assert.assertEquals("zone2", metadataManager.getZone()); assertThat(metadataManager.getZone()).isEqualTo("zone2");
Assert.assertEquals("region1", metadataManager.getRegion()); assertThat(metadataManager.getRegion()).isEqualTo("region1");
Map<String, String> locationInfo = metadataManager.getLocationMetadata(); Map<String, String> locationInfo = metadataManager.getLocationMetadata();
Assert.assertEquals("zone2", locationInfo.get("zone")); assertThat(locationInfo.get("zone")).isEqualTo("zone2");
Assert.assertEquals("region1", locationInfo.get("region")); assertThat(locationInfo.get("region")).isEqualTo("region1");
} }
@Test @Test
@ -132,53 +129,52 @@ public class StaticMetadataManagerTest {
new MockedMetadataProvider()); new MockedMetadataProvider());
Map<String, String> metadata = metadataManager.getMergedStaticMetadata(); Map<String, String> metadata = metadataManager.getMergedStaticMetadata();
Assert.assertEquals(6, metadata.size()); assertThat(metadata.size()).isEqualTo(6);
Assert.assertEquals("v1", metadata.get("k1")); assertThat(metadata.get("k1")).isEqualTo("v1");
Assert.assertEquals("v22", metadata.get("k2")); assertThat(metadata.get("k2")).isEqualTo("v22");
Assert.assertEquals("v33", metadata.get("k3")); assertThat(metadata.get("k3")).isEqualTo("v33");
Map<String, String> transitiveMetadata = metadataManager.getMergedStaticTransitiveMetadata(); Map<String, String> transitiveMetadata = metadataManager.getMergedStaticTransitiveMetadata();
Assert.assertEquals(2, transitiveMetadata.size()); assertThat(transitiveMetadata.size()).isEqualTo(2);
Assert.assertEquals("v1", metadata.get("k1")); assertThat(metadata.get("k1")).isEqualTo("v1");
Assert.assertEquals("v22", metadata.get("k2")); assertThat(metadata.get("k2")).isEqualTo("v22");
Assert.assertTrue(CollectionUtils.isEmpty(metadataManager.getAllEnvMetadata())); assertThat(metadataManager.getAllEnvMetadata()).isEmpty();
Assert.assertTrue(CollectionUtils.isEmpty(metadataManager.getEnvTransitiveMetadata())); assertThat(metadataManager.getEnvTransitiveMetadata()).isEmpty();
Assert.assertEquals("zone2", metadataManager.getZone()); assertThat(metadataManager.getZone()).isEqualTo("zone2");
Assert.assertEquals("region1", metadataManager.getRegion()); assertThat(metadataManager.getRegion()).isEqualTo("region1");
Map<String, String> locationInfo = metadataManager.getLocationMetadata(); Map<String, String> locationInfo = metadataManager.getLocationMetadata();
Assert.assertEquals("zone2", locationInfo.get("zone")); assertThat(locationInfo.get("zone")).isEqualTo("zone2");
Assert.assertEquals("region1", locationInfo.get("region")); assertThat(locationInfo.get("region")).isEqualTo("region1");
Assert.assertEquals("campus1", locationInfo.get("campus")); assertThat(locationInfo.get("campus")).isEqualTo("campus1");
} }
@Test @Test
public void testEnvMetadata() { public void testEnvMetadata() {
// set env // set env
rule.set("SCT_METADATA_CONTENT_TRANSITIVE", "transitiveKey"); environmentVariables.set("SCT_METADATA_CONTENT_TRANSITIVE", "transitiveKey")
rule.set("SCT_METADATA_CONTENT_DISPOSABLE", "disposableKey"); .set("SCT_METADATA_CONTENT_DISPOSABLE", "disposableKey")
rule.set("SCT_METADATA_CONTENT_transitiveKey", "transitiveValue"); .set("SCT_METADATA_CONTENT_transitiveKey", "transitiveValue")
rule.set("SCT_METADATA_CONTENT_disposableKey", "disposableValue"); .set("SCT_METADATA_CONTENT_disposableKey", "disposableValue")
rule.set("SCT_TRAFFIC_CONTENT_RAW_TRANSHEADERS", "header1,header2,header3"); .set("SCT_TRAFFIC_CONTENT_RAW_TRANSHEADERS", "header1,header2,header3");
StaticMetadataManager metadataManager = new StaticMetadataManager(metadataLocalProperties, null); StaticMetadataManager metadataManager = new StaticMetadataManager(metadataLocalProperties, null);
Map<String, String> allEnvMetadata = metadataManager.getAllEnvMetadata(); Map<String, String> allEnvMetadata = metadataManager.getAllEnvMetadata();
Assert.assertTrue(allEnvMetadata.containsKey("transitiveKey")); assertThat(allEnvMetadata).containsKey("transitiveKey");
Assert.assertTrue(allEnvMetadata.containsKey("disposableKey")); assertThat(allEnvMetadata).containsKey("disposableKey");
Map<String, String> envDisposableMetadata = metadataManager.getEnvDisposableMetadata(); Map<String, String> envDisposableMetadata = metadataManager.getEnvDisposableMetadata();
Assert.assertTrue(envDisposableMetadata.containsKey("disposableKey")); assertThat(envDisposableMetadata).containsKey("disposableKey");
Assert.assertEquals(envDisposableMetadata.get("disposableKey"), "disposableValue"); assertThat(envDisposableMetadata.get("disposableKey")).isEqualTo("disposableValue");
Map<String, String> envTransitiveMetadata = metadataManager.getEnvTransitiveMetadata(); Map<String, String> envTransitiveMetadata = metadataManager.getEnvTransitiveMetadata();
Assert.assertTrue(envTransitiveMetadata.containsKey("transitiveKey")); assertThat(envTransitiveMetadata).containsKey("transitiveKey");
Assert.assertEquals(envTransitiveMetadata.get("transitiveKey"), "transitiveValue"); assertThat(envTransitiveMetadata.get("transitiveKey")).isEqualTo("transitiveValue");
String transHeaderFromEnv = metadataManager.getTransHeaderFromEnv(); String transHeaderFromEnv = metadataManager.getTransHeaderFromEnv();
Assert.assertEquals(transHeaderFromEnv, "header1,header2,header3"); assertThat(transHeaderFromEnv).isEqualTo("header1,header2,header3");
} }
static class MockedMetadataProvider implements InstanceMetadataProvider { static class MockedMetadataProvider implements InstanceMetadataProvider {

@ -19,7 +19,7 @@
package com.tencent.cloud.common.metadata.config; package com.tencent.cloud.common.metadata.config;
import org.assertj.core.api.Assertions; import org.assertj.core.api.Assertions;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ApplicationContextRunner;

@ -18,20 +18,20 @@
package com.tencent.cloud.common.metadata.config; package com.tencent.cloud.common.metadata.config;
import org.assertj.core.api.Assertions; import org.assertj.core.api.Assertions;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit.jupiter.SpringExtension;
/** /**
* Test for {@link MetadataLocalProperties}. * Test for {@link MetadataLocalProperties}.
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@RunWith(SpringRunner.class) @ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = MetadataLocalPropertiesTest.TestApplication.class, classes = MetadataLocalPropertiesTest.TestApplication.class,
properties = {"spring.config.location = classpath:application-test.yml"}) properties = {"spring.config.location = classpath:application-test.yml"})

@ -16,17 +16,16 @@
* *
*/ */
package com.tencent.cloud.common.metadata.endpoint; package com.tencent.cloud.common.metadata.endpoint;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import com.tencent.cloud.common.metadata.StaticMetadataManager; import com.tencent.cloud.common.metadata.StaticMetadataManager;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -36,7 +35,7 @@ import static org.mockito.Mockito.when;
* *
* @author shuiqingliu * @author shuiqingliu
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class PolarisMetadataEndpointTests { public class PolarisMetadataEndpointTests {
@Mock @Mock

@ -21,77 +21,78 @@ package com.tencent.cloud.common.rule;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith; import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
/** /**
* Test for {@link Operation}. * Test for {@link Operation}.
* @author lepdou 2022-07-12 * @author lepdou 2022-07-12
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class OperationTest { public class OperationTest {
@Test @Test
public void testEqual() { public void testEqual() {
Assert.assertTrue(Operation.match(Collections.singletonList("v1"), "v1", Operation.EQUALS.getValue())); assertThat(Operation.match(Collections.singletonList("v1"), "v1", Operation.EQUALS.getValue())).isTrue();
Assert.assertFalse(Operation.match(Collections.singletonList("v1"), "v2", Operation.EQUALS.getValue())); assertThat(Operation.match(Collections.singletonList("v1"), "v2", Operation.EQUALS.getValue())).isFalse();
Assert.assertFalse(Operation.match(Collections.singletonList(""), "v2", Operation.EQUALS.getValue())); assertThat(Operation.match(Collections.singletonList(""), "v2", Operation.EQUALS.getValue())).isFalse();
Assert.assertFalse(Operation.match(Collections.singletonList("v1"), "", Operation.EQUALS.getValue())); assertThat(Operation.match(Collections.singletonList("v1"), "", Operation.EQUALS.getValue())).isFalse();
Assert.assertFalse(Operation.match(Collections.singletonList("v1"), null, Operation.EQUALS.getValue())); assertThat(Operation.match(Collections.singletonList("v1"), null, Operation.EQUALS.getValue())).isFalse();
Assert.assertFalse(Operation.match(Collections.emptyList(), "v1", Operation.EQUALS.getValue())); assertThat(Operation.match(Collections.emptyList(), "v1", Operation.EQUALS.getValue())).isFalse();
} }
@Test @Test
public void testNotEqual() { public void testNotEqual() {
Assert.assertFalse(Operation.match(Collections.singletonList("v1"), "v1", Operation.NOT_EQUALS.getValue())); assertThat(Operation.match(Collections.singletonList("v1"), "v1", Operation.NOT_EQUALS.getValue())).isFalse();
Assert.assertTrue(Operation.match(Collections.singletonList("v1"), "v2", Operation.NOT_EQUALS.getValue())); assertThat(Operation.match(Collections.singletonList("v1"), "v2", Operation.NOT_EQUALS.getValue())).isTrue();
Assert.assertTrue(Operation.match(Collections.singletonList(""), "v2", Operation.NOT_EQUALS.getValue())); assertThat(Operation.match(Collections.singletonList(""), "v2", Operation.NOT_EQUALS.getValue())).isTrue();
Assert.assertTrue(Operation.match(Collections.singletonList("v1"), "", Operation.NOT_EQUALS.getValue())); assertThat(Operation.match(Collections.singletonList("v1"), "", Operation.NOT_EQUALS.getValue())).isTrue();
Assert.assertTrue(Operation.match(Collections.singletonList("v1"), null, Operation.NOT_EQUALS.getValue())); assertThat(Operation.match(Collections.singletonList("v1"), null, Operation.NOT_EQUALS.getValue())).isTrue();
Assert.assertTrue(Operation.match(Collections.emptyList(), "v1", Operation.NOT_EQUALS.getValue())); assertThat(Operation.match(Collections.emptyList(), "v1", Operation.NOT_EQUALS.getValue())).isTrue();
} }
@Test @Test
public void testIn() { public void testIn() {
Assert.assertTrue(Operation.match(Arrays.asList("v1", "v2", "v3"), "v1", Operation.IN.getValue())); assertThat(Operation.match(Arrays.asList("v1", "v2", "v3"), "v1", Operation.IN.getValue())).isTrue();
Assert.assertTrue(Operation.match(Arrays.asList("v1", "v2", "v3"), "v2", Operation.IN.getValue())); assertThat(Operation.match(Arrays.asList("v1", "v2", "v3"), "v2", Operation.IN.getValue())).isTrue();
Assert.assertFalse(Operation.match(Arrays.asList("v1", "v2", "v3"), "v4", Operation.IN.getValue())); assertThat(Operation.match(Arrays.asList("v1", "v2", "v3"), "v4", Operation.IN.getValue())).isFalse();
Assert.assertFalse(Operation.match(Arrays.asList("v1", "v2", "v3"), "", Operation.IN.getValue())); assertThat(Operation.match(Arrays.asList("v1", "v2", "v3"), "", Operation.IN.getValue())).isFalse();
Assert.assertFalse(Operation.match(Arrays.asList("v1", "v2", "v3"), null, Operation.IN.getValue())); assertThat(Operation.match(Arrays.asList("v1", "v2", "v3"), null, Operation.IN.getValue())).isFalse();
Assert.assertFalse(Operation.match(Collections.emptyList(), null, Operation.IN.getValue())); assertThat(Operation.match(Collections.emptyList(), null, Operation.IN.getValue())).isFalse();
} }
@Test @Test
public void testNotIn() { public void testNotIn() {
Assert.assertFalse(Operation.match(Arrays.asList("v1", "v2", "v3"), "v1", Operation.NOT_IN.getValue())); assertThat(Operation.match(Arrays.asList("v1", "v2", "v3"), "v1", Operation.NOT_IN.getValue())).isFalse();
Assert.assertFalse(Operation.match(Arrays.asList("v1", "v2", "v3"), "v2", Operation.NOT_IN.getValue())); assertThat(Operation.match(Arrays.asList("v1", "v2", "v3"), "v2", Operation.NOT_IN.getValue())).isFalse();
Assert.assertTrue(Operation.match(Arrays.asList("v1", "v2", "v3"), "v4", Operation.NOT_IN.getValue())); assertThat(Operation.match(Arrays.asList("v1", "v2", "v3"), "v4", Operation.NOT_IN.getValue())).isTrue();
Assert.assertTrue(Operation.match(Arrays.asList("v1", "v2", "v3"), "", Operation.NOT_IN.getValue())); assertThat(Operation.match(Arrays.asList("v1", "v2", "v3"), "", Operation.NOT_IN.getValue())).isTrue();
Assert.assertTrue(Operation.match(Arrays.asList("v1", "v2", "v3"), null, Operation.NOT_IN.getValue())); assertThat(Operation.match(Arrays.asList("v1", "v2", "v3"), null, Operation.NOT_IN.getValue())).isTrue();
Assert.assertTrue(Operation.match(Collections.emptyList(), null, Operation.NOT_IN.getValue())); assertThat(Operation.match(Collections.emptyList(), null, Operation.NOT_IN.getValue())).isTrue();
} }
@Test @Test
public void testEmpty() { public void testEmpty() {
Assert.assertTrue(Operation.match(Collections.singletonList("v1"), null, Operation.BLANK.getValue())); assertThat(Operation.match(Collections.singletonList("v1"), null, Operation.BLANK.getValue())).isTrue();
Assert.assertTrue(Operation.match(Collections.singletonList("v1"), "", Operation.BLANK.getValue())); assertThat(Operation.match(Collections.singletonList("v1"), "", Operation.BLANK.getValue())).isTrue();
Assert.assertTrue(Operation.match(Collections.emptyList(), null, Operation.BLANK.getValue())); assertThat(Operation.match(Collections.emptyList(), null, Operation.BLANK.getValue())).isTrue();
} }
@Test @Test
public void testNotEmpty() { public void testNotEmpty() {
Assert.assertFalse(Operation.match(Collections.singletonList("v1"), null, Operation.NOT_BLANK.getValue())); assertThat(Operation.match(Collections.singletonList("v1"), null, Operation.NOT_BLANK.getValue())).isFalse();
Assert.assertFalse(Operation.match(Collections.singletonList("v1"), "", Operation.NOT_BLANK.getValue())); assertThat(Operation.match(Collections.singletonList("v1"), "", Operation.NOT_BLANK.getValue())).isFalse();
Assert.assertFalse(Operation.match(Collections.emptyList(), null, Operation.NOT_BLANK.getValue())); assertThat(Operation.match(Collections.emptyList(), null, Operation.NOT_BLANK.getValue())).isFalse();
Assert.assertTrue(Operation.match(Collections.emptyList(), "v1", Operation.NOT_BLANK.getValue())); assertThat(Operation.match(Collections.emptyList(), "v1", Operation.NOT_BLANK.getValue())).isTrue();
} }
@Test @Test
public void testRegex() { public void testRegex() {
Assert.assertTrue(Operation.match(Collections.singletonList("v[1~10]"), "v1", Operation.REGEX.getValue())); assertThat(Operation.match(Collections.singletonList("v[1~10]"), "v1", Operation.REGEX.getValue())).isTrue();
Assert.assertFalse(Operation.match(Collections.singletonList("v[1~10]"), "v12", Operation.REGEX.getValue())); assertThat(Operation.match(Collections.singletonList("v[1~10]"), "v12", Operation.REGEX.getValue())).isFalse();
Assert.assertFalse(Operation.match(Collections.singletonList("v[1~10]*"), "v12", Operation.REGEX.getValue())); assertThat(Operation.match(Collections.singletonList("v[1~10]*"), "v12", Operation.REGEX.getValue())).isFalse();
} }
} }

@ -20,37 +20,40 @@ package com.tencent.cloud.common.util;
import java.util.List; import java.util.List;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith; import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
/** /**
* test for {@link AddressUtils}. * test for {@link AddressUtils}.
* *
* @author lepdou 2022-05-27 * @author lepdou 2022-05-27
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class AddressUtilsTest { public class AddressUtilsTest {
@Test @Test
public void testEmptyStr() { public void testEmptyStr() {
List<String> result = AddressUtils.parseAddressList(""); List<String> result = AddressUtils.parseAddressList("");
Assert.assertEquals(0, result.size()); assertThat(result).isNotNull();
assertThat(result).isEmpty();
} }
@Test @Test
public void testNullStr() { public void testNullStr() {
List<String> result = AddressUtils.parseAddressList(null); List<String> result = AddressUtils.parseAddressList(null);
Assert.assertEquals(0, result.size()); assertThat(result).isNotNull();
assertThat(result).isEmpty();
} }
@Test @Test
public void testOneStr() { public void testOneStr() {
String host1 = "http://localhost"; String host1 = "http://localhost";
List<String> result = AddressUtils.parseAddressList(host1); List<String> result = AddressUtils.parseAddressList(host1);
Assert.assertEquals(1, result.size()); assertThat(result.size()).isEqualTo(1);
Assert.assertTrue(result.contains("localhost")); assertThat(result).contains("localhost");
} }
@Test @Test
@ -59,9 +62,9 @@ public class AddressUtilsTest {
String host2 = "http://localhost2"; String host2 = "http://localhost2";
String host3 = "http://localhost3"; String host3 = "http://localhost3";
List<String> result = AddressUtils.parseAddressList(host1 + "," + host2 + "," + host3); List<String> result = AddressUtils.parseAddressList(host1 + "," + host2 + "," + host3);
Assert.assertEquals(3, result.size()); assertThat(result.size()).isEqualTo(3);
Assert.assertTrue(result.contains("localhost")); assertThat(result).contains("localhost");
Assert.assertTrue(result.contains("localhost2")); assertThat(result).contains("localhost2");
Assert.assertTrue(result.contains("localhost3")); assertThat(result).contains("localhost3");
} }
} }

@ -17,12 +17,13 @@
package com.tencent.cloud.common.util; package com.tencent.cloud.common.util;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.support.RootBeanDefinition;
import static org.assertj.core.api.Assertions.assertThat;
/** /**
* Test for {@link BeanFactoryUtils}. * Test for {@link BeanFactoryUtils}.
* *
@ -37,10 +38,9 @@ public class BeanFactoryUtilsTest {
DefaultListableBeanFactory childBeanFactory = new DefaultListableBeanFactory(parentBeanFactory); DefaultListableBeanFactory childBeanFactory = new DefaultListableBeanFactory(parentBeanFactory);
Assert.assertTrue(childBeanFactory.getBeansOfType(Foo.class).isEmpty()); assertThat(childBeanFactory.getBeansOfType(Foo.class)).isEmpty();
Assert.assertTrue(BeanFactoryUtils.getBeans(childBeanFactory, Foo.class).size() == 1); assertThat(BeanFactoryUtils.getBeans(childBeanFactory, Foo.class).size()).isEqualTo(1);
assertThat(BeanFactoryUtils.getBeans(childBeanFactory, Bar.class)).isEmpty();
Assert.assertTrue(BeanFactoryUtils.getBeans(childBeanFactory, Bar.class).isEmpty());
} }
static class Foo { static class Foo {

@ -21,15 +21,14 @@ package com.tencent.cloud.common.util;
import java.net.URI; import java.net.URI;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.stream.Stream;
import com.google.common.collect.Sets;
import com.tencent.cloud.common.util.expresstion.ExpressionLabelUtils; import com.tencent.cloud.common.util.expresstion.ExpressionLabelUtils;
import com.tencent.cloud.common.util.expresstion.ServletExpressionLabelUtils; import com.tencent.cloud.common.util.expresstion.ServletExpressionLabelUtils;
import com.tencent.cloud.common.util.expresstion.SpringWebExpressionLabelUtils; import com.tencent.cloud.common.util.expresstion.SpringWebExpressionLabelUtils;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith; import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.http.HttpCookie; import org.springframework.http.HttpCookie;
import org.springframework.http.HttpMethod; import org.springframework.http.HttpMethod;
@ -39,12 +38,15 @@ import org.springframework.mock.web.MockCookie;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.mock.web.server.MockServerWebExchange;
import static java.util.stream.Collectors.toSet;
import static org.assertj.core.api.Assertions.assertThat;
/** /**
* test for {@link ExpressionLabelUtils}. * test for {@link ExpressionLabelUtils}.
* *
* @author lepdou 2022-05-27 * @author lepdou 2022-05-27
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class ExpressionLabelUtilsTest { public class ExpressionLabelUtilsTest {
@Test @Test
@ -64,20 +66,20 @@ public class ExpressionLabelUtilsTest {
String invalidLabel8 = "$${http.uri}"; String invalidLabel8 = "$${http.uri}";
String invalidLabel9 = "#{http.uri}"; String invalidLabel9 = "#{http.uri}";
Assert.assertTrue(ExpressionLabelUtils.isExpressionLabel(validLabel1)); assertThat(ExpressionLabelUtils.isExpressionLabel(validLabel1)).isTrue();
Assert.assertTrue(ExpressionLabelUtils.isExpressionLabel(validLabel2)); assertThat(ExpressionLabelUtils.isExpressionLabel(validLabel2)).isTrue();
Assert.assertTrue(ExpressionLabelUtils.isExpressionLabel(validLabel3)); assertThat(ExpressionLabelUtils.isExpressionLabel(validLabel3)).isTrue();
Assert.assertTrue(ExpressionLabelUtils.isExpressionLabel(validLabel4)); assertThat(ExpressionLabelUtils.isExpressionLabel(validLabel4)).isTrue();
Assert.assertTrue(ExpressionLabelUtils.isExpressionLabel(validLabel5)); assertThat(ExpressionLabelUtils.isExpressionLabel(validLabel5)).isTrue();
Assert.assertTrue(ExpressionLabelUtils.isExpressionLabel(invalidLabel1)); assertThat(ExpressionLabelUtils.isExpressionLabel(invalidLabel1)).isTrue();
Assert.assertFalse(ExpressionLabelUtils.isExpressionLabel(invalidLabel2)); assertThat(ExpressionLabelUtils.isExpressionLabel(invalidLabel2)).isFalse();
Assert.assertTrue(ExpressionLabelUtils.isExpressionLabel(invalidLabel3)); assertThat(ExpressionLabelUtils.isExpressionLabel(invalidLabel3)).isTrue();
Assert.assertTrue(ExpressionLabelUtils.isExpressionLabel(invalidLabel4)); assertThat(ExpressionLabelUtils.isExpressionLabel(invalidLabel4)).isTrue();
Assert.assertTrue(ExpressionLabelUtils.isExpressionLabel(invalidLabel5)); assertThat(ExpressionLabelUtils.isExpressionLabel(invalidLabel5)).isTrue();
Assert.assertTrue(ExpressionLabelUtils.isExpressionLabel(invalidLabel6)); assertThat(ExpressionLabelUtils.isExpressionLabel(invalidLabel6)).isTrue();
Assert.assertFalse(ExpressionLabelUtils.isExpressionLabel(invalidLabel7)); assertThat(ExpressionLabelUtils.isExpressionLabel(invalidLabel7)).isFalse();
Assert.assertTrue(ExpressionLabelUtils.isExpressionLabel(invalidLabel8)); assertThat(ExpressionLabelUtils.isExpressionLabel(invalidLabel8)).isTrue();
Assert.assertFalse(ExpressionLabelUtils.isExpressionLabel(invalidLabel9)); assertThat(ExpressionLabelUtils.isExpressionLabel(invalidLabel9)).isFalse();
} }
@Test @Test
@ -97,9 +99,9 @@ public class ExpressionLabelUtilsTest {
String invalidLabel8 = "$${http.uri}"; String invalidLabel8 = "$${http.uri}";
String invalidLabel9 = "#{http.uri}"; String invalidLabel9 = "#{http.uri}";
Set<String> labelKeys = Sets.newHashSet(validLabel1, validLabel2, validLabel3, validLabel4, validLabel5, Set<String> labelKeys = Stream.of(validLabel1, validLabel2, validLabel3, validLabel4, validLabel5,
invalidLabel1, invalidLabel2, invalidLabel3, invalidLabel4, invalidLabel5, invalidLabel6, invalidLabel7, invalidLabel1, invalidLabel2, invalidLabel3, invalidLabel4, invalidLabel5, invalidLabel6, invalidLabel7,
invalidLabel8, invalidLabel9); invalidLabel8, invalidLabel9).collect(toSet());
MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletRequest request = new MockHttpServletRequest();
request.setQueryString("uid=zhangsan"); request.setQueryString("uid=zhangsan");
@ -110,20 +112,20 @@ public class ExpressionLabelUtilsTest {
Map<String, String> result = ServletExpressionLabelUtils.resolve(request, labelKeys); Map<String, String> result = ServletExpressionLabelUtils.resolve(request, labelKeys);
Assert.assertEquals("zhangsan", result.get(validLabel1)); assertThat(result.get(validLabel1)).isEqualTo("zhangsan");
Assert.assertEquals("zhangsan", result.get(validLabel2)); assertThat(result.get(validLabel2)).isEqualTo("zhangsan");
Assert.assertEquals("zhangsan", result.get(validLabel3)); assertThat(result.get(validLabel3)).isEqualTo("zhangsan");
Assert.assertEquals("GET", result.get(validLabel4)); assertThat(result.get(validLabel4)).isEqualTo("GET");
Assert.assertEquals("/users", result.get(validLabel5)); assertThat(result.get(validLabel5)).isEqualTo("/users");
Assert.assertNull(result.get(invalidLabel1)); assertThat(result.get(invalidLabel1)).isNull();
Assert.assertNull(result.get(invalidLabel2)); assertThat(result.get(invalidLabel2)).isNull();
Assert.assertNull(result.get(invalidLabel3)); assertThat(result.get(invalidLabel3)).isNull();
Assert.assertNull(result.get(invalidLabel4)); assertThat(result.get(invalidLabel4)).isNull();
Assert.assertNull(result.get(invalidLabel5)); assertThat(result.get(invalidLabel5)).isNull();
Assert.assertNull(result.get(invalidLabel6)); assertThat(result.get(invalidLabel6)).isNull();
Assert.assertNull(result.get(invalidLabel7)); assertThat(result.get(invalidLabel7)).isNull();
Assert.assertNull(result.get(invalidLabel8)); assertThat(result.get(invalidLabel8)).isNull();
Assert.assertNull(result.get(invalidLabel9)); assertThat(result.get(invalidLabel9)).isNull();
} }
@Test @Test
@ -143,9 +145,9 @@ public class ExpressionLabelUtilsTest {
String invalidLabel8 = "$${http.uri}"; String invalidLabel8 = "$${http.uri}";
String invalidLabel9 = "#{http.uri}"; String invalidLabel9 = "#{http.uri}";
Set<String> labelKeys = Sets.newHashSet(validLabel1, validLabel2, validLabel3, validLabel4, validLabel5, Set<String> labelKeys = Stream.of(validLabel1, validLabel2, validLabel3, validLabel4, validLabel5,
invalidLabel1, invalidLabel2, invalidLabel3, invalidLabel4, invalidLabel5, invalidLabel6, invalidLabel7, invalidLabel1, invalidLabel2, invalidLabel3, invalidLabel4, invalidLabel5, invalidLabel6, invalidLabel7,
invalidLabel8, invalidLabel9); invalidLabel8, invalidLabel9).collect(toSet());
MockServerHttpRequest httpRequest = MockServerHttpRequest.get("http://calleeService/user/get?uid=zhangsan") MockServerHttpRequest httpRequest = MockServerHttpRequest.get("http://calleeService/user/get?uid=zhangsan")
.header("uid", "zhangsan") .header("uid", "zhangsan")
@ -154,20 +156,20 @@ public class ExpressionLabelUtilsTest {
Map<String, String> result = SpringWebExpressionLabelUtils.resolve(exchange, labelKeys); Map<String, String> result = SpringWebExpressionLabelUtils.resolve(exchange, labelKeys);
Assert.assertEquals("zhangsan", result.get(validLabel1)); assertThat(result.get(validLabel1)).isEqualTo("zhangsan");
Assert.assertEquals("zhangsan", result.get(validLabel2)); assertThat(result.get(validLabel2)).isEqualTo("zhangsan");
Assert.assertEquals("zhangsan", result.get(validLabel3)); assertThat(result.get(validLabel3)).isEqualTo("zhangsan");
Assert.assertEquals("GET", result.get(validLabel4)); assertThat(result.get(validLabel4)).isEqualTo("GET");
Assert.assertEquals("/user/get", result.get(validLabel5)); assertThat(result.get(validLabel5)).isEqualTo("/user/get");
Assert.assertNull(result.get(invalidLabel1)); assertThat(result.get(invalidLabel1)).isNull();
Assert.assertNull(result.get(invalidLabel2)); assertThat(result.get(invalidLabel2)).isNull();
Assert.assertNull(result.get(invalidLabel3)); assertThat(result.get(invalidLabel3)).isNull();
Assert.assertNull(result.get(invalidLabel4)); assertThat(result.get(invalidLabel4)).isNull();
Assert.assertNull(result.get(invalidLabel5)); assertThat(result.get(invalidLabel5)).isNull();
Assert.assertNull(result.get(invalidLabel6)); assertThat(result.get(invalidLabel6)).isNull();
Assert.assertNull(result.get(invalidLabel7)); assertThat(result.get(invalidLabel7)).isNull();
Assert.assertNull(result.get(invalidLabel8)); assertThat(result.get(invalidLabel8)).isNull();
Assert.assertNull(result.get(invalidLabel9)); assertThat(result.get(invalidLabel9)).isNull();
} }
@Test @Test
@ -187,9 +189,9 @@ public class ExpressionLabelUtilsTest {
String invalidLabel8 = "$${http.uri}"; String invalidLabel8 = "$${http.uri}";
String invalidLabel9 = "#{http.uri}"; String invalidLabel9 = "#{http.uri}";
Set<String> labelKeys = Sets.newHashSet(validLabel1, validLabel2, validLabel3, validLabel4, validLabel5, Set<String> labelKeys = Stream.of(validLabel1, validLabel2, validLabel3, validLabel4, validLabel5,
invalidLabel1, invalidLabel2, invalidLabel3, invalidLabel4, invalidLabel5, invalidLabel6, invalidLabel7, invalidLabel1, invalidLabel2, invalidLabel3, invalidLabel4, invalidLabel5, invalidLabel6, invalidLabel7,
invalidLabel8, invalidLabel9); invalidLabel8, invalidLabel9).collect(toSet());
MockClientHttpRequest request = new MockClientHttpRequest(); MockClientHttpRequest request = new MockClientHttpRequest();
request.setMethod(HttpMethod.GET); request.setMethod(HttpMethod.GET);
@ -198,19 +200,19 @@ public class ExpressionLabelUtilsTest {
Map<String, String> result = SpringWebExpressionLabelUtils.resolve(request, labelKeys); Map<String, String> result = SpringWebExpressionLabelUtils.resolve(request, labelKeys);
Assert.assertEquals("zhangsan", result.get(validLabel1)); assertThat(result.get(validLabel1)).isEqualTo("zhangsan");
Assert.assertEquals("zhangsan", result.get(validLabel2)); assertThat(result.get(validLabel2)).isEqualTo("zhangsan");
Assert.assertNull(result.get(validLabel3)); assertThat(result.get(validLabel3)).isNull();
Assert.assertEquals("GET", result.get(validLabel4)); assertThat(result.get(validLabel4)).isEqualTo("GET");
Assert.assertEquals("/user/get", result.get(validLabel5)); assertThat(result.get(validLabel5)).isEqualTo("/user/get");
Assert.assertNull(result.get(invalidLabel1)); assertThat(result.get(invalidLabel1)).isNull();
Assert.assertNull(result.get(invalidLabel2)); assertThat(result.get(invalidLabel2)).isNull();
Assert.assertNull(result.get(invalidLabel3)); assertThat(result.get(invalidLabel3)).isNull();
Assert.assertNull(result.get(invalidLabel4)); assertThat(result.get(invalidLabel4)).isNull();
Assert.assertNull(result.get(invalidLabel5)); assertThat(result.get(invalidLabel5)).isNull();
Assert.assertNull(result.get(invalidLabel6)); assertThat(result.get(invalidLabel6)).isNull();
Assert.assertNull(result.get(invalidLabel7)); assertThat(result.get(invalidLabel7)).isNull();
Assert.assertNull(result.get(invalidLabel8)); assertThat(result.get(invalidLabel8)).isNull();
Assert.assertNull(result.get(invalidLabel9)); assertThat(result.get(invalidLabel9)).isNull();
} }
} }

@ -18,8 +18,9 @@
package com.tencent.cloud.common.util; package com.tencent.cloud.common.util;
import com.tencent.cloud.common.util.expresstion.ExpressionParserV1; import com.tencent.cloud.common.util.expresstion.ExpressionParserV1;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
/** /**
* Test for {@link ExpressionParserV1}. * Test for {@link ExpressionParserV1}.
@ -46,25 +47,25 @@ public class ExpressionParserV1Test {
ExpressionParserV1 parser = new ExpressionParserV1(); ExpressionParserV1 parser = new ExpressionParserV1();
Assert.assertTrue(parser.isExpressionLabel(validLabel1)); assertThat(parser.isExpressionLabel(validLabel1)).isTrue();
Assert.assertTrue(parser.isExpressionLabel(validLabel2)); assertThat(parser.isExpressionLabel(validLabel2)).isTrue();
Assert.assertTrue(parser.isExpressionLabel(validLabel3)); assertThat(parser.isExpressionLabel(validLabel3)).isTrue();
Assert.assertTrue(parser.isExpressionLabel(validLabel4)); assertThat(parser.isExpressionLabel(validLabel4)).isTrue();
Assert.assertTrue(parser.isExpressionLabel(validLabel5)); assertThat(parser.isExpressionLabel(validLabel5)).isTrue();
Assert.assertTrue(parser.isExpressionLabel(invalidLabel1)); assertThat(parser.isExpressionLabel(invalidLabel1)).isTrue();
Assert.assertFalse(parser.isExpressionLabel(invalidLabel2)); assertThat(parser.isExpressionLabel(invalidLabel2)).isFalse();
Assert.assertFalse(parser.isExpressionLabel(invalidLabel3)); assertThat(parser.isExpressionLabel(invalidLabel3)).isFalse();
Assert.assertFalse(parser.isExpressionLabel(invalidLabel4)); assertThat(parser.isExpressionLabel(invalidLabel4)).isFalse();
Assert.assertTrue(parser.isExpressionLabel(invalidLabel5)); assertThat(parser.isExpressionLabel(invalidLabel5)).isTrue();
Assert.assertTrue(parser.isExpressionLabel(invalidLabel6)); assertThat(parser.isExpressionLabel(invalidLabel6)).isTrue();
Assert.assertFalse(parser.isExpressionLabel(invalidLabel7)); assertThat(parser.isExpressionLabel(invalidLabel7)).isFalse();
Assert.assertFalse(parser.isExpressionLabel(invalidLabel8)); assertThat(parser.isExpressionLabel(invalidLabel8)).isFalse();
Assert.assertFalse(parser.isExpressionLabel(invalidLabel9)); assertThat(parser.isExpressionLabel(invalidLabel9)).isFalse();
Assert.assertTrue(parser.isQueryLabel(validLabel1)); assertThat(parser.isQueryLabel(validLabel1)).isTrue();
Assert.assertTrue(parser.isHeaderLabel(validLabel2)); assertThat(parser.isHeaderLabel(validLabel2)).isTrue();
Assert.assertTrue(parser.isCookieLabel(validLabel3)); assertThat(parser.isCookieLabel(validLabel3)).isTrue();
Assert.assertTrue(parser.isMethodLabel(validLabel4)); assertThat(parser.isMethodLabel(validLabel4)).isTrue();
Assert.assertTrue(parser.isUriLabel(validLabel5)); assertThat(parser.isUriLabel(validLabel5)).isTrue();
} }
} }

@ -18,8 +18,9 @@
package com.tencent.cloud.common.util; package com.tencent.cloud.common.util;
import com.tencent.cloud.common.util.expresstion.ExpressionParserV2; import com.tencent.cloud.common.util.expresstion.ExpressionParserV2;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
/** /**
* Test for {@link ExpressionParserV2}. * Test for {@link ExpressionParserV2}.
@ -46,29 +47,29 @@ public class ExpressionParserV2Test {
ExpressionParserV2 parser = new ExpressionParserV2(); ExpressionParserV2 parser = new ExpressionParserV2();
Assert.assertTrue(parser.isExpressionLabel(validLabel1)); assertThat(parser.isExpressionLabel(validLabel1)).isTrue();
Assert.assertTrue(parser.isExpressionLabel(validLabel2)); assertThat(parser.isExpressionLabel(validLabel2)).isTrue();
Assert.assertTrue(parser.isExpressionLabel(validLabel3)); assertThat(parser.isExpressionLabel(validLabel3)).isTrue();
Assert.assertTrue(parser.isExpressionLabel(validLabel4)); assertThat(parser.isExpressionLabel(validLabel4)).isTrue();
Assert.assertTrue(parser.isExpressionLabel(validLabel5)); assertThat(parser.isExpressionLabel(validLabel5)).isTrue();
Assert.assertTrue(parser.isExpressionLabel(invalidLabel1)); assertThat(parser.isExpressionLabel(invalidLabel1)).isTrue();
Assert.assertFalse(parser.isExpressionLabel(invalidLabel2)); assertThat(parser.isExpressionLabel(invalidLabel2)).isFalse();
Assert.assertTrue(parser.isExpressionLabel(invalidLabel3)); assertThat(parser.isExpressionLabel(invalidLabel3)).isTrue();
Assert.assertTrue(parser.isExpressionLabel(invalidLabel4)); assertThat(parser.isExpressionLabel(invalidLabel4)).isTrue();
Assert.assertTrue(parser.isExpressionLabel(invalidLabel5)); assertThat(parser.isExpressionLabel(invalidLabel5)).isTrue();
Assert.assertTrue(parser.isExpressionLabel(invalidLabel6)); assertThat(parser.isExpressionLabel(invalidLabel6)).isTrue();
Assert.assertFalse(parser.isExpressionLabel(invalidLabel7)); assertThat(parser.isExpressionLabel(invalidLabel7)).isFalse();
Assert.assertTrue(parser.isExpressionLabel(invalidLabel8)); assertThat(parser.isExpressionLabel(invalidLabel8)).isTrue();
Assert.assertFalse(parser.isExpressionLabel(invalidLabel9)); assertThat(parser.isExpressionLabel(invalidLabel9)).isFalse();
Assert.assertFalse(parser.isQueryLabel(validLabel1)); assertThat(parser.isQueryLabel(validLabel1)).isFalse();
Assert.assertFalse(parser.isHeaderLabel(validLabel2)); assertThat(parser.isHeaderLabel(validLabel2)).isFalse();
Assert.assertFalse(parser.isCookieLabel(validLabel3)); assertThat(parser.isCookieLabel(validLabel3)).isFalse();
Assert.assertFalse(parser.isMethodLabel(validLabel4)); assertThat(parser.isMethodLabel(validLabel4)).isFalse();
Assert.assertFalse(parser.isUriLabel(validLabel5)); assertThat(parser.isUriLabel(validLabel5)).isFalse();
Assert.assertTrue(parser.isHeaderLabel("$header.userId")); assertThat(parser.isHeaderLabel("$header.userId")).isTrue();
Assert.assertTrue(parser.isMethodLabel("$method")); assertThat(parser.isMethodLabel("$method")).isTrue();
Assert.assertTrue(parser.isQueryLabel("$query.userId")); assertThat(parser.isQueryLabel("$query.userId")).isTrue();
} }
} }

@ -21,9 +21,9 @@ package com.tencent.cloud.common.util;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatThrownBy;
@ -33,7 +33,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
* *
* @author lepdou, Haotian Zhang, cheese8 * @author lepdou, Haotian Zhang, cheese8
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class JacksonUtilsTest { public class JacksonUtilsTest {
@Test @Test

@ -20,28 +20,29 @@ package com.tencent.cloud.common.util;
import java.io.IOException; import java.io.IOException;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith; import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
/** /**
* test for {@link ResourceFileUtils}. * test for {@link ResourceFileUtils}.
* *
* @author lepdou 2022-05-27 * @author lepdou 2022-05-27
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class ResourceFileUtilsTest { public class ResourceFileUtilsTest {
@Test @Test
public void testReadExistedFile() throws IOException { public void testReadExistedFile() throws IOException {
String content = ResourceFileUtils.readFile("test.txt"); String content = ResourceFileUtils.readFile("test.txt");
Assert.assertEquals("just for test", content); assertThat(content).isEqualTo("just for test");
} }
@Test @Test
public void testReadNotExistedFile() throws IOException { public void testReadNotExistedFile() throws IOException {
String content = ResourceFileUtils.readFile("not_existed_test.txt"); String content = ResourceFileUtils.readFile("not_existed_test.txt");
Assert.assertEquals("", content); assertThat(content).isEqualTo("");
} }
} }

@ -73,13 +73,13 @@
<revision>1.10.0-2022.0.1-SNAPSHOT</revision> <revision>1.10.0-2022.0.1-SNAPSHOT</revision>
<!-- Dependencies --> <!-- Dependencies -->
<polaris.version>1.10.5</polaris.version> <polaris.version>1.11.0-SNAPSHOT</polaris.version>
<guava.version>31.1-jre</guava.version> <guava.version>31.1-jre</guava.version>
<mocktio.version>4.9.0</mocktio.version> <mocktio.version>4.9.0</mocktio.version>
<byte-buddy.version>1.12.19</byte-buddy.version> <byte-buddy.version>1.12.19</byte-buddy.version>
<protobuf-java.version>3.21.7</protobuf-java.version> <protobuf-java.version>3.21.7</protobuf-java.version>
<bcprov-jdk15on.version>1.69</bcprov-jdk15on.version> <bcprov-jdk15on.version>1.69</bcprov-jdk15on.version>
<system-stubs-junit4.version>2.0.1</system-stubs-junit4.version> <system-stubs-jupiter.version>2.0.2</system-stubs-jupiter.version>
<!-- Maven Plugin Versions --> <!-- Maven Plugin Versions -->
<flatten-maven-plugin.version>1.3.0</flatten-maven-plugin.version> <flatten-maven-plugin.version>1.3.0</flatten-maven-plugin.version>
@ -231,8 +231,8 @@
<dependency> <dependency>
<groupId>uk.org.webcompere</groupId> <groupId>uk.org.webcompere</groupId>
<artifactId>system-stubs-junit4</artifactId> <artifactId>system-stubs-jupiter</artifactId>
<version>${system-stubs-junit4.version}</version> <version>${system-stubs-jupiter.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>

@ -29,18 +29,19 @@ import com.tencent.polaris.api.pojo.ServiceInstances;
import com.tencent.polaris.api.pojo.ServiceKey; import com.tencent.polaris.api.pojo.ServiceKey;
import com.tencent.polaris.plugins.router.metadata.MetadataRouter; import com.tencent.polaris.plugins.router.metadata.MetadataRouter;
import com.tencent.polaris.router.api.rpc.ProcessRoutersRequest; import com.tencent.polaris.router.api.rpc.ProcessRoutersRequest;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.Assertions.assertThat;
/** /**
* Test for {@link FeatureEnvRouterRequestInterceptor}. * Test for {@link FeatureEnvRouterRequestInterceptor}.
* *
* @author lepdou, Hoatian Zhang * @author lepdou, Hoatian Zhang
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class FeatureEnvRouterRequestInterceptorTest { public class FeatureEnvRouterRequestInterceptorTest {
@Test @Test
@ -59,8 +60,8 @@ public class FeatureEnvRouterRequestInterceptorTest {
interceptor.apply(request, routerContext); interceptor.apply(request, routerContext);
Map<String, String> metadataRouterLabels = request.getRouterMetadata().get(MetadataRouter.ROUTER_TYPE_METADATA); Map<String, String> metadataRouterLabels = request.getRouterMetadata().get(MetadataRouter.ROUTER_TYPE_METADATA);
Assert.assertEquals(1, metadataRouterLabels.size()); assertThat(metadataRouterLabels.size()).isEqualTo(1);
Assert.assertEquals("blue", metadataRouterLabels.get("featureenv")); assertThat(metadataRouterLabels.get("featureenv")).isEqualTo("blue");
} }
@Test @Test
@ -80,8 +81,8 @@ public class FeatureEnvRouterRequestInterceptorTest {
interceptor.apply(request, routerContext); interceptor.apply(request, routerContext);
Map<String, String> metadataRouterLabels = request.getRouterMetadata().get(MetadataRouter.ROUTER_TYPE_METADATA); Map<String, String> metadataRouterLabels = request.getRouterMetadata().get(MetadataRouter.ROUTER_TYPE_METADATA);
Assert.assertEquals(1, metadataRouterLabels.size()); assertThat(metadataRouterLabels.size()).isEqualTo(1);
Assert.assertEquals("blue", metadataRouterLabels.get("specify-env")); assertThat(metadataRouterLabels.get("specify-env")).isEqualTo("blue");
} }
@Test @Test
@ -100,7 +101,7 @@ public class FeatureEnvRouterRequestInterceptorTest {
interceptor.apply(request, routerContext); interceptor.apply(request, routerContext);
Map<String, String> metadataRouterLabels = request.getRouterMetadata().get(MetadataRouter.ROUTER_TYPE_METADATA); Map<String, String> metadataRouterLabels = request.getRouterMetadata().get(MetadataRouter.ROUTER_TYPE_METADATA);
Assert.assertEquals(1, metadataRouterLabels.size()); assertThat(metadataRouterLabels.size()).isEqualTo(1);
Assert.assertEquals("NOT_EXISTED_ENV", metadataRouterLabels.get("specify-env")); assertThat(metadataRouterLabels.get("specify-env")).isEqualTo("NOT_EXISTED_ENV");
} }
} }

@ -26,24 +26,24 @@ import com.tencent.cloud.plugin.gateway.staining.rule.StainingRuleManager;
import com.tencent.polaris.client.api.SDKContext; import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.configuration.api.core.ConfigFileService; import com.tencent.polaris.configuration.api.core.ConfigFileService;
import com.tencent.polaris.configuration.factory.ConfigFileServiceFactory; import com.tencent.polaris.configuration.factory.ConfigFileServiceFactory;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT;
/** /**
* Test for {@link SCGPluginsAutoConfiguration}. * Test for {@link SCGPluginsAutoConfiguration}.
* @author derek.yi 2022-11-03 * @author derek.yi 2022-11-03
*/ */
@RunWith(SpringRunner.class) @ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = DEFINED_PORT, classes = SCGPluginsAutoConfigurationTest.TestApplication.class, @SpringBootTest(webEnvironment = DEFINED_PORT, classes = SCGPluginsAutoConfigurationTest.TestApplication.class,
properties = {"server.port=8081", "spring.config.location = classpath:application-test.yml", properties = {"server.port=8081", "spring.config.location = classpath:application-test.yml",
"spring.cloud.tencent.plugin.scg.staining.rule-staining.enabled = true"}) "spring.cloud.tencent.plugin.scg.staining.rule-staining.enabled = true"})
@ -54,11 +54,11 @@ public class SCGPluginsAutoConfigurationTest {
@Test @Test
public void testAutoConfiguration() { public void testAutoConfiguration() {
Assert.assertEquals(1, applicationContext.getBeansOfType(RuleStainingProperties.class).size()); assertThat(applicationContext.getBeansOfType(RuleStainingProperties.class).size()).isEqualTo(1);
Assert.assertEquals(1, applicationContext.getBeansOfType(StainingRuleManager.class).size()); assertThat(applicationContext.getBeansOfType(StainingRuleManager.class).size()).isEqualTo(1);
Assert.assertEquals(1, applicationContext.getBeansOfType(TrafficStainingGatewayFilter.class).size()); assertThat(applicationContext.getBeansOfType(TrafficStainingGatewayFilter.class).size()).isEqualTo(1);
Assert.assertEquals(1, applicationContext.getBeansOfType(RuleStainingExecutor.class).size()); assertThat(applicationContext.getBeansOfType(RuleStainingExecutor.class).size()).isEqualTo(1);
Assert.assertEquals(1, applicationContext.getBeansOfType(RuleTrafficStainer.class).size()); assertThat(applicationContext.getBeansOfType(RuleTrafficStainer.class).size()).isEqualTo(1);
} }
@SpringBootApplication @SpringBootApplication

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save