refactor:update to junit 5.

pull/1080/head
Haotian Zhang 2 years ago
parent f97a1b2450
commit 21953e17b6

@ -26,9 +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 com.tencent.cloud.metadata.core.EncodeTransferMetadataZuulFilter; import org.junit.jupiter.api.Test;
import org.assertj.core.api.Assertions;
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;
@ -39,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}.
* *
@ -53,25 +53,14 @@ public class MetadataTransferAutoConfigurationTest {
*/ */
@Test @Test
public void test1() { public void test1() {
this.applicationContextRunner this.applicationContextRunner.withConfiguration(AutoConfigurations.of(MetadataTransferAutoConfiguration.class))
.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) assertThat(context).hasSingleBean(MetadataTransferAutoConfiguration.MetadataTransferRestTemplateConfig.class);
.hasSingleBean(EncodeTransferMedataFeignInterceptor.class); assertThat(context).hasSingleBean(EncodeTransferMedataRestTemplateInterceptor.class);
Assertions.assertThat(context).hasSingleBean( assertThat(context).hasSingleBean(MetadataTransferAutoConfiguration.MetadataTransferScgFilterConfig.class);
MetadataTransferAutoConfiguration.MetadataTransferRestTemplateConfig.class); assertThat(context).hasSingleBean(GlobalFilter.class);
Assertions.assertThat(context).hasSingleBean(
EncodeTransferMedataRestTemplateInterceptor.class);
Assertions.assertThat(context).hasSingleBean(
MetadataTransferAutoConfiguration.MetadataTransferZuulFilterConfig.class);
Assertions.assertThat(context)
.hasSingleBean(EncodeTransferMetadataZuulFilter.class);
Assertions.assertThat(context).hasSingleBean(
MetadataTransferAutoConfiguration.MetadataTransferScgFilterConfig.class);
Assertions.assertThat(context).hasSingleBean(GlobalFilter.class);
}); });
} }
@ -82,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,10 +40,10 @@ 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", "spring.main.web-application-type = reactive" }) properties = {"spring.config.location = classpath:application-test.yml", "spring.main.web-application-type = reactive"})
public class DecodeTransferMetadataReactiveFilterTest { public class DecodeTransferMetadataReactiveFilterTest {
@Autowired @Autowired
@ -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,10 +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")) assertThat(metadataLocalProperties.getContent().get("a")).isEqualTo("1");
.isEqualTo("1"); assertThat(metadataLocalProperties.getContent().get("b")).isEqualTo("2");
Assertions.assertThat(metadataLocalProperties.getContent().get("b")) assertThat(metadataLocalProperties.getContent().get("c")).isNull();
.isEqualTo("2");
Assertions.assertThat(metadataLocalProperties.getContent().get("c")).isNull();
} }
} }

@ -24,17 +24,17 @@ import javax.servlet.ServletException;
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.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;
/** /**
@ -42,12 +42,12 @@ 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",
"spring.main.web-application-type = servlet", "spring.main.web-application-type = servlet",
"spring.cloud.gateway.enabled = false" }) "spring.cloud.gateway.enabled = false"})
public class DecodeTransferMetadataServletFilterTest { public class DecodeTransferMetadataServletFilterTest {
@Autowired @Autowired
@ -68,9 +68,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

@ -17,17 +17,14 @@
package com.tencent.cloud.metadata.core; package com.tencent.cloud.metadata.core;
import java.io.UnsupportedEncodingException;
import com.tencent.cloud.common.constant.MetadataConstant; import com.tencent.cloud.common.constant.MetadataConstant;
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.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;
@ -35,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;
/** /**
@ -46,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", properties = {"server.port=8081",
@ -64,9 +62,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
@ -75,7 +73,7 @@ public class EncodeTransferMedataFeignInterceptorTest {
protected static class TestApplication { protected static class TestApplication {
@RequestMapping("/test") @RequestMapping("/test")
public String test() throws UnsupportedEncodingException { public String test() {
return MetadataContextHolder.get().getContext(MetadataContext.FRAGMENT_TRANSITIVE, "b"); return MetadataContextHolder.get().getContext(MetadataContext.FRAGMENT_TRANSITIVE, "b");
} }
@ -91,8 +89,7 @@ public class EncodeTransferMedataFeignInterceptorTest {
@Override @Override
public void apply(RequestTemplate template) { public void apply(RequestTemplate template) {
template.header(MetadataConstant.HeaderName.CUSTOM_METADATA, template.header(MetadataConstant.HeaderName.CUSTOM_METADATA, "{\"a\":\"11\",\"b\":\"22\",\"c\":\"33\"}");
"{\"a\":\"11\",\"b\":\"22\",\"c\":\"33\"}");
} }
} }
} }

@ -17,13 +17,10 @@
package com.tencent.cloud.metadata.core; package com.tencent.cloud.metadata.core;
import java.io.UnsupportedEncodingException;
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;
@ -33,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;
/** /**
@ -45,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",
@ -65,7 +63,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
@ -78,7 +76,7 @@ public class EncodeTransferMedataRestTemplateInterceptorTest {
} }
@RequestMapping("/test") @RequestMapping("/test")
public String test() throws UnsupportedEncodingException { public String test() {
return MetadataContextHolder.get().getContext(MetadataContext.FRAGMENT_TRANSITIVE, "b"); return MetadataContextHolder.get().getContext(MetadataContext.FRAGMENT_TRANSITIVE, "b");
} }
} }

@ -24,9 +24,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;
@ -36,17 +35,17 @@ 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;
/** /**
* @author quan * @author quan
*/ */
@RunWith(SpringRunner.class) @ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = RANDOM_PORT, @SpringBootTest(webEnvironment = RANDOM_PORT, classes = EncodeTransferMedataScgFilterTest.TestApplication.class,
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"})
public class EncodeTransferMedataScgFilterTest { public class EncodeTransferMedataScgFilterTest {
@ -60,20 +59,14 @@ public class EncodeTransferMedataScgFilterTest {
@Test @Test
public void testTransitiveMetadataFromApplicationConfig() throws UnsupportedEncodingException { public void testTransitiveMetadataFromApplicationConfig() throws UnsupportedEncodingException {
EncodeTransferMedataScgFilter filter = applicationContext.getBean(EncodeTransferMedataScgFilter.class); EncodeTransferMedataScgFilter filter = applicationContext.getBean(EncodeTransferMedataScgFilter.class);
// Mock Server Http Request
MockServerHttpRequest.BaseBuilder<?> builder = MockServerHttpRequest.get(""); MockServerHttpRequest.BaseBuilder<?> builder = MockServerHttpRequest.get("");
MockServerWebExchange exchange = MockServerWebExchange.from(builder); MockServerWebExchange exchange = MockServerWebExchange.from(builder);
filter.filter(exchange, chain); filter.filter(exchange, chain);
String metadataStr = exchange.getRequest().getHeaders().getFirst(MetadataConstant.HeaderName.CUSTOM_METADATA);
// Check metadata str String decode = URLDecoder.decode(metadataStr, UTF_8);
String metadata = exchange.getRequest().getHeaders().getFirst(MetadataConstant.HeaderName.CUSTOM_METADATA);
Assertions.assertThat(metadata).isNotNull();
String decode = URLDecoder.decode(metadata, 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

@ -26,16 +26,16 @@ import com.netflix.zuul.context.RequestContext;
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.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.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.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.mock.web.MockMultipartHttpServletRequest; import org.springframework.mock.web.MockMultipartHttpServletRequest;
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.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, @SpringBootTest(webEnvironment = RANDOM_PORT,
classes = EncodeTransferMetadataZuulFilterTest.TestApplication.class, classes = EncodeTransferMetadataZuulFilterTest.TestApplication.class,
properties = {"spring.config.location = classpath:application-test.yml", properties = {"spring.config.location = classpath:application-test.yml",
@ -56,8 +56,8 @@ public class EncodeTransferMetadataZuulFilterTest {
@Autowired @Autowired
private ApplicationContext applicationContext; private ApplicationContext applicationContext;
@Before @BeforeEach
public void init() { void setUp() {
RequestContext ctx = RequestContext.getCurrentContext(); RequestContext ctx = RequestContext.getCurrentContext();
ctx.clear(); ctx.clear();
ctx.setRequest(this.request); ctx.setRequest(this.request);

@ -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", "spring.main.web-application-type=reactive"}) properties = {"spring.config.location = classpath:application-test.yml", "spring.main.web-application-type=reactive"})
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;
@ -78,9 +79,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,15 +29,15 @@ 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;
/** /**
@ -45,7 +45,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 PolarisConfigFileLocatorTest { public class PolarisConfigFileLocatorTest {
private final String testNamespace = "testNamespace"; private final String testNamespace = "testNamespace";
@ -89,9 +89,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
@ -132,9 +132,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
@ -181,8 +181,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");
} }
} }

@ -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();
} }

@ -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,12 +45,12 @@ 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, @SpringBootTest(webEnvironment = DEFINED_PORT, classes = ConfigChangeListenerTest.TestApplication.class,
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 {
private static final CountDownLatch hits = new CountDownLatch(2);
@Autowired @Autowired
private ApplicationEventPublisher applicationEventPublisher; private ApplicationEventPublisher applicationEventPublisher;
@Autowired @Autowired
@ -58,8 +58,6 @@ public class ConfigChangeListenerTest {
@Autowired @Autowired
private TestApplication.TestConfig testConfig; private TestApplication.TestConfig testConfig;
private static final CountDownLatch hits = new CountDownLatch(2);
@Test @Test
public void test() throws InterruptedException { public void test() throws InterruptedException {
//before change //before change

@ -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();
} }
@ -91,19 +91,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);
}); });
} }
@ -124,19 +124,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");
}); });
} }
@ -158,31 +158,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();
} }
} }

@ -36,6 +36,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,15 +24,14 @@ 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;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import static com.tencent.polaris.test.common.Consts.NAMESPACE_TEST; import static com.tencent.polaris.test.common.Consts.NAMESPACE_TEST;
@ -58,17 +57,16 @@ public class PolarisDiscoveryEndpointTest {
.withPropertyValues("spring.application.name=" + SERVICE_PROVIDER) .withPropertyValues("spring.application.name=" + SERVICE_PROVIDER)
.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")
.withPropertyValues( .withPropertyValues("spring.cloud.polaris.discovery.namespace=" + NAMESPACE_TEST)
"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() throws Exception { static void afterAll() {
if (null != namingServer) { if (null != namingServer) {
namingServer.terminate(); namingServer.terminate();
} }
@ -87,15 +85,12 @@ public class PolarisDiscoveryEndpointTest {
Map<String, Object> mapInfo = polarisDiscoveryEndpoint.polarisDiscovery("java_provider_test"); Map<String, Object> mapInfo = polarisDiscoveryEndpoint.polarisDiscovery("java_provider_test");
assertThat(polarisDiscoveryProperties).isEqualTo(mapInfo.get("PolarisDiscoveryProperties")); assertThat(polarisDiscoveryProperties).isEqualTo(mapInfo.get("PolarisDiscoveryProperties"));
}); });
} }
@Configuration @Configuration
@EnableAutoConfiguration @EnableAutoConfiguration
@EnableDiscoveryClient
static class PolarisPropertiesConfiguration { static class PolarisPropertiesConfiguration {
} }
} }

@ -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 {

@ -24,14 +24,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;
@ -41,7 +41,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 {
@ -74,7 +74,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();

@ -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();
}
}); });
} }

@ -17,7 +17,7 @@
package com.tencent.cloud.polaris.ribbon; package com.tencent.cloud.polaris.ribbon;
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.ribbon;
import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.DefaultClientConfigImpl;
import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.ServerList; import com.netflix.loadbalancer.ServerList;
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.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;

@ -17,6 +17,7 @@
package com.tencent.cloud.polaris.ribbon; package com.tencent.cloud.polaris.ribbon;
import java.io.IOException;
import java.util.List; import java.util.List;
import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfig;
@ -28,10 +29,10 @@ import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler;
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 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.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.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@ -69,23 +70,23 @@ public class PolarisServerListTest {
private IClientConfig iClientConfig; private IClientConfig iClientConfig;
@BeforeClass @BeforeAll
public static void beforeClass() throws Exception { static void beforeAll() throws IOException {
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();
} }
} }
@Before @BeforeEach
public void setUp() { void setUp() {
// mock IClientConfig // mock IClientConfig
iClientConfig = mock(IClientConfig.class); iClientConfig = mock(IClientConfig.class);
when(iClientConfig.getClientName()).thenReturn(SERVICE_PROVIDER); when(iClientConfig.getClientName()).thenReturn(SERVICE_PROVIDER);

@ -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.web.server.LocalServerPort; import org.springframework.boot.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,16 +39,14 @@ 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 ServiceRuleManager serviceRuleManager;
private RateLimitRuleLabelResolver rateLimitRuleLabelResolver; private RateLimitRuleLabelResolver rateLimitRuleLabelResolver;
@Before @BeforeEach
public void setUp() { void setUp() {
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();
if (serviceName.equals("TestApp1")) { if (serviceName.equals("TestApp1")) {
@ -63,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.web.server.LocalServerPort; import org.springframework.boot.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", properties = { "spring.application.name=java_provider_test",
@ -73,8 +74,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
@ -87,15 +88,15 @@ public class CalleeControllerTests {
instanceParameter); 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);
@ -126,12 +127,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 WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
@ -67,8 +67,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();
@ -84,7 +84,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,10 +71,10 @@ import static org.mockito.Mockito.when;
* *
* @author Haotian Zhang, cheese8, kaiy * @author Haotian Zhang, cheese8, kaiy
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
@SpringBootTest(classes = QuotaCheckReactiveFilterTest.TestApplication.class, properties = { @MockitoSettings(strictness = Strictness.LENIENT)
"spring.cloud.polaris.namespace=Test", "spring.cloud.polaris.service=TestApp" @SpringBootTest(classes = QuotaCheckReactiveFilterTest.TestApplication.class,
}) properties = {"spring.cloud.polaris.namespace=Test", "spring.cloud.polaris.service=TestApp"})
public class QuotaCheckReactiveFilterTest { public class QuotaCheckReactiveFilterTest {
private static MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils; private static MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils;
@ -83,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"));
@ -94,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();
@ -127,7 +129,8 @@ public class QuotaCheckReactiveFilterTest {
polarisRateLimitProperties.setRejectHttpCode(419); polarisRateLimitProperties.setRejectHttpCode(419);
RateLimitRuleLabelResolver rateLimitRuleLabelResolver = mock(RateLimitRuleLabelResolver.class); RateLimitRuleLabelResolver rateLimitRuleLabelResolver = mock(RateLimitRuleLabelResolver.class);
when(rateLimitRuleLabelResolver.getExpressionLabelKeys(anyString(), anyString())).thenReturn(Collections.emptySet()); when(rateLimitRuleLabelResolver.getExpressionLabelKeys(anyString(), anyString()))
.thenReturn(Collections.emptySet());
this.quotaCheckReactiveFilter = new QuotaCheckReactiveFilter( this.quotaCheckReactiveFilter = new QuotaCheckReactiveFilter(
limitAPI, labelResolver, polarisRateLimitProperties, rateLimitRuleLabelResolver, null); limitAPI, labelResolver, polarisRateLimitProperties, rateLimitRuleLabelResolver, null);
@ -156,7 +159,8 @@ public class QuotaCheckReactiveFilterTest {
@Test @Test
public void testGetRuleExpressionLabels() { public void testGetRuleExpressionLabels() {
try { try {
Method getCustomResolvedLabels = QuotaCheckReactiveFilter.class.getDeclaredMethod("getCustomResolvedLabels", ServerWebExchange.class); Method getCustomResolvedLabels =
QuotaCheckReactiveFilter.class.getDeclaredMethod("getCustomResolvedLabels", ServerWebExchange.class);
getCustomResolvedLabels.setAccessible(true); getCustomResolvedLabels.setAccessible(true);
// Mock request // Mock request
@ -169,11 +173,8 @@ public class QuotaCheckReactiveFilterTest {
assertThat(result.get("ReactiveResolver")).isEqualTo("ReactiveResolver"); assertThat(result.get("ReactiveResolver")).isEqualTo("ReactiveResolver");
// throw exception // throw exception
PolarisRateLimiterLabelReactiveResolver exceptionLabelResolver = new PolarisRateLimiterLabelReactiveResolver() { PolarisRateLimiterLabelReactiveResolver exceptionLabelResolver = exchange1 -> {
@Override
public Map<String, String> resolve(ServerWebExchange exchange) {
throw new RuntimeException("Mock exception."); throw new RuntimeException("Mock exception.");
}
}; };
quotaCheckReactiveFilter = new QuotaCheckReactiveFilter(null, exceptionLabelResolver, null, null, null); quotaCheckReactiveFilter = new QuotaCheckReactiveFilter(null, exceptionLabelResolver, null, null, null);
result = (Map<String, String>) getCustomResolvedLabels.invoke(quotaCheckReactiveFilter, exchange); result = (Map<String, String>) getCustomResolvedLabels.invoke(quotaCheckReactiveFilter, exchange);

@ -39,14 +39,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 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;
@ -69,7 +71,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"
}) })
@ -84,8 +87,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"));
@ -95,14 +98,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);
@ -240,6 +243,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();

@ -33,6 +33,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;

@ -62,15 +62,16 @@ 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.assertj.core.api.AssertionsForClassTypes;
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.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.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -80,11 +81,14 @@ import static org.mockito.Mockito.when;
* *
* @author lepdou 2022-05-26 * @author lepdou 2022-05-26
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class PolarisLoadBalancerCompositeRuleTest { public class PolarisLoadBalancerCompositeRuleTest {
private static final AtomicBoolean initTransitiveMetadata = new AtomicBoolean(false); private static final AtomicBoolean initTransitiveMetadata = new AtomicBoolean(false);
private final List<RouterRequestInterceptor> requestInterceptors = new ArrayList<>(); private final List<RouterRequestInterceptor> requestInterceptors = new ArrayList<>();
private final String testNamespace = "testNamespace";
private final String testCallerService = "testCallerService";
private final String testCalleeService = "testCalleeService";
@Mock @Mock
private PolarisLoadBalancerProperties polarisLoadBalancerProperties; private PolarisLoadBalancerProperties polarisLoadBalancerProperties;
@Mock @Mock
@ -96,12 +100,9 @@ public class PolarisLoadBalancerCompositeRuleTest {
@Mock @Mock
private RouterAPI routerAPI; private RouterAPI routerAPI;
private IClientConfig config; private IClientConfig config;
private String testNamespace = "testNamespace";
private String testCallerService = "testCallerService";
private String testCalleeService = "testCalleeService";
@Before @BeforeEach
public void before() { void setUp() {
config = new DefaultClientConfigImpl(); config = new DefaultClientConfigImpl();
config.loadDefaultValues(); config.loadDefaultValues();
requestInterceptors.add(new MetadataRouterRequestInterceptor(polarisMetadataRouterProperties)); requestInterceptors.add(new MetadataRouterRequestInterceptor(polarisMetadataRouterProperties));
@ -117,7 +118,7 @@ public class PolarisLoadBalancerCompositeRuleTest {
AbstractLoadBalancerRule defaultRule = compositeRule.getRule(); AbstractLoadBalancerRule defaultRule = compositeRule.getRule();
Assert.assertNull(defaultRule); assertThat(defaultRule).isNull();
} }
@Test @Test
@ -128,7 +129,7 @@ public class PolarisLoadBalancerCompositeRuleTest {
AbstractLoadBalancerRule lbRule = compositeRule.getRule(); AbstractLoadBalancerRule lbRule = compositeRule.getRule();
Assert.assertTrue(lbRule instanceof RandomRule); assertThat(lbRule).isInstanceOf(RandomRule.class);
} }
@Test @Test
@ -139,7 +140,7 @@ public class PolarisLoadBalancerCompositeRuleTest {
AbstractLoadBalancerRule lbRule = compositeRule.getRule(); AbstractLoadBalancerRule lbRule = compositeRule.getRule();
Assert.assertTrue(lbRule instanceof PolarisWeightedRule); assertThat(lbRule).isInstanceOf(PolarisWeightedRule.class);
} }
@Test @Test
@ -150,7 +151,7 @@ public class PolarisLoadBalancerCompositeRuleTest {
AbstractLoadBalancerRule lbRule = compositeRule.getRule(); AbstractLoadBalancerRule lbRule = compositeRule.getRule();
Assert.assertTrue(lbRule instanceof RetryRule); assertThat(lbRule).isInstanceOf(RetryRule.class);
} }
@Test @Test
@ -161,7 +162,7 @@ public class PolarisLoadBalancerCompositeRuleTest {
AbstractLoadBalancerRule lbRule = compositeRule.getRule(); AbstractLoadBalancerRule lbRule = compositeRule.getRule();
Assert.assertTrue(lbRule instanceof WeightedResponseTimeRule); assertThat(lbRule).isInstanceOf(WeightedResponseTimeRule.class);
} }
@Test @Test
@ -172,7 +173,7 @@ public class PolarisLoadBalancerCompositeRuleTest {
AbstractLoadBalancerRule lbRule = compositeRule.getRule(); AbstractLoadBalancerRule lbRule = compositeRule.getRule();
Assert.assertTrue(lbRule instanceof BestAvailableRule); assertThat(lbRule).isInstanceOf(BestAvailableRule.class);
} }
@Test @Test
@ -183,7 +184,7 @@ public class PolarisLoadBalancerCompositeRuleTest {
AbstractLoadBalancerRule lbRule = compositeRule.getRule(); AbstractLoadBalancerRule lbRule = compositeRule.getRule();
Assert.assertTrue(lbRule instanceof RoundRobinRule); assertThat(lbRule).isInstanceOf(RoundRobinRule.class);
} }
@Test @Test
@ -194,7 +195,7 @@ public class PolarisLoadBalancerCompositeRuleTest {
AbstractLoadBalancerRule lbRule = compositeRule.getRule(); AbstractLoadBalancerRule lbRule = compositeRule.getRule();
Assert.assertTrue(lbRule instanceof AvailabilityFilteringRule); assertThat(lbRule).isInstanceOf(AvailabilityFilteringRule.class);
} }
@Test @Test
@ -224,13 +225,15 @@ public class PolarisLoadBalancerCompositeRuleTest {
Set<RouteArgument> routerMetadata = request.getRouterArguments(MetadataRouter.ROUTER_TYPE_METADATA); Set<RouteArgument> routerMetadata = request.getRouterArguments(MetadataRouter.ROUTER_TYPE_METADATA);
Assert.assertEquals(1, routerMetadata.size()); AssertionsForClassTypes.assertThat(routerMetadata.size()).isEqualTo(1);
Assert.assertEquals(0, request.getRouterArguments(NearbyRouter.ROUTER_TYPE_NEAR_BY).size()); AssertionsForClassTypes.assertThat(request.getRouterArguments(NearbyRouter.ROUTER_TYPE_NEAR_BY).size())
Assert.assertEquals(1, request.getRouterArguments(RuleBasedRouter.ROUTER_TYPE_RULE_BASED).size()); .isEqualTo(0);
AssertionsForClassTypes.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()); AssertionsForClassTypes.assertThat(routeArgument.getKey()).isEqualTo(RuleBasedRouter.ROUTER_ENABLED);
Assert.assertEquals("false", routeArgument.getValue()); AssertionsForClassTypes.assertThat(routeArgument.getValue()).isEqualTo("false");
} }
} }
} }
@ -257,19 +260,21 @@ public class PolarisLoadBalancerCompositeRuleTest {
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()); AssertionsForClassTypes.assertThat(request.getRouterArguments(MetadataRouter.ROUTER_TYPE_METADATA).size())
Assert.assertEquals(1, routerMetadata.size()); .isEqualTo(0);
AssertionsForClassTypes.assertThat(routerMetadata.size()).isEqualTo(1);
for (RouteArgument routeArgument : routerMetadata) { for (RouteArgument routeArgument : routerMetadata) {
Assert.assertEquals(NearbyRouter.ROUTER_ENABLED, routeArgument.getKey()); AssertionsForClassTypes.assertThat(routeArgument.getKey()).isEqualTo(RuleBasedRouter.ROUTER_ENABLED);
Assert.assertEquals("true", routeArgument.getValue()); AssertionsForClassTypes.assertThat(routeArgument.getValue()).isEqualTo("true");
} }
Assert.assertEquals(1, request.getRouterArguments(RuleBasedRouter.ROUTER_TYPE_RULE_BASED).size()); AssertionsForClassTypes.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()); AssertionsForClassTypes.assertThat(routeArgument.getKey()).isEqualTo(RuleBasedRouter.ROUTER_ENABLED);
Assert.assertEquals("false", routeArgument.getValue()); AssertionsForClassTypes.assertThat(routeArgument.getValue()).isEqualTo("false");
} }
} }
} }
@ -296,9 +301,11 @@ public class PolarisLoadBalancerCompositeRuleTest {
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()); AssertionsForClassTypes.assertThat(routerMetadata.size()).isEqualTo(3);
Assert.assertEquals(0, request.getRouterArguments(MetadataRouter.ROUTER_TYPE_METADATA).size()); AssertionsForClassTypes.assertThat(request.getRouterArguments(MetadataRouter.ROUTER_TYPE_METADATA).size())
Assert.assertEquals(0, request.getRouterArguments(NearbyRouter.ROUTER_TYPE_NEAR_BY).size()); .isEqualTo(0);
AssertionsForClassTypes.assertThat(request.getRouterArguments(NearbyRouter.ROUTER_TYPE_NEAR_BY).size())
.isEqualTo(0);
} }
} }
@ -321,7 +328,7 @@ public class PolarisLoadBalancerCompositeRuleTest {
List<Server> servers = compositeRule.doRouter(assembleServers(), assembleRouterContext()); List<Server> servers = compositeRule.doRouter(assembleServers(), assembleRouterContext());
Assert.assertEquals(assembleResponse.getServiceInstances().getInstances().size(), servers.size()); assertThat(servers.size()).isEqualTo(assembleResponse.getServiceInstances().getInstances().size());
} }
} }

@ -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");
} }
} }

@ -24,16 +24,16 @@ 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;
/** /**
@ -41,7 +41,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 RouterRuleLabelResolverTest { public class RouterRuleLabelResolverTest {
private final String testNamespace = "testNamespace"; private final String testNamespace = "testNamespace";
@ -73,7 +73,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 +83,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);
} }
} }

@ -13,27 +13,26 @@
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the * CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License. * specific language governing permissions and limitations under the License.
*
*/ */
package com.tencent.cloud.polaris.router.resttemplate; package com.tencent.cloud.polaris.router.beanprocessor;
import com.tencent.cloud.common.util.BeanFactoryUtils; import com.tencent.cloud.common.util.BeanFactoryUtils;
import com.tencent.cloud.polaris.router.beanprocessor.LoadBalancerInterceptorBeanPostProcessor; import com.tencent.cloud.polaris.router.resttemplate.PolarisLoadBalancerInterceptor;
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.client.loadbalancer.LoadBalancerClient; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor; import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor;
import org.springframework.cloud.client.loadbalancer.LoadBalancerRequestFactory; import org.springframework.cloud.client.loadbalancer.LoadBalancerRequestFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
/** /**
@ -41,8 +40,8 @@ import static org.mockito.Mockito.when;
* *
* @author lepdou 2022-05-26 * @author lepdou 2022-05-26
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class PolarisLoadBalancerBeanPostProcessorTest { public class LoadBalancerInterceptorBeanPostProcessorTest {
@Mock @Mock
private LoadBalancerClient loadBalancerClient; private LoadBalancerClient loadBalancerClient;
@ -66,7 +65,7 @@ public class PolarisLoadBalancerBeanPostProcessorTest {
Object bean = processor.postProcessBeforeInitialization(loadBalancerInterceptor, ""); Object bean = processor.postProcessBeforeInitialization(loadBalancerInterceptor, "");
Assert.assertTrue(bean instanceof PolarisLoadBalancerInterceptor); assertThat(bean).isInstanceOf(PolarisLoadBalancerInterceptor.class);
} }
} }
@ -77,8 +76,8 @@ public class PolarisLoadBalancerBeanPostProcessorTest {
OtherBean otherBean = new OtherBean(); OtherBean otherBean = new OtherBean();
Object bean = processor.postProcessBeforeInitialization(otherBean, ""); Object bean = processor.postProcessBeforeInitialization(otherBean, "");
Assert.assertFalse(bean instanceof PolarisLoadBalancerInterceptor); assertThat(bean).isNotInstanceOf(PolarisLoadBalancerInterceptor.class);
Assert.assertTrue(bean instanceof OtherBean); assertThat(bean).isInstanceOf(OtherBean.class);
} }
static class OtherBean { static class OtherBean {

@ -36,8 +36,7 @@ import com.tencent.cloud.polaris.router.spi.RouterRequestInterceptor;
import com.tencent.polaris.client.api.SDKContext; import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.router.api.core.RouterAPI; import com.tencent.polaris.router.api.core.RouterAPI;
import com.tencent.polaris.router.client.api.DefaultRouterAPI; import com.tencent.polaris.router.client.api.DefaultRouterAPI;
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.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
@ -49,7 +48,8 @@ import org.springframework.cloud.netflix.ribbon.RibbonClients;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory; import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
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.util.CollectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
/** /**
* Test for {@link PolarisLoadBalancerCompositeRuleBeanPostProcessor}. * Test for {@link PolarisLoadBalancerCompositeRuleBeanPostProcessor}.
@ -74,12 +74,12 @@ public class PolarisLoadBalancerCompositeRuleBeanPostProcessorTest {
SpringClientFactory springClientFactory = context.getBean(SpringClientFactory.class); SpringClientFactory springClientFactory = context.getBean(SpringClientFactory.class);
IRule rule = springClientFactory.getInstance(SERVICE_1, IRule.class); IRule rule = springClientFactory.getInstance(SERVICE_1, IRule.class);
Assert.assertTrue(rule instanceof PolarisLoadBalancerCompositeRule); assertThat(rule).isInstanceOf(PolarisLoadBalancerCompositeRule.class);
List<RouterRequestInterceptor> requestInterceptors = (List<RouterRequestInterceptor>) ReflectionUtils.getFieldValue(rule, "requestInterceptors"); List<RouterRequestInterceptor> requestInterceptors = (List<RouterRequestInterceptor>) ReflectionUtils.getFieldValue(rule, "requestInterceptors");
Assert.assertFalse(CollectionUtils.isEmpty(requestInterceptors)); assertThat(requestInterceptors).isNotEmpty();
AbstractLoadBalancerRule delegateRule = ((PolarisLoadBalancerCompositeRule) rule).getDelegateRule(); AbstractLoadBalancerRule delegateRule = ((PolarisLoadBalancerCompositeRule) rule).getDelegateRule();
//ZoneAvoidanceRule default //ZoneAvoidanceRule default
Assert.assertTrue(delegateRule instanceof ZoneAvoidanceRule); assertThat(delegateRule).isInstanceOf(ZoneAvoidanceRule.class);
}); });
} }
@ -92,10 +92,10 @@ public class PolarisLoadBalancerCompositeRuleBeanPostProcessorTest {
SpringClientFactory springClientFactory = context.getBean(SpringClientFactory.class); SpringClientFactory springClientFactory = context.getBean(SpringClientFactory.class);
IRule rule = springClientFactory.getInstance(SERVICE_1, IRule.class); IRule rule = springClientFactory.getInstance(SERVICE_1, IRule.class);
Assert.assertTrue(rule instanceof PolarisLoadBalancerCompositeRule); assertThat(rule).isInstanceOf(PolarisLoadBalancerCompositeRule.class);
AbstractLoadBalancerRule delegateRule = ((PolarisLoadBalancerCompositeRule) rule).getDelegateRule(); AbstractLoadBalancerRule delegateRule = ((PolarisLoadBalancerCompositeRule) rule).getDelegateRule();
//spring.cloud.polaris.loadbalancer.strategy = random //spring.cloud.polaris.loadbalancer.strategy = random
Assert.assertTrue(delegateRule instanceof RandomRule); assertThat(delegateRule).isInstanceOf(RandomRule.class);
}); });
} }
@ -108,17 +108,17 @@ public class PolarisLoadBalancerCompositeRuleBeanPostProcessorTest {
SpringClientFactory springClientFactory = context.getBean(SpringClientFactory.class); SpringClientFactory springClientFactory = context.getBean(SpringClientFactory.class);
IRule rule1 = springClientFactory.getInstance(SERVICE_1, IRule.class); IRule rule1 = springClientFactory.getInstance(SERVICE_1, IRule.class);
Assert.assertTrue(rule1 instanceof PolarisLoadBalancerCompositeRule); assertThat(rule1).isInstanceOf(PolarisLoadBalancerCompositeRule.class);
AbstractLoadBalancerRule delegateRule1 = ((PolarisLoadBalancerCompositeRule) rule1).getDelegateRule(); AbstractLoadBalancerRule delegateRule1 = ((PolarisLoadBalancerCompositeRule) rule1).getDelegateRule();
//service1.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RoundRobinRule //service1.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RoundRobinRule
Assert.assertTrue(delegateRule1 instanceof RoundRobinRule); assertThat(delegateRule1).isInstanceOf(RoundRobinRule.class);
IRule rule2 = springClientFactory.getInstance(SERVICE_2, IRule.class); IRule rule2 = springClientFactory.getInstance(SERVICE_2, IRule.class);
Assert.assertTrue(rule2 instanceof PolarisLoadBalancerCompositeRule); assertThat(rule2).isInstanceOf(PolarisLoadBalancerCompositeRule.class);
AbstractLoadBalancerRule delegateRule2 = ((PolarisLoadBalancerCompositeRule) rule2).getDelegateRule(); AbstractLoadBalancerRule delegateRule2 = ((PolarisLoadBalancerCompositeRule) rule2).getDelegateRule();
//ZoneAvoidanceRule default //ZoneAvoidanceRule default
Assert.assertTrue(delegateRule2 instanceof ZoneAvoidanceRule); assertThat(delegateRule2).isInstanceOf(ZoneAvoidanceRule.class);
}); });
} }
@ -130,16 +130,16 @@ public class PolarisLoadBalancerCompositeRuleBeanPostProcessorTest {
SpringClientFactory springClientFactory = context.getBean(SpringClientFactory.class); SpringClientFactory springClientFactory = context.getBean(SpringClientFactory.class);
IRule rule1 = springClientFactory.getInstance(SERVICE_1, IRule.class); IRule rule1 = springClientFactory.getInstance(SERVICE_1, IRule.class);
Assert.assertTrue(rule1 instanceof PolarisLoadBalancerCompositeRule); assertThat(rule1).isInstanceOf(PolarisLoadBalancerCompositeRule.class);
AbstractLoadBalancerRule delegateRule1 = ((PolarisLoadBalancerCompositeRule) rule1).getDelegateRule(); AbstractLoadBalancerRule delegateRule1 = ((PolarisLoadBalancerCompositeRule) rule1).getDelegateRule();
//RibbonConfigForService1#loadBalancerRule returns BestAvailableRule //RibbonConfigForService1#loadBalancerRule returns BestAvailableRule
Assert.assertTrue(delegateRule1 instanceof BestAvailableRule); assertThat(delegateRule1).isInstanceOf(BestAvailableRule.class);
IRule rule2 = springClientFactory.getInstance(SERVICE_2, IRule.class); IRule rule2 = springClientFactory.getInstance(SERVICE_2, IRule.class);
Assert.assertTrue(rule2 instanceof PolarisLoadBalancerCompositeRule); assertThat(rule2).isInstanceOf(PolarisLoadBalancerCompositeRule.class);
AbstractLoadBalancerRule delegateRule2 = ((PolarisLoadBalancerCompositeRule) rule2).getDelegateRule(); AbstractLoadBalancerRule delegateRule2 = ((PolarisLoadBalancerCompositeRule) rule2).getDelegateRule();
//ZoneAvoidanceRule default //ZoneAvoidanceRule default
Assert.assertTrue(delegateRule2 instanceof ZoneAvoidanceRule); assertThat(delegateRule2).isInstanceOf(ZoneAvoidanceRule.class);
}); });
} }

@ -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;
@ -45,7 +45,7 @@ import static org.mockito.Mockito.when;
* Test for {@link PolarisRouterEndpoint}. * Test for {@link PolarisRouterEndpoint}.
* @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";
@ -56,15 +56,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();
} }
@ -91,27 +91,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);
} }
} }

@ -20,17 +20,17 @@ package com.tencent.cloud.polaris.router.feign;
import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.DefaultClientConfigImpl;
import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.ILoadBalancer;
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.cloud.netflix.ribbon.DefaultServerIntrospector; import org.springframework.cloud.netflix.ribbon.DefaultServerIntrospector;
import org.springframework.cloud.netflix.ribbon.ServerIntrospector; import org.springframework.cloud.netflix.ribbon.ServerIntrospector;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory; import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.cloud.openfeign.ribbon.FeignLoadBalancer; import org.springframework.cloud.openfeign.ribbon.FeignLoadBalancer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -40,7 +40,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 PolarisCachingSpringLoadBalanceFactoryTest { public class PolarisCachingSpringLoadBalanceFactoryTest {
private final String service1 = "service1"; private final String service1 = "service1";
@ -74,30 +74,30 @@ public class PolarisCachingSpringLoadBalanceFactoryTest {
// load balancer for service1 // load balancer for service1
FeignLoadBalancer feignLoadBalancer = polarisCachingSpringLoadBalanceFactory.create(service1); FeignLoadBalancer feignLoadBalancer = polarisCachingSpringLoadBalanceFactory.create(service1);
Assert.assertNotNull(feignLoadBalancer); assertThat(feignLoadBalancer).isNotNull();
verify(factory).getClientConfig(service1); verify(factory).getClientConfig(service1);
verify(factory, times(0)).getClientConfig(service2); verify(factory, times(0)).getClientConfig(service2);
verify(factory).getLoadBalancer(service1); verify(factory).getLoadBalancer(service1);
verify(factory, times(0)).getLoadBalancer(service2); verify(factory, times(0)).getLoadBalancer(service2);
verify(factory).getInstance(service1, ServerIntrospector.class); verify(factory).getInstance(service1, ServerIntrospector.class);
verify(factory, times(0)).getInstance(service2, ServerIntrospector.class); verify(factory, times(0)).getInstance(service2, ServerIntrospector.class);
Assert.assertEquals(loadBalancer, feignLoadBalancer.getLoadBalancer()); assertThat(feignLoadBalancer.getLoadBalancer()).isEqualTo(loadBalancer);
Assert.assertEquals(service1, feignLoadBalancer.getClientName()); assertThat(feignLoadBalancer.getClientName()).isEqualTo(service1);
// load balancer for service2 // load balancer for service2
FeignLoadBalancer feignLoadBalancer2 = polarisCachingSpringLoadBalanceFactory.create(service2); FeignLoadBalancer feignLoadBalancer2 = polarisCachingSpringLoadBalanceFactory.create(service2);
// load balancer for service1 again // load balancer for service1 again
feignLoadBalancer = polarisCachingSpringLoadBalanceFactory.create(service1); feignLoadBalancer = polarisCachingSpringLoadBalanceFactory.create(service1);
Assert.assertNotNull(feignLoadBalancer); assertThat(feignLoadBalancer2).isNotNull();
verify(factory).getClientConfig(service1); verify(factory).getClientConfig(service1);
verify(factory).getClientConfig(service2); verify(factory).getClientConfig(service2);
verify(factory).getLoadBalancer(service1); verify(factory).getLoadBalancer(service1);
verify(factory).getLoadBalancer(service2); verify(factory).getLoadBalancer(service2);
verify(factory).getInstance(service1, ServerIntrospector.class); verify(factory).getInstance(service1, ServerIntrospector.class);
verify(factory).getInstance(service2, ServerIntrospector.class); verify(factory).getInstance(service2, ServerIntrospector.class);
Assert.assertEquals(loadBalancer, feignLoadBalancer2.getLoadBalancer()); assertThat(feignLoadBalancer2.getLoadBalancer()).isEqualTo(loadBalancer);
Assert.assertEquals(service2, feignLoadBalancer2.getClientName()); assertThat(feignLoadBalancer2.getClientName()).isEqualTo(service2);
} }
} }

@ -32,16 +32,16 @@ import com.tencent.cloud.common.metadata.MetadataContextHolder;
import com.tencent.cloud.common.util.ApplicationContextAwareUtils; import com.tencent.cloud.common.util.ApplicationContextAwareUtils;
import com.tencent.cloud.common.util.JacksonUtils; import com.tencent.cloud.common.util.JacksonUtils;
import com.tencent.cloud.polaris.router.PolarisRouterContext; import com.tencent.cloud.polaris.router.PolarisRouterContext;
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.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.cloud.netflix.ribbon.DefaultServerIntrospector; import org.springframework.cloud.netflix.ribbon.DefaultServerIntrospector;
import org.springframework.cloud.netflix.ribbon.ServerIntrospector; import org.springframework.cloud.netflix.ribbon.ServerIntrospector;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.anyString;
/** /**
@ -49,7 +49,7 @@ import static org.mockito.Mockito.anyString;
* *
* @author lepdou 2022-05-26 * @author lepdou 2022-05-26
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class PolarisFeignLoadBalancerTest { public class PolarisFeignLoadBalancerTest {
@Test @Test
@ -83,12 +83,12 @@ public class PolarisFeignLoadBalancerTest {
PolarisRouterContext routerContext = polarisFeignLoadBalancer.buildRouterContext(headers); PolarisRouterContext routerContext = polarisFeignLoadBalancer.buildRouterContext(headers);
Assert.assertNotNull(routerContext); assertThat(routerContext).isNotNull();
Map<String, String> routerLabels = routerContext.getLabels(RouterConstant.ROUTER_LABELS); Map<String, String> routerLabels = routerContext.getLabels(RouterConstant.ROUTER_LABELS);
Assert.assertNotNull(routerLabels); assertThat(routerLabels).isNotNull();
Assert.assertEquals("v1", routerLabels.get("k1")); assertThat(routerLabels.get("k1")).isEqualTo("v1");
Assert.assertEquals("v2", routerLabels.get("k2")); assertThat(routerLabels.get("k2")).isEqualTo("v2");
Assert.assertNull(routerLabels.get("k3")); assertThat(routerLabels.get("k3")).isNull();
} }
} }
} }
@ -114,8 +114,7 @@ public class PolarisFeignLoadBalancerTest {
mockedMetadataContextHolder.when(MetadataContextHolder::get).thenReturn(metadataContext); mockedMetadataContextHolder.when(MetadataContextHolder::get).thenReturn(metadataContext);
PolarisRouterContext routerContext = polarisFeignLoadBalancer.buildRouterContext(headers); PolarisRouterContext routerContext = polarisFeignLoadBalancer.buildRouterContext(headers);
assertThat(routerContext).isNull();
Assert.assertNull(routerContext);
} }
} }
} }

@ -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;
@ -55,7 +54,7 @@ import static org.mockito.Mockito.when;
* *
* @author lepdou, cheese8 * @author lepdou, cheese8
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class RouterLabelFeignInterceptorTest { public class RouterLabelFeignInterceptorTest {
@Mock @Mock
@ -124,16 +123,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("");
} }
} }
} }

@ -31,14 +31,12 @@ import com.tencent.cloud.common.metadata.MetadataContextHolder;
import com.tencent.cloud.common.util.ApplicationContextAwareUtils; import com.tencent.cloud.common.util.ApplicationContextAwareUtils;
import com.tencent.cloud.common.util.JacksonUtils; import com.tencent.cloud.common.util.JacksonUtils;
import com.tencent.cloud.polaris.router.PolarisRouterContext; import com.tencent.cloud.polaris.router.PolarisRouterContext;
import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test;
import org.junit.Assert; 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.cloud.client.ServiceInstance; import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
@ -53,6 +51,7 @@ import org.springframework.http.client.ClientHttpResponse;
import org.springframework.mock.http.client.MockClientHttpResponse; import org.springframework.mock.http.client.MockClientHttpResponse;
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.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;
@ -64,7 +63,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 PolarisLoadBalancerInterceptorTest { public class PolarisLoadBalancerInterceptorTest {
@Mock @Mock
@ -116,7 +115,7 @@ public class PolarisLoadBalancerInterceptorTest {
catch (UnsupportedEncodingException e) { catch (UnsupportedEncodingException e) {
throw new RuntimeException("unsupported charset exception " + UTF_8); throw new RuntimeException("unsupported charset exception " + UTF_8);
} }
Assertions.assertThat(mockedResponse.getHeaders().get(RouterConstant.ROUTER_LABELS).get(0)) assertThat(mockedResponse.getHeaders().get(RouterConstant.ROUTER_LABELS).get(0))
.isEqualTo(encodedLabelsContent); .isEqualTo(encodedLabelsContent);
} }
} }
@ -139,7 +138,7 @@ public class PolarisLoadBalancerInterceptorTest {
ClientHttpResponse response = polarisLoadBalancerInterceptor.intercept(request, null, null); ClientHttpResponse response = polarisLoadBalancerInterceptor.intercept(request, null, null);
Assert.assertEquals(mockedResponse, response); assertThat(response).isEqualTo(mockedResponse);
verify(loadBalancerRequestFactory).createRequest(request, null, null); verify(loadBalancerRequestFactory).createRequest(request, null, null);
verify(notRibbonLoadBalancerClient).execute(calleeService, loadBalancerRequest); verify(notRibbonLoadBalancerClient).execute(calleeService, loadBalancerRequest);
@ -155,7 +154,7 @@ public class PolarisLoadBalancerInterceptorTest {
static class MockedHttpRequest implements HttpRequest { static class MockedHttpRequest implements HttpRequest {
private URI uri; private final URI uri;
MockedHttpRequest(String url) { MockedHttpRequest(String url) {
this.uri = URI.create(url); this.uri = URI.create(url);

@ -18,7 +18,7 @@
package com.tencent.cloud.polaris.router.resttemplate; package com.tencent.cloud.polaris.router.resttemplate;
import java.net.URI; import java.net.URI;
import java.util.Arrays; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map; import java.util.Map;
@ -33,18 +33,18 @@ import com.tencent.cloud.polaris.context.config.PolarisContextProperties;
import com.tencent.cloud.polaris.router.PolarisRouterContext; import com.tencent.cloud.polaris.router.PolarisRouterContext;
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.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.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod; import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest; import org.springframework.http.HttpRequest;
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.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -54,7 +54,7 @@ import static org.mockito.Mockito.when;
* *
* @author lepdou 2022-10-09 * @author lepdou 2022-10-09
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class RouterContextFactoryTest { public class RouterContextFactoryTest {
@Mock @Mock
@ -105,7 +105,7 @@ public class RouterContextFactoryTest {
try (MockedStatic<MetadataContextHolder> mockedMetadataContextHolder = Mockito.mockStatic(MetadataContextHolder.class)) { try (MockedStatic<MetadataContextHolder> mockedMetadataContextHolder = Mockito.mockStatic(MetadataContextHolder.class)) {
mockedMetadataContextHolder.when(MetadataContextHolder::get).thenReturn(metadataContext); mockedMetadataContextHolder.when(MetadataContextHolder::get).thenReturn(metadataContext);
RouterContextFactory routerContextFactory = new RouterContextFactory(Arrays.asList(springWebRouterLabelResolver), RouterContextFactory routerContextFactory = new RouterContextFactory(Collections.singletonList(springWebRouterLabelResolver),
staticMetadataManager, routerRuleLabelResolver, polarisContextProperties); staticMetadataManager, routerRuleLabelResolver, polarisContextProperties);
PolarisRouterContext routerContext = routerContextFactory.create(request, null, calleeService); PolarisRouterContext routerContext = routerContextFactory.create(request, null, calleeService);
@ -114,22 +114,22 @@ public class RouterContextFactoryTest {
verify(routerRuleLabelResolver).getExpressionLabelKeys(callerService, callerService, calleeService); verify(routerRuleLabelResolver).getExpressionLabelKeys(callerService, callerService, calleeService);
verify(springWebRouterLabelResolver).resolve(request, null, expressionKeys); verify(springWebRouterLabelResolver).resolve(request, null, expressionKeys);
Assert.assertEquals("v1", routerContext.getLabels(RouterConstant.TRANSITIVE_LABELS).get("k1")); assertThat(routerContext.getLabels(RouterConstant.TRANSITIVE_LABELS).get("k1")).isEqualTo("v1");
Assert.assertEquals("v22", routerContext.getLabels(RouterConstant.TRANSITIVE_LABELS).get("k2")); assertThat(routerContext.getLabels(RouterConstant.TRANSITIVE_LABELS).get("k2")).isEqualTo("v22");
Assert.assertEquals("v1", routerContext.getLabels(RouterConstant.ROUTER_LABELS).get("k1")); assertThat(routerContext.getLabels(RouterConstant.ROUTER_LABELS).get("k1")).isEqualTo("v1");
Assert.assertEquals("v22", routerContext.getLabels(RouterConstant.ROUTER_LABELS).get("k2")); assertThat(routerContext.getLabels(RouterConstant.ROUTER_LABELS).get("k2")).isEqualTo("v22");
Assert.assertEquals("v4", routerContext.getLabels(RouterConstant.ROUTER_LABELS).get("k4")); assertThat(routerContext.getLabels(RouterConstant.ROUTER_LABELS).get("k4")).isEqualTo("v4");
Assert.assertEquals("GET", routerContext.getLabels(RouterConstant.ROUTER_LABELS) assertThat(routerContext.getLabels(RouterConstant.ROUTER_LABELS)
.get("${http.method}")); .get("${http.method}")).isEqualTo("GET");
Assert.assertEquals("/user/get", routerContext.getLabels(RouterConstant.ROUTER_LABELS) assertThat(routerContext.getLabels(RouterConstant.ROUTER_LABELS)
.get("${http.uri}")); .get("${http.uri}")).isEqualTo("/user/get");
} }
} }
} }
static class MockedHttpRequest implements HttpRequest { static class MockedHttpRequest implements HttpRequest {
private URI uri; private final URI uri;
MockedHttpRequest(String url) { MockedHttpRequest(String url) {
this.uri = URI.create(url); this.uri = URI.create(url);

@ -34,15 +34,14 @@ import com.tencent.cloud.polaris.context.config.PolarisContextProperties;
import com.tencent.cloud.polaris.router.PolarisRouterContext; import com.tencent.cloud.polaris.router.PolarisRouterContext;
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.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.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.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.gateway.config.LoadBalancerProperties; import org.springframework.cloud.gateway.config.LoadBalancerProperties;
@ -50,6 +49,7 @@ import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
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 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.Mockito.mock; import static org.mockito.Mockito.mock;
@ -61,9 +61,9 @@ import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.G
/** /**
* test for ${@link PolarisLoadBalancerClientFilter}. * test for ${@link PolarisLoadBalancerClientFilter}.
* *
* @author lepdou 2022-06-13 * @author lepdou 2022-07-04
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class PolarisLoadBalancerClientFilterTest { public class PolarisLoadBalancerClientFilterTest {
private static final String callerService = "callerService"; private static final String callerService = "callerService";
@ -83,8 +83,8 @@ public class PolarisLoadBalancerClientFilterTest {
@Mock @Mock
private PolarisContextProperties polarisContextProperties; private PolarisContextProperties polarisContextProperties;
@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(callerService); .thenReturn(callerService);
@ -101,8 +101,8 @@ public class PolarisLoadBalancerClientFilterTest {
mockedMetadataContextHolder.when(MetadataContextHolder::get).thenReturn(metadataContext); mockedMetadataContextHolder.when(MetadataContextHolder::get).thenReturn(metadataContext);
} }
@AfterClass @AfterAll
public static void afterClass() { static void afterAll() {
mockedApplicationContextAwareUtils.close(); mockedApplicationContextAwareUtils.close();
mockedMetadataContextHolder.close(); mockedMetadataContextHolder.close();
} }
@ -111,13 +111,13 @@ public class PolarisLoadBalancerClientFilterTest {
public void testGenRouterContext() { public void testGenRouterContext() {
PolarisLoadBalancerClientFilter polarisLoadBalancerClientFilter = new PolarisLoadBalancerClientFilter( PolarisLoadBalancerClientFilter polarisLoadBalancerClientFilter = new PolarisLoadBalancerClientFilter(
loadBalancerClient, loadBalancerProperties, staticMetadataManager, routerRuleLabelResolver, loadBalancerClient, loadBalancerProperties, staticMetadataManager, routerRuleLabelResolver,
Lists.newArrayList(routerLabelResolver), polarisContextProperties); com.google.common.collect.Lists.newArrayList(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 = com.google.common.collect.Sets.newHashSet("${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")
@ -133,11 +133,11 @@ public class PolarisLoadBalancerClientFilterTest {
PolarisRouterContext routerContext = polarisLoadBalancerClientFilter.genRouterContext(webExchange, calleeService); PolarisRouterContext routerContext = polarisLoadBalancerClientFilter.genRouterContext(webExchange, calleeService);
Map<String, String> routerLabels = routerContext.getLabels(RouterConstant.ROUTER_LABELS); Map<String, String> routerLabels = routerContext.getLabels(RouterConstant.ROUTER_LABELS);
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

@ -39,15 +39,14 @@ import com.tencent.cloud.polaris.router.PolarisRouterContext;
import com.tencent.cloud.polaris.router.RouterRuleLabelResolver; import com.tencent.cloud.polaris.router.RouterRuleLabelResolver;
import com.tencent.cloud.polaris.router.spi.ServletRouterLabelResolver; import com.tencent.cloud.polaris.router.spi.ServletRouterLabelResolver;
import okhttp3.OkHttpClient; import okhttp3.OkHttpClient;
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.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.cloud.netflix.ribbon.apache.RibbonLoadBalancingHttpClient; import org.springframework.cloud.netflix.ribbon.apache.RibbonLoadBalancingHttpClient;
import org.springframework.cloud.netflix.ribbon.okhttp.OkHttpLoadBalancingClient; import org.springframework.cloud.netflix.ribbon.okhttp.OkHttpLoadBalancingClient;
@ -61,6 +60,7 @@ import org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRib
import org.springframework.cloud.netflix.zuul.filters.route.okhttp.OkHttpRibbonCommand; import org.springframework.cloud.netflix.zuul.filters.route.okhttp.OkHttpRibbonCommand;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
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.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
@ -74,7 +74,7 @@ import static org.springframework.cloud.netflix.zuul.filters.support.FilterConst
* *
* @author jarvisxiong 2022-08-09 * @author jarvisxiong 2022-08-09
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class PolarisRibbonRoutingFilterTest { public class PolarisRibbonRoutingFilterTest {
private static final String callerService = "callerService"; private static final String callerService = "callerService";
@ -96,8 +96,8 @@ public class PolarisRibbonRoutingFilterTest {
@Mock @Mock
private PolarisLoadBalancer polarisLoadBalancer; private PolarisLoadBalancer polarisLoadBalancer;
@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(callerService); .thenReturn(callerService);
@ -114,8 +114,8 @@ public class PolarisRibbonRoutingFilterTest {
mockedMetadataContextHolder.when(MetadataContextHolder::get).thenReturn(metadataContext); mockedMetadataContextHolder.when(MetadataContextHolder::get).thenReturn(metadataContext);
} }
@AfterClass @AfterAll
public static void afterClass() { static void afterAll() {
mockedApplicationContextAwareUtils.close(); mockedApplicationContextAwareUtils.close();
mockedMetadataContextHolder.close(); mockedMetadataContextHolder.close();
} }
@ -146,11 +146,11 @@ public class PolarisRibbonRoutingFilterTest {
PolarisRouterContext routerContext = polarisRibbonRoutingFilter.genRouterContext(request, calleeService); PolarisRouterContext routerContext = polarisRibbonRoutingFilter.genRouterContext(request, calleeService);
Map<String, String> routerLabels = routerContext.getLabels(RouterConstant.ROUTER_LABELS); Map<String, String> routerLabels = routerContext.getLabels(RouterConstant.ROUTER_LABELS);
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

@ -108,7 +108,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,34 +26,31 @@ 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() {
@ -69,20 +66,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
@ -98,21 +95,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
@ -131,53 +128,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.assertEquals("zone2", metadataManager.getZone()); assertThat(metadataManager.getAllEnvMetadata()).isEmpty();
Assert.assertEquals("region1", metadataManager.getRegion()); assertThat(metadataManager.getEnvTransitiveMetadata()).isEmpty();
Assert.assertTrue(CollectionUtils.isEmpty(metadataManager.getAllEnvMetadata())); assertThat(metadataManager.getZone()).isEqualTo("zone2");
Assert.assertTrue(CollectionUtils.isEmpty(metadataManager.getEnvTransitiveMetadata())); 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, cheese8 * @author lepdou 2022-05-27, cheese8
*/ */
@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,7 +73,7 @@
<revision>1.11.1-Hoxton.SR12-SNAPSHOT</revision> <revision>1.11.1-Hoxton.SR12-SNAPSHOT</revision>
<!-- Dependencies --> <!-- Dependencies -->
<polaris.version>1.10.5</polaris.version> <polaris.version>1.12.0</polaris.version>
<guava.version>31.0.1-jre</guava.version> <guava.version>31.0.1-jre</guava.version>
<logback.version>1.2.11</logback.version> <logback.version>1.2.11</logback.version>
<mocktio.version>4.5.1</mocktio.version> <mocktio.version>4.5.1</mocktio.version>
@ -81,7 +81,7 @@
<jackson.version>2.12.7</jackson.version> <jackson.version>2.12.7</jackson.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 -->
<maven-javadoc-plugin.verison>3.3.0</maven-javadoc-plugin.verison> <maven-javadoc-plugin.verison>3.3.0</maven-javadoc-plugin.verison>
@ -272,8 +272,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,17 +29,18 @@ 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 2022-07-12 * @author lepdou 2022-07-12
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class FeatureEnvRouterRequestInterceptorTest { public class FeatureEnvRouterRequestInterceptorTest {
@Test @Test
@ -58,8 +59,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
@ -79,8 +80,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
@ -99,7 +100,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

@ -32,21 +32,20 @@ import com.tencent.cloud.plugin.gateway.staining.rule.RuleTrafficStainer;
import com.tencent.cloud.plugin.gateway.staining.rule.StainingRuleManager; import com.tencent.cloud.plugin.gateway.staining.rule.StainingRuleManager;
import com.tencent.polaris.configuration.api.core.ConfigFile; import com.tencent.polaris.configuration.api.core.ConfigFile;
import com.tencent.polaris.configuration.api.core.ConfigFileService; import com.tencent.polaris.configuration.api.core.ConfigFileService;
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.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Mono; import reactor.core.publisher.Mono;
import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GatewayFilterChain;
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 org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -55,9 +54,12 @@ import static org.mockito.Mockito.when;
* Test for {@link TrafficStainingGatewayFilter}. * Test for {@link TrafficStainingGatewayFilter}.
* @author lepdou 2022-07-12 * @author lepdou 2022-07-12
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class TrafficStainingGatewayFilterTest { public class TrafficStainingGatewayFilterTest {
private final String testNamespace = "testNamespace";
private final String testGroup = "testGroup";
private final String testFileName = "rule.json";
@Mock @Mock
private GatewayFilterChain chain; private GatewayFilterChain chain;
@Mock @Mock
@ -65,12 +67,8 @@ public class TrafficStainingGatewayFilterTest {
@Mock @Mock
private ConfigFileService configFileService; private ConfigFileService configFileService;
private final String testNamespace = "testNamespace"; @BeforeAll
private final String testGroup = "testGroup"; static void beforeAll() {
private final String testFileName = "rule.json";
@BeforeClass
public static void before() {
Mockito.mockStatic(ApplicationContextAwareUtils.class); Mockito.mockStatic(ApplicationContextAwareUtils.class);
when(ApplicationContextAwareUtils when(ApplicationContextAwareUtils
.getProperties(any())).thenReturn("fooBar"); .getProperties(any())).thenReturn("fooBar");
@ -108,10 +106,10 @@ public class TrafficStainingGatewayFilterTest {
TrafficStainingGatewayFilter filter = new TrafficStainingGatewayFilter(Arrays.asList(trafficStainer1, trafficStainer2)); TrafficStainingGatewayFilter filter = new TrafficStainingGatewayFilter(Arrays.asList(trafficStainer1, trafficStainer2));
Map<String, String> result = filter.getStainedLabels(exchange); Map<String, String> result = filter.getStainedLabels(exchange);
Assert.assertFalse(CollectionUtils.isEmpty(result)); assertThat(result).isNotEmpty();
Assert.assertEquals("v1", result.get("k1")); assertThat(result.get("k1")).isEqualTo("v1");
Assert.assertEquals("v2", result.get("k2")); assertThat(result.get("k2")).isEqualTo("v2");
Assert.assertEquals("v3", result.get("k3")); assertThat(result.get("k3")).isEqualTo("v3");
} }
@Test @Test
@ -122,7 +120,7 @@ public class TrafficStainingGatewayFilterTest {
TrafficStainingGatewayFilter filter = new TrafficStainingGatewayFilter(null); TrafficStainingGatewayFilter filter = new TrafficStainingGatewayFilter(null);
filter.filter(exchange, chain); filter.filter(exchange, chain);
Map<String, String> map = metadataContext.getTransitiveMetadata(); Map<String, String> map = metadataContext.getTransitiveMetadata();
Assert.assertTrue(CollectionUtils.isEmpty(map)); assertThat(map).isEmpty();
} }
@Test @Test
@ -169,8 +167,8 @@ public class TrafficStainingGatewayFilterTest {
filter.filter(exchange, chain); filter.filter(exchange, chain);
Map<String, String> map = metadataContext.getTransitiveMetadata(); Map<String, String> map = metadataContext.getTransitiveMetadata();
Assert.assertNotNull(map); assertThat(map).isNotNull();
Assert.assertEquals(1, map.size()); assertThat(map.size()).isEqualTo(1);
Assert.assertEquals("blue", map.get("env")); assertThat(map.get("env")).isEqualTo("blue");
} }
} }

@ -25,20 +25,20 @@ import java.util.Map;
import com.tencent.cloud.common.rule.Condition; import com.tencent.cloud.common.rule.Condition;
import com.tencent.cloud.common.rule.KVPair; import com.tencent.cloud.common.rule.KVPair;
import com.tencent.cloud.common.rule.Operation; import com.tencent.cloud.common.rule.Operation;
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.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 static org.assertj.core.api.Assertions.assertThat;
/** /**
* Test for {@link RuleStainingExecutor}. * Test for {@link RuleStainingExecutor}.
* @author lepdou 2022-07-12 * @author lepdou 2022-07-12
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class RuleStainingExecutorTest { public class RuleStainingExecutorTest {
@Test @Test
@ -73,9 +73,9 @@ public class RuleStainingExecutorTest {
Map<String, String> stainedLabels = executor.execute(exchange, stainingRule); Map<String, String> stainedLabels = executor.execute(exchange, stainingRule);
Assert.assertNotNull(stainedLabels); assertThat(stainedLabels).isNotNull();
Assert.assertEquals(1, stainedLabels.size()); assertThat(stainedLabels.size()).isEqualTo(1);
Assert.assertEquals("blue", stainedLabels.get("env")); assertThat(stainedLabels.get("env")).isEqualTo("blue");
} }
@Test @Test
@ -110,8 +110,8 @@ public class RuleStainingExecutorTest {
Map<String, String> stainedLabels = executor.execute(exchange, stainingRule); Map<String, String> stainedLabels = executor.execute(exchange, stainingRule);
Assert.assertNotNull(stainedLabels); assertThat(stainedLabels).isNotNull();
Assert.assertEquals(0, stainedLabels.size()); assertThat(stainedLabels.size()).isEqualTo(0);
} }
@Test @Test
@ -173,17 +173,17 @@ public class RuleStainingExecutorTest {
Map<String, String> stainedLabels = executor.execute(exchange, stainingRule); Map<String, String> stainedLabels = executor.execute(exchange, stainingRule);
Assert.assertNotNull(stainedLabels); assertThat(stainedLabels).isNotNull();
Assert.assertEquals(3, stainedLabels.size()); assertThat(stainedLabels.size()).isEqualTo(3);
Assert.assertEquals("blue", stainedLabels.get("env")); assertThat(stainedLabels.get("env")).isEqualTo("blue");
Assert.assertEquals("value1", stainedLabels.get("label1")); assertThat(stainedLabels.get("label1")).isEqualTo("value1");
Assert.assertEquals("value2", stainedLabels.get("label2")); assertThat(stainedLabels.get("label2")).isEqualTo("value2");
} }
@Test @Test
public void testNoStainingRule() { public void testNoStainingRule() {
RuleStainingExecutor executor = new RuleStainingExecutor(); RuleStainingExecutor executor = new RuleStainingExecutor();
Assert.assertTrue(CollectionUtils.isEmpty(executor.execute(null, null))); assertThat(executor.execute(null, null)).isEmpty();
Assert.assertTrue(CollectionUtils.isEmpty(executor.execute(null, new StainingRule()))); assertThat(executor.execute(null, new StainingRule())).isEmpty();
} }
} }

@ -22,32 +22,30 @@ import java.util.Map;
import com.tencent.polaris.configuration.api.core.ConfigFile; import com.tencent.polaris.configuration.api.core.ConfigFile;
import com.tencent.polaris.configuration.api.core.ConfigFileService; import com.tencent.polaris.configuration.api.core.ConfigFileService;
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.Mockito; import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.jupiter.MockitoExtension;
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 static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
/** /**
* Test for {@link RuleTrafficStainer}. * Test for {@link RuleTrafficStainer}.
* @author derek.yi 2022-11-03 * @author derek.yi 2022-11-03
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class RuleTrafficStainerTest { public class RuleTrafficStainerTest {
@Mock
private ConfigFileService configFileService;
private final String testNamespace = "testNamespace"; private final String testNamespace = "testNamespace";
private final String testGroup = "testGroup"; private final String testGroup = "testGroup";
private final String testFileName = "rule.json"; private final String testFileName = "rule.json";
@Mock
private ConfigFileService configFileService;
@Test @Test
public void testNoStainingRule() { public void testNoStainingRule() {
@ -64,7 +62,7 @@ public class RuleTrafficStainerTest {
RuleStainingExecutor ruleStainingExecutor = new RuleStainingExecutor(); RuleStainingExecutor ruleStainingExecutor = new RuleStainingExecutor();
RuleTrafficStainer ruleTrafficStainer = new RuleTrafficStainer(stainingRuleManager, ruleStainingExecutor); RuleTrafficStainer ruleTrafficStainer = new RuleTrafficStainer(stainingRuleManager, ruleStainingExecutor);
Map<String, String> map = ruleTrafficStainer.apply(null); Map<String, String> map = ruleTrafficStainer.apply(null);
Assert.assertTrue(CollectionUtils.isEmpty(map)); assertThat(map).isEmpty();
} }
@Test @Test
@ -105,8 +103,8 @@ public class RuleTrafficStainerTest {
MockServerWebExchange exchange = new MockServerWebExchange.Builder(request).build(); MockServerWebExchange exchange = new MockServerWebExchange.Builder(request).build();
Map<String, String> map = ruleTrafficStainer.apply(exchange); Map<String, String> map = ruleTrafficStainer.apply(exchange);
Assert.assertNotNull(map); assertThat(map).isNotNull();
Assert.assertEquals(1, map.size()); assertThat(map.size()).isEqualTo(1);
Assert.assertEquals("blue", map.get("env")); assertThat(map.get("env")).isEqualTo("blue");
} }
} }

@ -20,29 +20,28 @@ package com.tencent.cloud.plugin.gateway.staining.rule;
import com.tencent.polaris.configuration.api.core.ConfigFile; import com.tencent.polaris.configuration.api.core.ConfigFile;
import com.tencent.polaris.configuration.api.core.ConfigFileService; import com.tencent.polaris.configuration.api.core.ConfigFileService;
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.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.assertj.core.api.Assertions.assertThatCode;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
/** /**
* Test for {@link StainingRuleManager}. * Test for {@link StainingRuleManager}.
* @author lepdou 2022-07-12 * @author lepdou 2022-07-12
*/ */
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class StainingRuleManagerTest { public class StainingRuleManagerTest {
@Mock
private ConfigFileService configFileService;
private final String testNamespace = "testNamespace"; private final String testNamespace = "testNamespace";
private final String testGroup = "testGroup"; private final String testGroup = "testGroup";
private final String testFileName = "rule.json"; private final String testFileName = "rule.json";
@Mock
private ConfigFileService configFileService;
@Test @Test
public void testNormalRule() { public void testNormalRule() {
@ -77,15 +76,16 @@ public class StainingRuleManagerTest {
StainingRule stainingRule = stainingRuleManager.getStainingRule(); StainingRule stainingRule = stainingRuleManager.getStainingRule();
Assert.assertNotNull(stainingRule); assertThat(stainingRule).isNotNull();
Assert.assertEquals(1, stainingRule.getRules().size()); assertThat(stainingRule.getRules().size()).isEqualTo(1);
StainingRule.Rule rule = stainingRule.getRules().get(0); StainingRule.Rule rule = stainingRule.getRules().get(0);
Assert.assertEquals(1, rule.getConditions().size()); assertThat(rule.getConditions().size()).isEqualTo(1);
Assert.assertEquals(1, rule.getLabels().size()); assertThat(rule.getLabels().size()).isEqualTo(1);
} }
@Test(expected = RuntimeException.class) @Test
public void testWrongRule() { public void testWrongRule() {
assertThatCode(() -> {
RuleStainingProperties ruleStainingProperties = new RuleStainingProperties(); RuleStainingProperties ruleStainingProperties = new RuleStainingProperties();
ruleStainingProperties.setNamespace(testNamespace); ruleStainingProperties.setNamespace(testNamespace);
ruleStainingProperties.setGroup(testGroup); ruleStainingProperties.setGroup(testGroup);
@ -114,6 +114,7 @@ public class StainingRuleManagerTest {
when(configFileService.getConfigFile(testNamespace, testGroup, testFileName)).thenReturn(configFile); when(configFileService.getConfigFile(testNamespace, testGroup, testFileName)).thenReturn(configFile);
new StainingRuleManager(ruleStainingProperties, configFileService); new StainingRuleManager(ruleStainingProperties, configFileService);
}).isInstanceOf(RuntimeException.class);
} }
@Test @Test
@ -128,6 +129,6 @@ public class StainingRuleManagerTest {
when(configFileService.getConfigFile(testNamespace, testGroup, testFileName)).thenReturn(configFile); when(configFileService.getConfigFile(testNamespace, testGroup, testFileName)).thenReturn(configFile);
StainingRuleManager stainingRuleManager = new StainingRuleManager(ruleStainingProperties, configFileService); StainingRuleManager stainingRuleManager = new StainingRuleManager(ruleStainingProperties, configFileService);
Assert.assertNull(stainingRuleManager.getStainingRule()); assertThat(stainingRuleManager.getStainingRule()).isNull();
} }
} }

@ -16,6 +16,7 @@
<dependency> <dependency>
<groupId>com.tencent.polaris</groupId> <groupId>com.tencent.polaris</groupId>
<artifactId>stat-pushgateway</artifactId> <artifactId>stat-pushgateway</artifactId>
<version>1.10.5</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.tencent.cloud</groupId> <groupId>com.tencent.cloud</groupId>

@ -18,7 +18,8 @@
package com.tencent.cloud.plugin.pushgateway; package com.tencent.cloud.plugin.pushgateway;
import org.junit.Test; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
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;
@ -34,7 +35,9 @@ import static org.assertj.core.api.Assertions.assertThat;
public class PolarisStatPushGatewayAutoConfigurationTest { public class PolarisStatPushGatewayAutoConfigurationTest {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(PolarisStatPushGatewayAutoConfiguration.class)); .withConfiguration(AutoConfigurations.of(
PolarisContextAutoConfiguration.class,
PolarisStatPushGatewayAutoConfiguration.class));
@Test @Test
public void testDefaultInitialization() { public void testDefaultInitialization() {

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

Loading…
Cancel
Save