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.EncodeTransferMedataRestTemplateInterceptor;
import com.tencent.cloud.metadata.core.EncodeTransferMetadataZuulFilter;
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.test.context.runner.ApplicationContextRunner;
@ -39,6 +37,8 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test for {@link MetadataTransferAutoConfiguration}.
*
@ -53,25 +53,14 @@ public class MetadataTransferAutoConfigurationTest {
*/
@Test
public void test1() {
this.applicationContextRunner
.withConfiguration(
AutoConfigurations.of(MetadataTransferAutoConfiguration.class))
this.applicationContextRunner.withConfiguration(AutoConfigurations.of(MetadataTransferAutoConfiguration.class))
.run(context -> {
Assertions.assertThat(context).hasSingleBean(
MetadataTransferAutoConfiguration.MetadataTransferFeignInterceptorConfig.class);
Assertions.assertThat(context)
.hasSingleBean(EncodeTransferMedataFeignInterceptor.class);
Assertions.assertThat(context).hasSingleBean(
MetadataTransferAutoConfiguration.MetadataTransferRestTemplateConfig.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);
assertThat(context).hasSingleBean(MetadataTransferAutoConfiguration.MetadataTransferFeignInterceptorConfig.class);
assertThat(context).hasSingleBean(EncodeTransferMedataFeignInterceptor.class);
assertThat(context).hasSingleBean(MetadataTransferAutoConfiguration.MetadataTransferRestTemplateConfig.class);
assertThat(context).hasSingleBean(EncodeTransferMedataRestTemplateInterceptor.class);
assertThat(context).hasSingleBean(MetadataTransferAutoConfiguration.MetadataTransferScgFilterConfig.class);
assertThat(context).hasSingleBean(GlobalFilter.class);
});
}
@ -82,20 +71,19 @@ public class MetadataTransferAutoConfigurationTest {
.withConfiguration(
AutoConfigurations.of(MetadataTransferAutoConfiguration.class, RestTemplateConfiguration.class))
.run(context -> {
Assertions.assertThat(context)
.hasSingleBean(EncodeTransferMedataFeignInterceptor.class);
assertThat(context).hasSingleBean(EncodeTransferMedataFeignInterceptor.class);
EncodeTransferMedataRestTemplateInterceptor encodeTransferMedataRestTemplateInterceptor = context.getBean(EncodeTransferMedataRestTemplateInterceptor.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")) {
RestTemplate restTemplate = restTemplateMap.get(beanName);
Assertions.assertThat(restTemplate).isNotNull();
assertThat(restTemplate).isNotNull();
List<ClientHttpRequestInterceptor> encodeTransferMedataFeignInterceptorList = restTemplate.getInterceptors()
.stream()
.filter(interceptor -> Objects.equals(interceptor, encodeTransferMedataRestTemplateInterceptor))
.collect(Collectors.toList());
//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 org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test for {@link CustomTransitiveMetadataResolver}.
*
@ -39,8 +40,8 @@ public class CustomTransitiveMetadataResolverTest {
builder.header("X-SCT-Metadata-Transitive-a", "test");
MockServerWebExchange exchange = MockServerWebExchange.from(builder);
Map<String, String> resolve = CustomTransitiveMetadataResolver.resolve(exchange);
Assertions.assertThat(resolve.size()).isEqualTo(1);
Assertions.assertThat(resolve.get("a")).isEqualTo("test");
assertThat(resolve.size()).isEqualTo(1);
assertThat(resolve.get("a")).isEqualTo("test");
}
@Test
@ -49,8 +50,8 @@ public class CustomTransitiveMetadataResolverTest {
builder.header("X-Polaris-Metadata-Transitive-a", "test");
MockServerWebExchange exchange = MockServerWebExchange.from(builder);
Map<String, String> resolve = CustomTransitiveMetadataResolver.resolve(exchange);
Assertions.assertThat(resolve.size()).isEqualTo(1);
Assertions.assertThat(resolve.get("a")).isEqualTo("test");
assertThat(resolve.size()).isEqualTo(1);
assertThat(resolve.get("a")).isEqualTo("test");
}
@Test
@ -58,8 +59,8 @@ public class CustomTransitiveMetadataResolverTest {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("X-SCT-Metadata-Transitive-a", "test");
Map<String, String> resolve = CustomTransitiveMetadataResolver.resolve(request);
Assertions.assertThat(resolve.size()).isEqualTo(1);
Assertions.assertThat(resolve.get("a")).isEqualTo("test");
assertThat(resolve.size()).isEqualTo(1);
assertThat(resolve.get("a")).isEqualTo("test");
}
@Test
@ -67,7 +68,7 @@ public class CustomTransitiveMetadataResolverTest {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("X-Polaris-Metadata-Transitive-a", "test");
Map<String, String> resolve = CustomTransitiveMetadataResolver.resolve(request);
Assertions.assertThat(resolve.size()).isEqualTo(1);
Assertions.assertThat(resolve.get("a")).isEqualTo("test");
assertThat(resolve.size()).isEqualTo(1);
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.metadata.config.MetadataLocalProperties;
import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import reactor.core.publisher.Mono;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
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.WebFilterChain;
import static org.assertj.core.api.Assertions.assertThat;
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
*/
@RunWith(SpringRunner.class)
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = MOCK,
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 {
@Autowired
@ -51,14 +51,14 @@ public class DecodeTransferMetadataReactiveFilterTest {
private DecodeTransferMetadataReactiveFilter metadataReactiveFilter;
@Before
@BeforeEach
public void setUp() {
this.metadataReactiveFilter = new DecodeTransferMetadataReactiveFilter();
}
@Test
public void test1() {
Assertions.assertThat(this.metadataReactiveFilter.getOrder())
assertThat(this.metadataReactiveFilter.getOrder())
.isEqualTo(MetadataConstant.OrderConstant.WEB_FILTER_ORDER);
}
@ -74,10 +74,8 @@ public class DecodeTransferMetadataReactiveFilterTest {
ServerWebExchange exchange = MockServerWebExchange.from(request);
metadataReactiveFilter.filter(exchange, webFilterChain);
Assertions.assertThat(metadataLocalProperties.getContent().get("a"))
.isEqualTo("1");
Assertions.assertThat(metadataLocalProperties.getContent().get("b"))
.isEqualTo("2");
Assertions.assertThat(metadataLocalProperties.getContent().get("c")).isNull();
assertThat(metadataLocalProperties.getContent().get("a")).isEqualTo("1");
assertThat(metadataLocalProperties.getContent().get("b")).isEqualTo("2");
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.metadata.config.MetadataLocalProperties;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockHttpServletRequest;
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;
/**
@ -42,12 +42,12 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
*
* @author Haotian Zhang
*/
@RunWith(SpringRunner.class)
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = RANDOM_PORT,
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.cloud.gateway.enabled = false" })
"spring.cloud.gateway.enabled = false"})
public class DecodeTransferMetadataServletFilterTest {
@Autowired
@ -68,9 +68,9 @@ public class DecodeTransferMetadataServletFilterTest {
request.addHeader(MetadataConstant.HeaderName.CUSTOM_METADATA, "{\"c\": \"3\"}");
MockHttpServletResponse response = new MockHttpServletResponse();
metadataServletFilter.doFilter(request, response, filterChain);
Assertions.assertThat(metadataLocalProperties.getContent().get("a")).isEqualTo("1");
Assertions.assertThat(metadataLocalProperties.getContent().get("b")).isEqualTo("2");
Assertions.assertThat(metadataLocalProperties.getContent().get("c")).isNull();
assertThat(metadataLocalProperties.getContent().get("a")).isEqualTo("1");
assertThat(metadataLocalProperties.getContent().get("b")).isEqualTo("2");
assertThat(metadataLocalProperties.getContent().get("c")).isNull();
}
@SpringBootApplication

@ -17,17 +17,14 @@
package com.tencent.cloud.metadata.core;
import java.io.UnsupportedEncodingException;
import com.tencent.cloud.common.constant.MetadataConstant;
import com.tencent.cloud.common.metadata.MetadataContext;
import com.tencent.cloud.common.metadata.MetadataContextHolder;
import com.tencent.cloud.common.metadata.config.MetadataLocalProperties;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
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.FeignClient;
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.RestController;
import static org.assertj.core.api.Assertions.assertThat;
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
*/
@RunWith(SpringRunner.class)
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = DEFINED_PORT,
classes = EncodeTransferMedataFeignInterceptorTest.TestApplication.class,
properties = {"server.port=8081",
@ -64,9 +62,9 @@ public class EncodeTransferMedataFeignInterceptorTest {
@Test
public void testTransitiveMetadataFromApplicationConfig() {
String metadata = testFeign.test();
Assertions.assertThat(metadata).isEqualTo("2");
Assertions.assertThat(metadataLocalProperties.getContent().get("a")).isEqualTo("1");
Assertions.assertThat(metadataLocalProperties.getContent().get("b")).isEqualTo("2");
assertThat(metadata).isEqualTo("2");
assertThat(metadataLocalProperties.getContent().get("a")).isEqualTo("1");
assertThat(metadataLocalProperties.getContent().get("b")).isEqualTo("2");
}
@SpringBootApplication
@ -75,7 +73,7 @@ public class EncodeTransferMedataFeignInterceptorTest {
protected static class TestApplication {
@RequestMapping("/test")
public String test() throws UnsupportedEncodingException {
public String test() {
return MetadataContextHolder.get().getContext(MetadataContext.FRAGMENT_TRANSITIVE, "b");
}
@ -91,8 +89,7 @@ public class EncodeTransferMedataFeignInterceptorTest {
@Override
public void apply(RequestTemplate template) {
template.header(MetadataConstant.HeaderName.CUSTOM_METADATA,
"{\"a\":\"11\",\"b\":\"22\",\"c\":\"33\"}");
template.header(MetadataConstant.HeaderName.CUSTOM_METADATA, "{\"a\":\"11\",\"b\":\"22\",\"c\":\"33\"}");
}
}
}

@ -17,13 +17,10 @@
package com.tencent.cloud.metadata.core;
import java.io.UnsupportedEncodingException;
import com.tencent.cloud.common.metadata.MetadataContext;
import com.tencent.cloud.common.metadata.MetadataContextHolder;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
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.HttpHeaders;
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.RestController;
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;
/**
@ -45,7 +43,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
*
* @author Haotian Zhang
*/
@RunWith(SpringRunner.class)
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = RANDOM_PORT,
classes = EncodeTransferMedataRestTemplateInterceptorTest.TestApplication.class,
properties = {"spring.config.location = classpath:application-test.yml",
@ -65,7 +63,7 @@ public class EncodeTransferMedataRestTemplateInterceptorTest {
String metadata = restTemplate
.exchange("http://localhost:" + localServerPort + "/test", HttpMethod.GET, httpEntity, String.class)
.getBody();
Assertions.assertThat(metadata).isEqualTo("2");
assertThat(metadata).isEqualTo("2");
}
@SpringBootApplication
@ -78,7 +76,7 @@ public class EncodeTransferMedataRestTemplateInterceptorTest {
}
@RequestMapping("/test")
public String test() throws UnsupportedEncodingException {
public String test() {
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.util.JacksonUtils;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
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.mock.http.server.reactive.MockServerHttpRequest;
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 org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* @author quan
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT,
classes = EncodeTransferMedataScgFilterTest.TestApplication.class,
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = EncodeTransferMedataScgFilterTest.TestApplication.class,
properties = {"spring.config.location = classpath:application-test.yml",
"spring.main.web-application-type = reactive"})
public class EncodeTransferMedataScgFilterTest {
@ -60,20 +59,14 @@ public class EncodeTransferMedataScgFilterTest {
@Test
public void testTransitiveMetadataFromApplicationConfig() throws UnsupportedEncodingException {
EncodeTransferMedataScgFilter filter = applicationContext.getBean(EncodeTransferMedataScgFilter.class);
// Mock Server Http Request
MockServerHttpRequest.BaseBuilder<?> builder = MockServerHttpRequest.get("");
MockServerWebExchange exchange = MockServerWebExchange.from(builder);
filter.filter(exchange, chain);
// Check metadata str
String metadata = exchange.getRequest().getHeaders().getFirst(MetadataConstant.HeaderName.CUSTOM_METADATA);
Assertions.assertThat(metadata).isNotNull();
String decode = URLDecoder.decode(metadata, UTF_8);
String metadataStr = exchange.getRequest().getHeaders().getFirst(MetadataConstant.HeaderName.CUSTOM_METADATA);
String decode = URLDecoder.decode(metadataStr, UTF_8);
Map<String, String> transitiveMap = JacksonUtils.deserialize2Map(decode);
Assertions.assertThat(transitiveMap.size()).isEqualTo(1);
Assertions.assertThat(transitiveMap.get("b")).isEqualTo("2");
assertThat(transitiveMap.size()).isEqualTo(1);
assertThat(transitiveMap.get("b")).isEqualTo("2");
}
@SpringBootApplication

@ -26,16 +26,16 @@ import com.netflix.zuul.context.RequestContext;
import com.tencent.cloud.common.constant.MetadataConstant;
import com.tencent.cloud.common.util.JacksonUtils;
import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
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 org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@ -45,7 +45,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
*
* @author quan
*/
@RunWith(SpringRunner.class)
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = RANDOM_PORT,
classes = EncodeTransferMetadataZuulFilterTest.TestApplication.class,
properties = {"spring.config.location = classpath:application-test.yml",
@ -56,8 +56,8 @@ public class EncodeTransferMetadataZuulFilterTest {
@Autowired
private ApplicationContext applicationContext;
@Before
public void init() {
@BeforeEach
void setUp() {
RequestContext ctx = RequestContext.getCurrentContext();
ctx.clear();
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.MetadataContextHolder;
import com.tencent.cloud.common.util.JacksonUtils;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
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;
/**
@ -40,13 +40,13 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
*
* @author lingxiao.wlx
*/
@RunWith(SpringRunner.class)
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = RANDOM_PORT,
classes = DecodeTransferMetadataServletFilterTest.TestApplication.class,
properties = {"spring.config.location = classpath:application-test.yml", "spring.main.web-application-type=reactive"})
public class TransHeadersTransferTest {
@AfterClass
public static void afterClass() {
@AfterAll
static void afterAll() {
MetadataContextHolder.remove();
}
@ -60,9 +60,9 @@ public class TransHeadersTransferTest {
request.addHeader("header3", "3");
TransHeadersTransfer.transfer(request);
Map<String, String> transHeadersKV = MetadataContextHolder.get().getTransHeadersKV();
Assertions.assertEquals(transHeadersKV.get("header1"), "1");
Assertions.assertEquals(transHeadersKV.get("header2"), "2");
Assertions.assertEquals(transHeadersKV.get("header3"), "3");
assertThat(transHeadersKV.get("header1")).isEqualTo("1");
assertThat(transHeadersKV.get("header2")).isEqualTo("2");
assertThat(transHeadersKV.get("header3")).isEqualTo("3");
}
@Test
@ -79,8 +79,8 @@ public class TransHeadersTransferTest {
MockServerHttpRequest request = builder.build();
TransHeadersTransfer.transfer(request);
Map<String, String> transHeadersKV = MetadataContextHolder.get().getTransHeadersKV();
Assertions.assertEquals(transHeadersKV.get("header1"), JacksonUtils.serialize2Json(header1));
Assertions.assertEquals(transHeadersKV.get("header2"), JacksonUtils.serialize2Json(header2));
Assertions.assertEquals(transHeadersKV.get("header3"), JacksonUtils.serialize2Json(header3));
assertThat(transHeadersKV.get("header1")).isEqualTo(JacksonUtils.serialize2Json(header1));
assertThat(transHeadersKV.get("header2")).isEqualTo(JacksonUtils.serialize2Json(header2));
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.rpc.enhancement.config.RpcEnhancementAutoConfiguration;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
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.rpc.enhancement.config.RpcEnhancementAutoConfiguration;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;

@ -19,6 +19,7 @@
package com.tencent.cloud.polaris.config.listener;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
@ -78,9 +79,9 @@ public final class PolarisConfigChangeEventListener implements ApplicationListen
ConfigurableEnvironment environment = context.getEnvironment();
Map<String, Object> ret = loadEnvironmentProperties(environment);
Map<String, ConfigPropertyChangeInfo> changes = merge(ret);
ConfigChangeSpringEvent configChangeSpringEvent = new ConfigChangeSpringEvent(Maps.newHashMap(changes));
ConfigChangeSpringEvent configChangeSpringEvent = new ConfigChangeSpringEvent(new HashMap<>(changes));
eventPublisher.publishEvent(configChangeSpringEvent);
fireConfigChange(changes.keySet(), Maps.newHashMap(changes));
fireConfigChange(changes.keySet(), new HashMap<>(changes));
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.polaris.configuration.api.core.ConfigFileService;
import com.tencent.polaris.configuration.api.core.ConfigKVFile;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
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.PropertySource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
/**
@ -45,7 +45,7 @@ import static org.mockito.Mockito.when;
*
* @author lepdou 2022-06-11
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class PolarisConfigFileLocatorTest {
private final String testNamespace = "testNamespace";
@ -89,9 +89,9 @@ public class PolarisConfigFileLocatorTest {
PropertySource<?> propertySource = locator.locate(environment);
Assert.assertEquals("v1", propertySource.getProperty("k1"));
Assert.assertEquals("v2", propertySource.getProperty("k2"));
Assert.assertEquals("v3", propertySource.getProperty("k3"));
assertThat(propertySource.getProperty("k1")).isEqualTo("v1");
assertThat(propertySource.getProperty("k2")).isEqualTo("v2");
assertThat(propertySource.getProperty("k3")).isEqualTo("v3");
}
@Test
@ -132,9 +132,9 @@ public class PolarisConfigFileLocatorTest {
PropertySource<?> propertySource = locator.locate(environment);
Assert.assertEquals("v11", propertySource.getProperty("k1"));
Assert.assertEquals("v2", propertySource.getProperty("k2"));
Assert.assertEquals("v3", propertySource.getProperty("k3"));
assertThat(propertySource.getProperty("k1")).isEqualTo("v11");
assertThat(propertySource.getProperty("k2")).isEqualTo("v2");
assertThat(propertySource.getProperty("k3")).isEqualTo("v3");
}
@Test
@ -181,8 +181,8 @@ public class PolarisConfigFileLocatorTest {
PropertySource<?> propertySource = locator.locate(environment);
Assert.assertEquals("v1", propertySource.getProperty("k1"));
Assert.assertEquals("v2", propertySource.getProperty("k2"));
Assert.assertEquals("v3", propertySource.getProperty("k3"));
assertThat(propertySource.getProperty("k1")).isEqualTo("v1");
assertThat(propertySource.getProperty("k2")).isEqualTo("v2");
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.ConfigKVFileChangeEvent;
import com.tencent.polaris.configuration.api.core.ConfigPropertyChangeInfo;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.TypeConverter;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ConfigurableApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@ -51,7 +51,7 @@ import static org.mockito.Mockito.when;
*
* @author lepdou 2022-06-11
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class PolarisPropertiesSourceAutoRefresherTest {
private final String testNamespace = "testNamespace";
@ -114,9 +114,9 @@ public class PolarisPropertiesSourceAutoRefresherTest {
file.fireChangeListener(event);
Assert.assertEquals("v11", polarisPropertySource.getProperty("k1"));
Assert.assertEquals("v3", polarisPropertySource.getProperty("k3"));
Assert.assertNull(polarisPropertySource.getProperty("k2"));
Assert.assertEquals("v4", polarisPropertySource.getProperty("k4"));
assertThat(polarisPropertySource.getProperty("k1")).isEqualTo("v11");
assertThat(polarisPropertySource.getProperty("k3")).isEqualTo("v3");
assertThat(polarisPropertySource.getProperty("k2")).isNull();
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.property.PlaceholderHelper;
import com.tencent.cloud.polaris.config.spring.property.SpringValueRegistry;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
@ -52,8 +52,8 @@ public class ConditionalOnReflectRefreshTypeTest {
private static ServerSocket serverSocket;
@BeforeClass
public static void before() {
@BeforeAll
static void beforeAll() {
new Thread(() -> {
try {
serverSocket = new ServerSocket(8093);
@ -65,8 +65,8 @@ public class ConditionalOnReflectRefreshTypeTest {
}).start();
}
@AfterClass
public static void after() throws IOException {
@AfterAll
static void afterAll() throws IOException {
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.PolarisPropertySourceManager;
import com.tencent.cloud.polaris.config.config.PolarisConfigProperties;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
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;
@ -39,7 +39,7 @@ import static org.mockito.Mockito.when;
*
* @author shuiqingliu
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class PolarisConfigEndpointTest {
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.polaris.configuration.api.core.ConfigPropertyChangeInfo;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
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.ConfigurableApplicationContext;
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;
@ -45,12 +45,12 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
*
* @author lepdou 2022-06-11
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = DEFINED_PORT,
classes = ConfigChangeListenerTest.TestApplication.class,
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = DEFINED_PORT, classes = ConfigChangeListenerTest.TestApplication.class,
properties = {"server.port=8081", "spring.config.location = classpath:application-test.yml"})
public class ConfigChangeListenerTest {
private static final CountDownLatch hits = new CountDownLatch(2);
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
@Autowired
@ -58,8 +58,6 @@ public class ConfigChangeListenerTest {
@Autowired
private TestApplication.TestConfig testConfig;
private static final CountDownLatch hits = new CountDownLatch(2);
@Test
public void test() throws InterruptedException {
//before change

@ -22,7 +22,6 @@ import java.io.IOException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.util.Collection;
import java.util.Objects;
import java.util.Optional;
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.SpringValueRegistry;
import com.tencent.polaris.api.utils.CollectionUtils;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanFactory;
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.stereotype.Component;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test for {@link SpringValueProcessor}.
*
@ -56,8 +56,8 @@ public class SpringValueProcessorTest {
private static ServerSocket serverSocket;
@BeforeClass
public static void before() {
@BeforeAll
static void beforeAll() {
new Thread(() -> {
try {
serverSocket = new ServerSocket(8093);
@ -69,8 +69,8 @@ public class SpringValueProcessorTest {
}).start();
}
@AfterClass
public static void after() throws IOException {
@AfterAll
static void afterAll() throws IOException {
serverSocket.close();
}
@ -91,19 +91,19 @@ public class SpringValueProcessorTest {
PolarisConfigAutoConfiguration polarisConfigAutoConfiguration = context.getBean(PolarisConfigAutoConfiguration.class);
BeanFactory beanFactory = polarisConfigAutoConfiguration.beanFactory;
Collection<SpringValue> timeout = springValueRegistry.get(beanFactory, "timeout");
Assert.assertFalse(CollectionUtils.isEmpty(timeout));
assertThat(CollectionUtils.isEmpty(timeout)).isFalse();
Optional<SpringValue> springValueOptional = timeout.stream().findAny();
Assert.assertTrue(springValueOptional.isPresent());
assertThat(springValueOptional.isPresent()).isTrue();
SpringValue springValue = springValueOptional.get();
Assert.assertEquals("${timeout:1000}", springValue.getPlaceholder());
Assert.assertTrue(springValue.isField());
Assert.assertTrue(Objects.nonNull(springValue.getField()));
Assert.assertEquals("timeout", springValue.getField().getName());
Assert.assertEquals(int.class, springValue.getTargetType());
assertThat(springValue.getPlaceholder()).isEqualTo("${timeout:1000}");
assertThat(springValue.isField()).isTrue();
assertThat(springValue.getField()).isNotNull();
assertThat(springValue.getField().getName()).isEqualTo("timeout");
assertThat(springValue.getTargetType()).isEqualTo(int.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);
BeanFactory beanFactory = polarisConfigAutoConfiguration.beanFactory;
Collection<SpringValue> name = springValueRegistry.get(beanFactory, "name");
Assert.assertFalse(CollectionUtils.isEmpty(name));
assertThat(name).isNotEmpty();
Optional<SpringValue> springValueOptional = name.stream().findAny();
Assert.assertTrue(springValueOptional.isPresent());
assertThat(springValueOptional.isPresent()).isTrue();
SpringValue springValue = springValueOptional.get();
Method method = springValue.getMethodParameter().getMethod();
Assert.assertTrue(Objects.nonNull(method));
Assert.assertEquals("setName", method.getName());
Assert.assertEquals("${name:1000}", springValue.getPlaceholder());
Assert.assertFalse(springValue.isField());
Assert.assertEquals(String.class, springValue.getTargetType());
assertThat(method).isNotNull();
assertThat(method.getName()).isEqualTo("setName");
assertThat(springValue.getPlaceholder()).isEqualTo("${name:1000}");
assertThat(springValue.isField()).isFalse();
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);
BeanFactory beanFactory = person.getBeanFactory();
Collection<SpringValue> name = springValueRegistry.get(beanFactory, "name");
Assert.assertFalse(CollectionUtils.isEmpty(name));
assertThat(name).isNotEmpty();
Optional<SpringValue> nameSpringValueOptional = name.stream().findAny();
Assert.assertTrue(nameSpringValueOptional.isPresent());
assertThat(nameSpringValueOptional.isPresent()).isTrue();
SpringValue nameSpringValue = nameSpringValueOptional.get();
Method method = nameSpringValue.getMethodParameter().getMethod();
Assert.assertTrue(Objects.nonNull(method));
Assert.assertEquals("setName", method.getName());
Assert.assertEquals("${name:test}", nameSpringValue.getPlaceholder());
Assert.assertFalse(nameSpringValue.isField());
Assert.assertEquals(String.class, nameSpringValue.getTargetType());
assertThat(method).isNotNull();
assertThat(method.getName()).isEqualTo("setName");
assertThat(nameSpringValue.getPlaceholder()).isEqualTo("${name:test}");
assertThat(nameSpringValue.isField()).isFalse();
assertThat(nameSpringValue.getTargetType()).isEqualTo(String.class);
Collection<SpringValue> age = springValueRegistry.get(beanFactory, "age");
Assert.assertFalse(CollectionUtils.isEmpty(age));
assertThat(age).isNotEmpty();
Optional<SpringValue> ageSpringValueOptional = age.stream().findAny();
Assert.assertTrue(ageSpringValueOptional.isPresent());
assertThat(ageSpringValueOptional.isPresent()).isTrue();
SpringValue ageSpringValue = ageSpringValueOptional.get();
Method method1 = ageSpringValue.getMethodParameter().getMethod();
Assert.assertTrue(Objects.nonNull(method1));
Assert.assertEquals("setAge", method1.getName());
Assert.assertEquals("${age:10}", ageSpringValue.getPlaceholder());
Assert.assertFalse(ageSpringValue.isField());
Assert.assertEquals(String.class, ageSpringValue.getTargetType());
assertThat(method1).isNotNull();
assertThat(method1.getName()).isEqualTo("setAge");
assertThat(ageSpringValue.getPlaceholder()).isEqualTo("${age:10}");
assertThat(ageSpringValue.isField()).isFalse();
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.ConfigPropertyChangeInfo;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test for {@link ConfigChangeSpringEvent}.
@ -42,9 +43,9 @@ import org.springframework.context.annotation.Configuration;
*/
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
public void testPublishConfigChangeSpringEvent() {
@ -55,7 +56,7 @@ public class ConfigChangeSpringEventTest {
changeMap.put("key", new ConfigPropertyChangeInfo("key", null, "value", ChangeType.ADDED));
context.publishEvent(new ConfigChangeSpringEvent(changeMap));
countDownLatch.await(5, TimeUnit.SECONDS);
Assert.assertEquals(1, receiveEventTimes.get());
assertThat(receiveEventTimes.get()).isEqualTo(1);
});
}
@ -65,13 +66,13 @@ public class ConfigChangeSpringEventTest {
@Override
public void onApplicationEvent(ConfigChangeSpringEvent event) {
Set<String> changedKeys = event.changedKeys();
Assert.assertEquals(1, changedKeys.size());
Assert.assertTrue(event.isChanged("key"));
assertThat(changedKeys.size()).isEqualTo(1);
assertThat(event.isChanged("key")).isTrue();
ConfigPropertyChangeInfo changeInfo = event.getChange("key");
Assert.assertNotNull(changeInfo);
Assert.assertEquals("key", changeInfo.getPropertyName());
Assert.assertEquals("value", changeInfo.getNewValue());
Assert.assertEquals(ChangeType.ADDED, changeInfo.getChangeType());
assertThat(changeInfo).isNotNull();
assertThat(changeInfo.getPropertyName()).isEqualTo("key");
assertThat(changeInfo.getNewValue()).isEqualTo("value");
assertThat(changeInfo.getChangeType()).isEqualTo(ChangeType.ADDED);
receiveEventTimes.incrementAndGet();
countDownLatch.countDown();

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

@ -36,6 +36,12 @@
<groupId>com.tencent.polaris</groupId>
<artifactId>polaris-test-mock-discovery</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 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.polaris.api.core.ConsumerAPI;
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.test.context.runner.ApplicationContextRunner;

@ -18,7 +18,7 @@
package com.tencent.cloud.polaris;
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.test.context.runner.ApplicationContextRunner;

@ -18,7 +18,8 @@
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.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.ProviderAPI;
import com.tencent.polaris.test.mock.discovery.NamingServer;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@ -55,13 +55,13 @@ public class PolarisDiscoveryAutoConfigurationTest {
.withPropertyValues("server.port=" + PORT)
.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);
}
@AfterClass
public static void afterClass() {
@AfterAll
static void afterAll() {
if (null != namingServer) {
namingServer.terminate();
}

@ -19,9 +19,9 @@ package com.tencent.cloud.polaris.discovery;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.polaris.test.mock.discovery.NamingServer;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@ -50,13 +50,13 @@ public class PolarisDiscoveryClientConfigurationTest {
.withPropertyValues("server.port=" + PORT)
.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);
}
@AfterClass
public static void afterClass() {
@AfterAll
static void afterAll() {
if (null != namingServer) {
namingServer.terminate();
}

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

@ -26,12 +26,12 @@ import com.tencent.polaris.api.pojo.DefaultServiceInstances;
import com.tencent.polaris.api.pojo.ServiceInfo;
import com.tencent.polaris.api.rpc.InstancesResponse;
import com.tencent.polaris.api.rpc.ServicesResponse;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.client.ServiceInstance;
@ -50,8 +50,7 @@ import static org.mockito.Mockito.when;
*
* @author Haotian Zhang
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class PolarisServiceDiscoveryTest {
@Mock
@ -59,8 +58,8 @@ public class PolarisServiceDiscoveryTest {
@InjectMocks
private PolarisServiceDiscovery polarisServiceDiscovery;
@Before
public void before() {
@BeforeEach
void setUp() {
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.discovery.PolarisDiscoveryClientConfiguration;
import com.tencent.polaris.test.mock.discovery.NamingServer;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@ -52,13 +52,14 @@ public class PolarisReactiveDiscoveryClientConfigurationTest {
.withPropertyValues("server.port=" + PORT)
.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);
}
@AfterClass
public static void afterClass() {
@AfterAll
static void afterAll() {
if (null != namingServer) {
namingServer.terminate();
}

@ -22,11 +22,11 @@ import java.util.Arrays;
import com.tencent.cloud.polaris.discovery.PolarisServiceDiscovery;
import com.tencent.polaris.api.exception.ErrorCode;
import com.tencent.polaris.api.exception.PolarisException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
@ -44,7 +44,7 @@ import static org.mockito.Mockito.when;
*
* @author Haotian Zhang
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class PolarisReactiveDiscoveryClientTest {
@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.ServicesByProto;
import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
@ -52,8 +52,9 @@ public class PolarisServiceStatusChangeListenerTest {
private ApplicationEventPublisher publisher;
@Before
public void setUp() {
@BeforeEach
void setUp() {
publisher = mock(ApplicationEventPublisher.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.PolarisDiscoveryHandler;
import com.tencent.polaris.test.mock.discovery.NamingServer;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Configuration;
import static com.tencent.polaris.test.common.Consts.NAMESPACE_TEST;
@ -58,17 +57,16 @@ public class PolarisDiscoveryEndpointTest {
.withPropertyValues("spring.application.name=" + SERVICE_PROVIDER)
.withPropertyValues("server.port=" + PORT)
.withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081")
.withPropertyValues(
"spring.cloud.polaris.discovery.namespace=" + NAMESPACE_TEST)
.withPropertyValues("spring.cloud.polaris.discovery.namespace=" + NAMESPACE_TEST)
.withPropertyValues("spring.cloud.polaris.discovery.token=xxxxxx");
@BeforeClass
public static void beforeClass() throws Exception {
@BeforeAll
static void beforeAll() throws Exception {
namingServer = NamingServer.startNamingServer(10081);
}
@AfterClass
public static void afterClass() throws Exception {
@AfterAll
static void afterAll() {
if (null != namingServer) {
namingServer.terminate();
}
@ -87,15 +85,12 @@ public class PolarisDiscoveryEndpointTest {
Map<String, Object> mapInfo = polarisDiscoveryEndpoint.polarisDiscovery("java_provider_test");
assertThat(polarisDiscoveryProperties).isEqualTo(mapInfo.get("PolarisDiscoveryProperties"));
});
}
@Configuration
@EnableAutoConfiguration
@EnableDiscoveryClient
static class PolarisPropertiesConfiguration {
}
}

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

@ -24,14 +24,14 @@ import java.util.Optional;
import com.tencent.polaris.api.config.plugin.DefaultPlugins;
import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.factory.config.global.ServerConnectorConfigImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
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 static org.assertj.core.api.Assertions.assertThat;
@ -41,7 +41,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author lingxiao.wlx
*/
@RunWith(SpringRunner.class)
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = NacosContextPropertiesTest.TestApplication.class)
@ActiveProfiles("test")
public class NacosContextPropertiesTest {
@ -74,7 +74,8 @@ public class NacosContextPropertiesTest {
assertThat(optionalServerConnectorConfig.isPresent()).isTrue();
ServerConnectorConfigImpl serverConnectorConfig = optionalServerConnectorConfig.get();
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();

@ -18,11 +18,13 @@
package com.tencent.cloud.polaris.registry;
import com.tencent.cloud.polaris.PolarisDiscoveryProperties;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
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.ServiceRegistry;
@ -31,7 +33,7 @@ import org.springframework.core.env.Environment;
import static com.tencent.polaris.test.common.Consts.SERVICE_PROVIDER;
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.nullable;
import static org.mockito.Mockito.doNothing;
@ -42,7 +44,8 @@ import static org.mockito.Mockito.doReturn;
*
* @author Haotian Zhang
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
public class PolarisAutoServiceRegistrationTest {
@Mock
@ -65,8 +68,8 @@ public class PolarisAutoServiceRegistrationTest {
private PolarisAutoServiceRegistration polarisAutoServiceRegistration;
@Before
public void setUp() {
@BeforeEach
void setUp() {
doReturn(polarisDiscoveryProperties).when(registration).getPolarisProperties();
doNothing().when(serviceRegistry).register(nullable(PolarisRegistration.class));
@ -81,20 +84,14 @@ public class PolarisAutoServiceRegistrationTest {
@Test
public void testRegister() {
doReturn(false).when(registration).isRegisterEnabled();
try {
assertThatCode(() -> {
polarisAutoServiceRegistration.register();
}
catch (Exception e) {
fail();
}
}).doesNotThrowAnyException();
doReturn(true).when(registration).isRegisterEnabled();
try {
assertThatCode(() -> {
polarisAutoServiceRegistration.register();
}
catch (Exception e) {
fail();
}
}).doesNotThrowAnyException();
}
@Test
@ -105,20 +102,14 @@ public class PolarisAutoServiceRegistrationTest {
@Test
public void testRegisterManagement() {
doReturn(false).when(registration).isRegisterEnabled();
try {
assertThatCode(() -> {
polarisAutoServiceRegistration.registerManagement();
}
catch (Exception e) {
fail();
}
}).doesNotThrowAnyException();
doReturn(true).when(registration).isRegisterEnabled();
try {
assertThatCode(() -> {
polarisAutoServiceRegistration.registerManagement();
}
catch (Exception e) {
fail();
}
}).doesNotThrowAnyException();
}
@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.GlobalConfig;
import com.tencent.polaris.client.api.SDKContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
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.server.WebServer;
@ -50,7 +52,8 @@ import static org.mockito.Mockito.when;
*
* @author Haotian Zhang
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
public class PolarisRegistrationTest {
private NacosContextProperties nacosContextProperties;
@ -59,8 +62,8 @@ public class PolarisRegistrationTest {
private PolarisRegistration polarisRegistration3;
@Before
public void setUp() {
@BeforeEach
void setUp() {
// mock PolarisDiscoveryProperties
PolarisDiscoveryProperties polarisDiscoveryProperties = mock(PolarisDiscoveryProperties.class);
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.PolarisDiscoveryClientConfiguration;
import com.tencent.polaris.test.mock.discovery.NamingServer;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@ -53,13 +53,13 @@ public class PolarisServiceRegistryAutoConfigurationTest {
.withPropertyValues("server.port=" + PORT)
.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);
}
@AfterClass
public static void afterClass() {
@AfterAll
static void afterAll() {
if (null != namingServer) {
namingServer.terminate();
}

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

@ -17,7 +17,7 @@
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.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.IClientConfig;
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.SpringBootApplication;

@ -17,6 +17,7 @@
package com.tencent.cloud.polaris.ribbon;
import java.io.IOException;
import java.util.List;
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.test.mock.discovery.NamingServer;
import com.tencent.polaris.test.mock.discovery.NamingService;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@ -69,23 +70,23 @@ public class PolarisServerListTest {
private IClientConfig iClientConfig;
@BeforeClass
public static void beforeClass() throws Exception {
@BeforeAll
static void beforeAll() throws IOException {
namingServer = NamingServer.startNamingServer(10081);
// add service
namingServer.getNamingService().addService(new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER));
}
@AfterClass
public static void afterClass() {
@AfterAll
static void afterAll() {
if (null != namingServer) {
namingServer.terminate();
}
}
@Before
public void setUp() {
@BeforeEach
void setUp() {
// mock IClientConfig
iClientConfig = mock(IClientConfig.class);
when(iClientConfig.getClientName()).thenReturn(SERVICE_PROVIDER);

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

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

@ -26,8 +26,8 @@ import java.util.Set;
import com.tencent.cloud.common.util.expresstion.ExpressionLabelUtils;
import com.tencent.cloud.polaris.context.ServiceRuleManager;
import com.tencent.polaris.client.pb.ModelProto;
import com.tencent.polaris.client.pb.RateLimitProto;
import com.tencent.polaris.specification.api.v1.model.ModelProto;
import com.tencent.polaris.specification.api.v1.traffic.manage.RateLimitProto;
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.polaris.context.ServiceRuleManager;
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.LoggerFactory;

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

@ -17,7 +17,8 @@
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.test.context.runner.ApplicationContextRunner;

@ -17,7 +17,7 @@
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.test.context.runner.ApplicationContextRunner;

@ -17,14 +17,14 @@
package com.tencent.cloud.polaris.ratelimit.config;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
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;
@ -33,7 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Haotian Zhang
*/
@RunWith(SpringRunner.class)
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = PolarisRateLimitPropertiesTest.TestApplication.class)
@ActiveProfiles("test")
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.test.mock.discovery.NamingServer;
import com.tencent.polaris.test.mock.discovery.NamingService;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
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.context.annotation.Bean;
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.RestClientException;
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.PORT;
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.Mockito.mock;
import static org.mockito.Mockito.when;
@ -54,7 +55,7 @@ import static org.mockito.Mockito.when;
*
* @author Haotian Zhang
*/
@RunWith(SpringRunner.class)
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = { CalleeControllerTests.Config.class, TestController.class },
properties = { "spring.application.name=java_provider_test",
@ -73,8 +74,8 @@ public class CalleeControllerTests {
@MockBean
private LimitAPI limitAPI;
@BeforeClass
public static void beforeClass() throws Exception {
@BeforeAll
static void beforeAll() throws Exception {
namingServer = NamingServer.startNamingServer(10081);
// add service with 3 instances
@ -87,15 +88,15 @@ public class CalleeControllerTests {
instanceParameter);
}
@AfterClass
public static void afterClass() {
@AfterAll
static void afterAll() {
if (null != namingServer) {
namingServer.terminate();
}
}
@Before
public void setUp() {
@BeforeEach
void setUp() {
QuotaResponse quotaResponse = mock(QuotaResponse.class);
when(quotaResponse.getCode()).thenReturn(QuotaResultCode.QuotaResultOk);
when(limitAPI.getQuota(any())).thenReturn(quotaResponse);
@ -126,12 +127,12 @@ public class CalleeControllerTests {
}
else {
e.printStackTrace();
Assert.fail(e.getMessage());
fail(e.getMessage());
}
}
}
Assert.assertTrue(hasPassed);
Assert.assertTrue(hasLimited);
assertThat(hasPassed).isTrue();
assertThat(hasLimited).isTrue();
}
@Configuration

@ -22,12 +22,12 @@ import java.util.Map;
import com.google.protobuf.StringValue;
import com.tencent.cloud.polaris.context.ServiceRuleManager;
import com.tencent.cloud.polaris.ratelimit.config.PolarisRateLimitProperties;
import com.tencent.polaris.client.pb.ModelProto;
import com.tencent.polaris.client.pb.RateLimitProto;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import com.tencent.polaris.specification.api.v1.model.ModelProto;
import com.tencent.polaris.specification.api.v1.traffic.manage.RateLimitProto;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@ -48,7 +48,7 @@ import static org.mockito.Mockito.when;
*
* @author shuiqingliu
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class PolarisRateLimitRuleEndpointTests {
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
@ -67,8 +67,8 @@ public class PolarisRateLimitRuleEndpointTests {
private ServiceRuleManager serviceRuleManager;
private PolarisRateLimitProperties polarisRateLimitProperties;
@Before
public void setUp() {
@BeforeEach
void setUp() {
serviceRuleManager = mock(ServiceRuleManager.class);
when(serviceRuleManager.getServiceRateLimitRule(any(), anyString())).thenAnswer(invocationOnMock -> {
String serviceName = invocationOnMock.getArgument(1).toString();
@ -84,7 +84,7 @@ public class PolarisRateLimitRuleEndpointTests {
}
else {
ModelProto.MatchString matchString = ModelProto.MatchString.newBuilder()
.setType(ModelProto.Operation.EXACT)
.setType(ModelProto.MatchString.MatchStringType.EXACT)
.setValue(StringValue.of("value"))
.setValueType(ModelProto.MatchString.ValueType.TEXT).build();
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.rpc.QuotaRequest;
import com.tencent.polaris.ratelimit.api.rpc.QuotaResponse;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.MockedStatic;
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 org.springframework.boot.autoconfigure.SpringBootApplication;
@ -69,10 +71,10 @@ import static org.mockito.Mockito.when;
*
* @author Haotian Zhang, cheese8, kaiy
*/
@RunWith(MockitoJUnitRunner.class)
@SpringBootTest(classes = QuotaCheckReactiveFilterTest.TestApplication.class, properties = {
"spring.cloud.polaris.namespace=Test", "spring.cloud.polaris.service=TestApp"
})
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@SpringBootTest(classes = QuotaCheckReactiveFilterTest.TestApplication.class,
properties = {"spring.cloud.polaris.namespace=Test", "spring.cloud.polaris.service=TestApp"})
public class QuotaCheckReactiveFilterTest {
private static MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils;
@ -83,8 +85,8 @@ public class QuotaCheckReactiveFilterTest {
private QuotaCheckReactiveFilter quotaCheckWithRateLimiterLimitedFallbackReactiveFilter;
private PolarisRateLimiterLimitedFallback polarisRateLimiterLimitedFallback;
@BeforeClass
public static void beforeClass() {
@BeforeAll
static void beforeAll() {
expressionLabelUtilsMockedStatic = mockStatic(SpringWebExpressionLabelUtils.class);
when(SpringWebExpressionLabelUtils.resolve(any(ServerWebExchange.class), anySet()))
.thenReturn(Collections.singletonMap("RuleLabelResolver", "RuleLabelResolver"));
@ -94,14 +96,14 @@ public class QuotaCheckReactiveFilterTest {
.thenReturn("unit-test");
}
@AfterClass
public static void afterClass() {
@AfterAll
static void afterAll() {
mockedApplicationContextAwareUtils.close();
expressionLabelUtilsMockedStatic.close();
}
@Before
public void setUp() {
@BeforeEach
void setUp() {
MetadataContext.LOCAL_NAMESPACE = "TEST";
polarisRateLimiterLimitedFallback = new JsonPolarisRateLimiterLimitedFallback();
@ -127,7 +129,8 @@ public class QuotaCheckReactiveFilterTest {
polarisRateLimitProperties.setRejectHttpCode(419);
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(
limitAPI, labelResolver, polarisRateLimitProperties, rateLimitRuleLabelResolver, null);
@ -156,7 +159,8 @@ public class QuotaCheckReactiveFilterTest {
@Test
public void testGetRuleExpressionLabels() {
try {
Method getCustomResolvedLabels = QuotaCheckReactiveFilter.class.getDeclaredMethod("getCustomResolvedLabels", ServerWebExchange.class);
Method getCustomResolvedLabels =
QuotaCheckReactiveFilter.class.getDeclaredMethod("getCustomResolvedLabels", ServerWebExchange.class);
getCustomResolvedLabels.setAccessible(true);
// Mock request
@ -169,11 +173,8 @@ public class QuotaCheckReactiveFilterTest {
assertThat(result.get("ReactiveResolver")).isEqualTo("ReactiveResolver");
// throw exception
PolarisRateLimiterLabelReactiveResolver exceptionLabelResolver = new PolarisRateLimiterLabelReactiveResolver() {
@Override
public Map<String, String> resolve(ServerWebExchange exchange) {
throw new RuntimeException("Mock exception.");
}
PolarisRateLimiterLabelReactiveResolver exceptionLabelResolver = exchange1 -> {
throw new RuntimeException("Mock exception.");
};
quotaCheckReactiveFilter = new QuotaCheckReactiveFilter(null, exceptionLabelResolver, null, null, null);
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.rpc.QuotaRequest;
import com.tencent.polaris.ratelimit.api.rpc.QuotaResponse;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.MockedStatic;
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.test.context.SpringBootTest;
@ -69,7 +71,8 @@ import static org.mockito.Mockito.when;
*
* @author Haotian Zhang, cheese8
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@SpringBootTest(classes = QuotaCheckServletFilterTest.TestApplication.class, properties = {
"spring.cloud.polaris.namespace=Test", "spring.cloud.polaris.service=TestApp"
})
@ -84,8 +87,8 @@ public class QuotaCheckServletFilterTest {
private QuotaCheckServletFilter quotaCheckWithRateLimiterLimitedFallbackFilter;
private PolarisRateLimiterLimitedFallback polarisRateLimiterLimitedFallback;
@BeforeClass
public static void beforeClass() {
@BeforeAll
static void beforeAll() {
expressionLabelUtilsMockedStatic = mockStatic(SpringWebExpressionLabelUtils.class);
when(SpringWebExpressionLabelUtils.resolve(any(ServerWebExchange.class), anySet()))
.thenReturn(Collections.singletonMap("RuleLabelResolver", "RuleLabelResolver"));
@ -95,14 +98,14 @@ public class QuotaCheckServletFilterTest {
.thenReturn("unit-test");
}
@AfterClass
public static void afterClass() {
@AfterAll
static void afterAll() {
mockedApplicationContextAwareUtils.close();
expressionLabelUtilsMockedStatic.close();
}
@Before
public void setUp() {
@BeforeEach
void setUp() {
MetadataContext.LOCAL_NAMESPACE = "TEST";
LimitAPI limitAPI = mock(LimitAPI.class);
@ -240,6 +243,7 @@ public class QuotaCheckServletFilterTest {
fail("Exception encountered.", e);
}
}
@Test
public void polarisRateLimiterLimitedFallbackTest() {
// 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.QuotaResponse;
import com.tencent.polaris.ratelimit.api.rpc.QuotaResultCode;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
@ -37,13 +37,13 @@ import static org.mockito.Mockito.when;
*
* @author Haotian Zhang
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class QuotaCheckUtilsTest {
private LimitAPI limitAPI;
@Before
public void setUp() {
@BeforeEach
void setUp() {
limitAPI = mock(LimitAPI.class);
when(limitAPI.getQuota(any(QuotaRequest.class))).thenAnswer(invocationOnMock -> {
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.polaris.ratelimit.config.PolarisRateLimitProperties;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
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 org.assertj.core.api.Assertions.assertThat;
@ -37,12 +39,14 @@ import static org.mockito.Mockito.when;
*
* @author Haotian Zhang
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class RateLimitUtilsTest {
@BeforeClass
public static void beforeClass() throws IOException {
mockStatic(ResourceFileUtils.class);
private static MockedStatic<ResourceFileUtils> mockedResourceFileUtils;
@BeforeAll
static void beforeAll() throws IOException {
mockedResourceFileUtils = mockStatic(ResourceFileUtils.class);
when(ResourceFileUtils.readFile(anyString())).thenAnswer(invocation -> {
String rejectFilePath = invocation.getArgument(0).toString();
if (rejectFilePath.equals("exception.html")) {
@ -54,6 +58,11 @@ public class RateLimitUtilsTest {
});
}
@AfterAll
static void afterAll() {
mockedResourceFileUtils.close();
}
@Test
public void testGetRejectTips() {
PolarisRateLimitProperties polarisRateLimitProperties = new PolarisRateLimitProperties();

@ -33,6 +33,12 @@
<dependency>
<groupId>com.tencent.polaris</groupId>
<artifactId>router-rule</artifactId>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<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.polaris.context.ServiceRuleManager;
import com.tencent.polaris.client.pb.ModelProto;
import com.tencent.polaris.client.pb.RoutingProto;
import com.tencent.polaris.specification.api.v1.model.ModelProto;
import com.tencent.polaris.specification.api.v1.traffic.manage.RoutingProto;
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.util.JacksonUtils;
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.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.rpc.ProcessRoutersRequest;
import com.tencent.polaris.router.api.rpc.ProcessRoutersResponse;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.assertj.core.api.AssertionsForClassTypes;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
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.anyString;
import static org.mockito.Mockito.when;
@ -80,11 +81,14 @@ import static org.mockito.Mockito.when;
*
* @author lepdou 2022-05-26
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class PolarisLoadBalancerCompositeRuleTest {
private static final AtomicBoolean initTransitiveMetadata = new AtomicBoolean(false);
private final List<RouterRequestInterceptor> requestInterceptors = new ArrayList<>();
private final String testNamespace = "testNamespace";
private final String testCallerService = "testCallerService";
private final String testCalleeService = "testCalleeService";
@Mock
private PolarisLoadBalancerProperties polarisLoadBalancerProperties;
@Mock
@ -96,12 +100,9 @@ public class PolarisLoadBalancerCompositeRuleTest {
@Mock
private RouterAPI routerAPI;
private IClientConfig config;
private String testNamespace = "testNamespace";
private String testCallerService = "testCallerService";
private String testCalleeService = "testCalleeService";
@Before
public void before() {
@BeforeEach
void setUp() {
config = new DefaultClientConfigImpl();
config.loadDefaultValues();
requestInterceptors.add(new MetadataRouterRequestInterceptor(polarisMetadataRouterProperties));
@ -117,7 +118,7 @@ public class PolarisLoadBalancerCompositeRuleTest {
AbstractLoadBalancerRule defaultRule = compositeRule.getRule();
Assert.assertNull(defaultRule);
assertThat(defaultRule).isNull();
}
@Test
@ -128,7 +129,7 @@ public class PolarisLoadBalancerCompositeRuleTest {
AbstractLoadBalancerRule lbRule = compositeRule.getRule();
Assert.assertTrue(lbRule instanceof RandomRule);
assertThat(lbRule).isInstanceOf(RandomRule.class);
}
@Test
@ -139,7 +140,7 @@ public class PolarisLoadBalancerCompositeRuleTest {
AbstractLoadBalancerRule lbRule = compositeRule.getRule();
Assert.assertTrue(lbRule instanceof PolarisWeightedRule);
assertThat(lbRule).isInstanceOf(PolarisWeightedRule.class);
}
@Test
@ -150,7 +151,7 @@ public class PolarisLoadBalancerCompositeRuleTest {
AbstractLoadBalancerRule lbRule = compositeRule.getRule();
Assert.assertTrue(lbRule instanceof RetryRule);
assertThat(lbRule).isInstanceOf(RetryRule.class);
}
@Test
@ -161,7 +162,7 @@ public class PolarisLoadBalancerCompositeRuleTest {
AbstractLoadBalancerRule lbRule = compositeRule.getRule();
Assert.assertTrue(lbRule instanceof WeightedResponseTimeRule);
assertThat(lbRule).isInstanceOf(WeightedResponseTimeRule.class);
}
@Test
@ -172,7 +173,7 @@ public class PolarisLoadBalancerCompositeRuleTest {
AbstractLoadBalancerRule lbRule = compositeRule.getRule();
Assert.assertTrue(lbRule instanceof BestAvailableRule);
assertThat(lbRule).isInstanceOf(BestAvailableRule.class);
}
@Test
@ -183,7 +184,7 @@ public class PolarisLoadBalancerCompositeRuleTest {
AbstractLoadBalancerRule lbRule = compositeRule.getRule();
Assert.assertTrue(lbRule instanceof RoundRobinRule);
assertThat(lbRule).isInstanceOf(RoundRobinRule.class);
}
@Test
@ -194,7 +195,7 @@ public class PolarisLoadBalancerCompositeRuleTest {
AbstractLoadBalancerRule lbRule = compositeRule.getRule();
Assert.assertTrue(lbRule instanceof AvailabilityFilteringRule);
assertThat(lbRule).isInstanceOf(AvailabilityFilteringRule.class);
}
@Test
@ -224,13 +225,15 @@ public class PolarisLoadBalancerCompositeRuleTest {
Set<RouteArgument> routerMetadata = request.getRouterArguments(MetadataRouter.ROUTER_TYPE_METADATA);
Assert.assertEquals(1, routerMetadata.size());
Assert.assertEquals(0, request.getRouterArguments(NearbyRouter.ROUTER_TYPE_NEAR_BY).size());
Assert.assertEquals(1, request.getRouterArguments(RuleBasedRouter.ROUTER_TYPE_RULE_BASED).size());
AssertionsForClassTypes.assertThat(routerMetadata.size()).isEqualTo(1);
AssertionsForClassTypes.assertThat(request.getRouterArguments(NearbyRouter.ROUTER_TYPE_NEAR_BY).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)) {
Assert.assertEquals(RuleBasedRouter.ROUTER_ENABLED, routeArgument.getKey());
Assert.assertEquals("false", routeArgument.getValue());
AssertionsForClassTypes.assertThat(routeArgument.getKey()).isEqualTo(RuleBasedRouter.ROUTER_ENABLED);
AssertionsForClassTypes.assertThat(routeArgument.getValue()).isEqualTo("false");
}
}
}
@ -257,19 +260,21 @@ public class PolarisLoadBalancerCompositeRuleTest {
Set<RouteArgument> routerMetadata = request.getRouterArguments(NearbyRouter.ROUTER_TYPE_NEAR_BY);
Assert.assertEquals(0, request.getRouterArguments(MetadataRouter.ROUTER_TYPE_METADATA).size());
Assert.assertEquals(1, routerMetadata.size());
AssertionsForClassTypes.assertThat(request.getRouterArguments(MetadataRouter.ROUTER_TYPE_METADATA).size())
.isEqualTo(0);
AssertionsForClassTypes.assertThat(routerMetadata.size()).isEqualTo(1);
for (RouteArgument routeArgument : routerMetadata) {
Assert.assertEquals(NearbyRouter.ROUTER_ENABLED, routeArgument.getKey());
Assert.assertEquals("true", routeArgument.getValue());
AssertionsForClassTypes.assertThat(routeArgument.getKey()).isEqualTo(RuleBasedRouter.ROUTER_ENABLED);
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)) {
Assert.assertEquals(RuleBasedRouter.ROUTER_ENABLED, routeArgument.getKey());
Assert.assertEquals("false", routeArgument.getValue());
AssertionsForClassTypes.assertThat(routeArgument.getKey()).isEqualTo(RuleBasedRouter.ROUTER_ENABLED);
AssertionsForClassTypes.assertThat(routeArgument.getValue()).isEqualTo("false");
}
}
}
@ -296,9 +301,11 @@ public class PolarisLoadBalancerCompositeRuleTest {
Set<RouteArgument> routerMetadata = request.getRouterArguments(RuleBasedRouter.ROUTER_TYPE_RULE_BASED);
Assert.assertEquals(3, routerMetadata.size());
Assert.assertEquals(0, request.getRouterArguments(MetadataRouter.ROUTER_TYPE_METADATA).size());
Assert.assertEquals(0, request.getRouterArguments(NearbyRouter.ROUTER_TYPE_NEAR_BY).size());
AssertionsForClassTypes.assertThat(routerMetadata.size()).isEqualTo(3);
AssertionsForClassTypes.assertThat(request.getRouterArguments(MetadataRouter.ROUTER_TYPE_METADATA).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());
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.tencent.cloud.common.constant.RouterConstant;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* test for {@link PolarisRouterContext}.
@ -43,26 +44,26 @@ public class PolarisRouterContextTest {
PolarisRouterContext routerContext = new PolarisRouterContext();
routerContext.putLabels(RouterConstant.ROUTER_LABELS, labels);
Assert.assertEquals(0, routerContext.getLabels(RouterConstant.TRANSITIVE_LABELS).size());
Assert.assertEquals(2, routerContext.getLabels(RouterConstant.ROUTER_LABELS).size());
Assert.assertEquals("v1", routerContext.getLabels(RouterConstant.ROUTER_LABELS).get("k1"));
Assert.assertEquals("v2", routerContext.getLabels(RouterConstant.ROUTER_LABELS).get("k2"));
Assert.assertNull(routerContext.getLabels(RouterConstant.ROUTER_LABELS).get("k3"));
assertThat(routerContext.getLabels(RouterConstant.TRANSITIVE_LABELS).size()).isEqualTo(0);
assertThat(routerContext.getLabels(RouterConstant.ROUTER_LABELS).size()).isEqualTo(2);
assertThat(routerContext.getLabels(RouterConstant.ROUTER_LABELS).get("k1")).isEqualTo("v1");
assertThat(routerContext.getLabels(RouterConstant.ROUTER_LABELS).get("k2")).isEqualTo("v2");
assertThat(routerContext.getLabels(RouterConstant.ROUTER_LABELS).get("k3")).isNull();
}
@Test
public void testSetNull() {
PolarisRouterContext routerContext = new PolarisRouterContext();
routerContext.putLabels(RouterConstant.ROUTER_LABELS, null);
Assert.assertEquals(0, routerContext.getLabels(RouterConstant.TRANSITIVE_LABELS).size());
Assert.assertEquals(0, routerContext.getLabels(RouterConstant.ROUTER_LABELS).size());
assertThat(routerContext.getLabels(RouterConstant.TRANSITIVE_LABELS).size()).isEqualTo(0);
assertThat(routerContext.getLabels(RouterConstant.ROUTER_LABELS).size()).isEqualTo(0);
}
@Test
public void testGetEmptyRouterContext() {
PolarisRouterContext routerContext = new PolarisRouterContext();
Assert.assertEquals(0, routerContext.getLabels(RouterConstant.TRANSITIVE_LABELS).size());
Assert.assertEquals(0, routerContext.getLabels(RouterConstant.ROUTER_LABELS).size());
assertThat(routerContext.getLabels(RouterConstant.TRANSITIVE_LABELS).size()).isEqualTo(0);
assertThat(routerContext.getLabels(RouterConstant.ROUTER_LABELS).size()).isEqualTo(0);
}
@Test
@ -78,9 +79,9 @@ public class PolarisRouterContextTest {
Map<String, String> resolvedLabels = routerContext.getLabels(RouterConstant.ROUTER_LABELS,
Sets.newHashSet("k1", "k2", "k4"));
Assert.assertEquals(2, resolvedLabels.size());
Assert.assertEquals("v1", resolvedLabels.get("k1"));
Assert.assertEquals("v2", resolvedLabels.get("k2"));
assertThat(resolvedLabels.size()).isEqualTo(2);
assertThat(resolvedLabels.get("k1")).isEqualTo("v1");
assertThat(resolvedLabels.get("k2")).isEqualTo("v2");
}
@Test
@ -94,8 +95,7 @@ public class PolarisRouterContextTest {
routerContext.putLabels(RouterConstant.ROUTER_LABELS, labels);
String resolvedLabel = routerContext.getLabel("k1");
Assert.assertEquals("v1", resolvedLabel);
assertThat(resolvedLabel).isEqualTo("v1");
}
@Test
@ -108,9 +108,9 @@ public class PolarisRouterContextTest {
Set<String> resolvedLabels = routerContext.getLabelAsSet("k1");
Assert.assertEquals(3, resolvedLabels.size());
Assert.assertTrue(resolvedLabels.contains("v1"));
Assert.assertTrue(resolvedLabels.contains("v2"));
Assert.assertTrue(resolvedLabels.contains("v3"));
assertThat(resolvedLabels.size()).isEqualTo(3);
assertThat(resolvedLabels).contains("v1");
assertThat(resolvedLabels).contains("v2");
assertThat(resolvedLabels).contains("v3");
}
}

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

@ -13,27 +13,26 @@
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.polaris.router.resttemplate;
package com.tencent.cloud.polaris.router.beanprocessor;
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 org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor;
import org.springframework.cloud.client.loadbalancer.LoadBalancerRequestFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
/**
@ -41,8 +40,8 @@ import static org.mockito.Mockito.when;
*
* @author lepdou 2022-05-26
*/
@RunWith(MockitoJUnitRunner.class)
public class PolarisLoadBalancerBeanPostProcessorTest {
@ExtendWith(MockitoExtension.class)
public class LoadBalancerInterceptorBeanPostProcessorTest {
@Mock
private LoadBalancerClient loadBalancerClient;
@ -66,7 +65,7 @@ public class PolarisLoadBalancerBeanPostProcessorTest {
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();
Object bean = processor.postProcessBeforeInitialization(otherBean, "");
Assert.assertFalse(bean instanceof PolarisLoadBalancerInterceptor);
Assert.assertTrue(bean instanceof OtherBean);
assertThat(bean).isNotInstanceOf(PolarisLoadBalancerInterceptor.class);
assertThat(bean).isInstanceOf(OtherBean.class);
}
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.router.api.core.RouterAPI;
import com.tencent.polaris.router.client.api.DefaultRouterAPI;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test for {@link PolarisLoadBalancerCompositeRuleBeanPostProcessor}.
@ -74,12 +74,12 @@ public class PolarisLoadBalancerCompositeRuleBeanPostProcessorTest {
SpringClientFactory springClientFactory = context.getBean(SpringClientFactory.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");
Assert.assertFalse(CollectionUtils.isEmpty(requestInterceptors));
assertThat(requestInterceptors).isNotEmpty();
AbstractLoadBalancerRule delegateRule = ((PolarisLoadBalancerCompositeRule) rule).getDelegateRule();
//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);
IRule rule = springClientFactory.getInstance(SERVICE_1, IRule.class);
Assert.assertTrue(rule instanceof PolarisLoadBalancerCompositeRule);
assertThat(rule).isInstanceOf(PolarisLoadBalancerCompositeRule.class);
AbstractLoadBalancerRule delegateRule = ((PolarisLoadBalancerCompositeRule) rule).getDelegateRule();
//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);
IRule rule1 = springClientFactory.getInstance(SERVICE_1, IRule.class);
Assert.assertTrue(rule1 instanceof PolarisLoadBalancerCompositeRule);
assertThat(rule1).isInstanceOf(PolarisLoadBalancerCompositeRule.class);
AbstractLoadBalancerRule delegateRule1 = ((PolarisLoadBalancerCompositeRule) rule1).getDelegateRule();
//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);
Assert.assertTrue(rule2 instanceof PolarisLoadBalancerCompositeRule);
assertThat(rule2).isInstanceOf(PolarisLoadBalancerCompositeRule.class);
AbstractLoadBalancerRule delegateRule2 = ((PolarisLoadBalancerCompositeRule) rule2).getDelegateRule();
//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);
IRule rule1 = springClientFactory.getInstance(SERVICE_1, IRule.class);
Assert.assertTrue(rule1 instanceof PolarisLoadBalancerCompositeRule);
assertThat(rule1).isInstanceOf(PolarisLoadBalancerCompositeRule.class);
AbstractLoadBalancerRule delegateRule1 = ((PolarisLoadBalancerCompositeRule) rule1).getDelegateRule();
//RibbonConfigForService1#loadBalancerRule returns BestAvailableRule
Assert.assertTrue(delegateRule1 instanceof BestAvailableRule);
assertThat(delegateRule1).isInstanceOf(BestAvailableRule.class);
IRule rule2 = springClientFactory.getInstance(SERVICE_2, IRule.class);
Assert.assertTrue(rule2 instanceof PolarisLoadBalancerCompositeRule);
assertThat(rule2).isInstanceOf(PolarisLoadBalancerCompositeRule.class);
AbstractLoadBalancerRule delegateRule2 = ((PolarisLoadBalancerCompositeRule) rule2).getDelegateRule();
//ZoneAvoidanceRule default
Assert.assertTrue(delegateRule2 instanceof ZoneAvoidanceRule);
assertThat(delegateRule2).isInstanceOf(ZoneAvoidanceRule.class);
});
}

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

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

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

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

@ -22,22 +22,22 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Lists;
import com.tencent.cloud.common.util.ApplicationContextAwareUtils;
import com.tencent.cloud.polaris.context.ServiceRuleManager;
import com.tencent.polaris.client.pb.ModelProto;
import com.tencent.polaris.client.pb.RoutingProto;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.tencent.polaris.specification.api.v1.model.ModelProto;
import com.tencent.polaris.specification.api.v1.traffic.manage.RoutingProto;
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
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.Mockito.when;
@ -45,7 +45,7 @@ import static org.mockito.Mockito.when;
* Test for {@link PolarisRouterEndpoint}.
* @author lepdou 2022-07-25
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class PolarisRouterEndpointTest {
private static final String testDestService = "dstService";
@ -56,15 +56,15 @@ public class PolarisRouterEndpointTest {
@InjectMocks
private PolarisRouterEndpoint polarisRouterEndpoint;
@BeforeClass
public static void beforeClass() {
@BeforeAll
static void beforeAll() {
mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class);
mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString()))
.thenReturn(testDestService);
}
@AfterClass
public static void afterClass() {
@AfterAll
static void afterAll() {
mockedApplicationContextAwareUtils.close();
}
@ -91,27 +91,27 @@ public class PolarisRouterEndpointTest {
List<RoutingProto.Route> routes = new LinkedList<>();
RoutingProto.Route route = RoutingProto.Route.newBuilder()
.addAllSources(Lists.newArrayList(source1, source2, source3))
.addAllSources(Lists.list(source1, source2, source3))
.build();
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);
Assert.assertNotNull(actuator.get("routerRules"));
Assert.assertEquals(1, ((List) actuator.get("routerRules")).size());
assertThat(actuator.get("routerRules")).isNotNull();
assertThat(((List<?>) actuator.get("routerRules")).size()).isEqualTo(1);
}
@Test
public void testHasNotRouterRule() {
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);
Assert.assertNotNull(actuator.get("routerRules"));
Assert.assertEquals(0, ((List) actuator.get("routerRules")).size());
assertThat(actuator.get("routerRules")).isNotNull();
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.Map;
import java.util.stream.Stream;
import com.google.common.collect.Sets;
import feign.Request;
import feign.RequestTemplate;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.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}.
@ -52,14 +52,14 @@ public class FeignExpressionLabelUtilsTest {
String labelKey4 = "${http.header.}";
String labelKey5 = "${http.header.teacher.age}";
Map<String, String> result = FeignExpressionLabelUtils.resolve(requestTemplate,
Sets.newHashSet(labelKey1, labelKey2, labelKey3, labelKey4, labelKey5));
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(headerValue, result.get(labelKey1));
Assert.assertEquals(headerValue2, result.get(labelKey5));
Assert.assertTrue(StringUtils.isEmpty(result.get(labelKey2)));
Assert.assertTrue(StringUtils.isEmpty(result.get(labelKey3)));
Assert.assertTrue(StringUtils.isEmpty(result.get(labelKey4)));
Stream.of(labelKey1, labelKey2, labelKey3, labelKey4, labelKey5).collect(toSet()));
assertThat(result).isNotEmpty();
assertThat(result.get(labelKey1)).isEqualTo(headerValue);
assertThat(result.get(labelKey5)).isEqualTo(headerValue2);
assertThat(result.get(labelKey2)).isBlank();
assertThat(result.get(labelKey3)).isBlank();
assertThat(result.get(labelKey4)).isBlank();
}
@Test
@ -79,14 +79,14 @@ public class FeignExpressionLabelUtilsTest {
String labelKey4 = "${http.query.}";
String labelKey5 = "${http.query.teacher.age}";
Map<String, String> result = FeignExpressionLabelUtils.resolve(requestTemplate,
Sets.newHashSet(labelKey1, labelKey2, labelKey3, labelKey4, labelKey5));
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(headerValue, result.get(labelKey1));
Assert.assertEquals(headerValue2, result.get(labelKey5));
Assert.assertTrue(StringUtils.isEmpty(result.get(labelKey2)));
Assert.assertTrue(StringUtils.isEmpty(result.get(labelKey3)));
Assert.assertTrue(StringUtils.isEmpty(result.get(labelKey4)));
Stream.of(labelKey1, labelKey2, labelKey3, labelKey4, labelKey5).collect(toSet()));
assertThat(result).isNotEmpty();
assertThat(result.get(labelKey1)).isEqualTo(headerValue);
assertThat(result.get(labelKey5)).isEqualTo(headerValue2);
assertThat(result.get(labelKey2)).isBlank();
assertThat(result.get(labelKey3)).isBlank();
assertThat(result.get(labelKey4)).isBlank();
}
@Test
@ -95,11 +95,11 @@ public class FeignExpressionLabelUtilsTest {
requestTemplate.method(Request.HttpMethod.GET);
String labelKey1 = "${http.method}";
Map<String, String> result = FeignExpressionLabelUtils.resolve(requestTemplate,
Sets.newHashSet(labelKey1));
Map<String, String> result = FeignExpressionLabelUtils.resolve(requestTemplate, Stream.of(labelKey1)
.collect(toSet()));
Assert.assertFalse(result.isEmpty());
Assert.assertEquals("GET", result.get(labelKey1));
assertThat(result).isNotEmpty();
assertThat(result.get(labelKey1)).isEqualTo("GET");
}
@Test
@ -113,11 +113,11 @@ public class FeignExpressionLabelUtilsTest {
requestTemplate = requestTemplate.resolve(new HashMap<>());
String labelKey1 = "${http.uri}";
Map<String, String> result = FeignExpressionLabelUtils.resolve(requestTemplate,
Sets.newHashSet(labelKey1));
Map<String, String> result = FeignExpressionLabelUtils.resolve(requestTemplate, Stream.of(labelKey1)
.collect(toSet()));
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(uri, result.get(labelKey1));
assertThat(result).isNotEmpty();
assertThat(result.get(labelKey1)).isEqualTo(uri);
}
@Test
@ -131,10 +131,10 @@ public class FeignExpressionLabelUtilsTest {
requestTemplate = requestTemplate.resolve(new HashMap<>());
String labelKey1 = "${http.uri}";
Map<String, String> result = FeignExpressionLabelUtils.resolve(requestTemplate,
Sets.newHashSet(labelKey1));
Map<String, String> result = FeignExpressionLabelUtils.resolve(requestTemplate, Stream.of(labelKey1)
.collect(toSet()));
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(uri, result.get(labelKey1));
assertThat(result).isNotEmpty();
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.loadbalancer.ILoadBalancer;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
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.ServerIntrospector;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
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.verify;
import static org.mockito.Mockito.when;
@ -40,7 +40,7 @@ import static org.mockito.Mockito.when;
*
* @author lepdou 2022-05-26
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class PolarisCachingSpringLoadBalanceFactoryTest {
private final String service1 = "service1";
@ -74,30 +74,30 @@ public class PolarisCachingSpringLoadBalanceFactoryTest {
// load balancer for service1
FeignLoadBalancer feignLoadBalancer = polarisCachingSpringLoadBalanceFactory.create(service1);
Assert.assertNotNull(feignLoadBalancer);
assertThat(feignLoadBalancer).isNotNull();
verify(factory).getClientConfig(service1);
verify(factory, times(0)).getClientConfig(service2);
verify(factory).getLoadBalancer(service1);
verify(factory, times(0)).getLoadBalancer(service2);
verify(factory).getInstance(service1, ServerIntrospector.class);
verify(factory, times(0)).getInstance(service2, ServerIntrospector.class);
Assert.assertEquals(loadBalancer, feignLoadBalancer.getLoadBalancer());
Assert.assertEquals(service1, feignLoadBalancer.getClientName());
assertThat(feignLoadBalancer.getLoadBalancer()).isEqualTo(loadBalancer);
assertThat(feignLoadBalancer.getClientName()).isEqualTo(service1);
// load balancer for service2
FeignLoadBalancer feignLoadBalancer2 = polarisCachingSpringLoadBalanceFactory.create(service2);
// load balancer for service1 again
feignLoadBalancer = polarisCachingSpringLoadBalanceFactory.create(service1);
Assert.assertNotNull(feignLoadBalancer);
assertThat(feignLoadBalancer2).isNotNull();
verify(factory).getClientConfig(service1);
verify(factory).getClientConfig(service2);
verify(factory).getLoadBalancer(service1);
verify(factory).getLoadBalancer(service2);
verify(factory).getInstance(service1, ServerIntrospector.class);
verify(factory).getInstance(service2, ServerIntrospector.class);
Assert.assertEquals(loadBalancer, feignLoadBalancer2.getLoadBalancer());
Assert.assertEquals(service2, feignLoadBalancer2.getClientName());
assertThat(feignLoadBalancer2.getLoadBalancer()).isEqualTo(loadBalancer);
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.JacksonUtils;
import com.tencent.cloud.polaris.router.PolarisRouterContext;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.MockedStatic;
import org.mockito.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.ServerIntrospector;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.anyString;
/**
@ -49,7 +49,7 @@ import static org.mockito.Mockito.anyString;
*
* @author lepdou 2022-05-26
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class PolarisFeignLoadBalancerTest {
@Test
@ -83,12 +83,12 @@ public class PolarisFeignLoadBalancerTest {
PolarisRouterContext routerContext = polarisFeignLoadBalancer.buildRouterContext(headers);
Assert.assertNotNull(routerContext);
assertThat(routerContext).isNotNull();
Map<String, String> routerLabels = routerContext.getLabels(RouterConstant.ROUTER_LABELS);
Assert.assertNotNull(routerLabels);
Assert.assertEquals("v1", routerLabels.get("k1"));
Assert.assertEquals("v2", routerLabels.get("k2"));
Assert.assertNull(routerLabels.get("k3"));
assertThat(routerLabels).isNotNull();
assertThat(routerLabels.get("k1")).isEqualTo("v1");
assertThat(routerLabels.get("k2")).isEqualTo("v2");
assertThat(routerLabels.get("k3")).isNull();
}
}
}
@ -114,8 +114,7 @@ public class PolarisFeignLoadBalancerTest {
mockedMetadataContextHolder.when(MetadataContextHolder::get).thenReturn(metadataContext);
PolarisRouterContext routerContext = polarisFeignLoadBalancer.buildRouterContext(headers);
Assert.assertNull(routerContext);
assertThat(routerContext).isNull();
}
}
}

@ -38,13 +38,12 @@ import com.tencent.cloud.polaris.router.RouterRuleLabelResolver;
import com.tencent.cloud.polaris.router.spi.FeignRouterLabelResolver;
import feign.RequestTemplate;
import feign.Target;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
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.mockito.ArgumentMatchers.anyString;
@ -55,7 +54,7 @@ import static org.mockito.Mockito.when;
*
* @author lepdou, cheese8
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class RouterLabelFeignInterceptorTest {
@Mock
@ -124,16 +123,16 @@ public class RouterLabelFeignInterceptorTest {
Collection<String> routerLabels = requestTemplate.headers().get(RouterConstant.ROUTER_LABEL_HEADER);
Assert.assertNotNull(routerLabels);
assertThat(routerLabels).isNotNull();
for (String value : routerLabels) {
Map<String, String> labels = JacksonUtils.deserialize2Map(URLDecoder.decode(value, "UTF-8"));
Assert.assertEquals("v1", labels.get("k1"));
Assert.assertEquals("v22", labels.get("k2"));
Assert.assertEquals("v3", labels.get("k3"));
Assert.assertEquals("v4", labels.get("k4"));
Assert.assertEquals(headerUidValue, labels.get("${http.header.uid}"));
Assert.assertEquals("", labels.get("${http.header.name}"));
assertThat(labels.get("k1")).isEqualTo("v1");
assertThat(labels.get("k2")).isEqualTo("v22");
assertThat(labels.get("k3")).isEqualTo("v3");
assertThat(labels.get("k4")).isEqualTo("v4");
assertThat(labels.get("${http.header.uid}")).isEqualTo(headerUidValue);
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.JacksonUtils;
import com.tencent.cloud.polaris.router.PolarisRouterContext;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
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.loadbalancer.LoadBalancerClient;
@ -53,6 +51,7 @@ import org.springframework.http.client.ClientHttpResponse;
import org.springframework.mock.http.client.MockClientHttpResponse;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
@ -64,7 +63,7 @@ import static org.mockito.Mockito.when;
*
* @author lepdou 2022-05-26
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class PolarisLoadBalancerInterceptorTest {
@Mock
@ -116,7 +115,7 @@ public class PolarisLoadBalancerInterceptorTest {
catch (UnsupportedEncodingException e) {
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);
}
}
@ -139,7 +138,7 @@ public class PolarisLoadBalancerInterceptorTest {
ClientHttpResponse response = polarisLoadBalancerInterceptor.intercept(request, null, null);
Assert.assertEquals(mockedResponse, response);
assertThat(response).isEqualTo(mockedResponse);
verify(loadBalancerRequestFactory).createRequest(request, null, null);
verify(notRibbonLoadBalancerClient).execute(calleeService, loadBalancerRequest);
@ -155,7 +154,7 @@ public class PolarisLoadBalancerInterceptorTest {
static class MockedHttpRequest implements HttpRequest {
private URI uri;
private final URI uri;
MockedHttpRequest(String url) {
this.uri = URI.create(url);

@ -18,7 +18,7 @@
package com.tencent.cloud.polaris.router.resttemplate;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
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.RouterRuleLabelResolver;
import com.tencent.cloud.polaris.router.spi.SpringWebRouterLabelResolver;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ -54,7 +54,7 @@ import static org.mockito.Mockito.when;
*
* @author lepdou 2022-10-09
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class RouterContextFactoryTest {
@Mock
@ -105,7 +105,7 @@ public class RouterContextFactoryTest {
try (MockedStatic<MetadataContextHolder> mockedMetadataContextHolder = Mockito.mockStatic(MetadataContextHolder.class)) {
mockedMetadataContextHolder.when(MetadataContextHolder::get).thenReturn(metadataContext);
RouterContextFactory routerContextFactory = new RouterContextFactory(Arrays.asList(springWebRouterLabelResolver),
RouterContextFactory routerContextFactory = new RouterContextFactory(Collections.singletonList(springWebRouterLabelResolver),
staticMetadataManager, routerRuleLabelResolver, polarisContextProperties);
PolarisRouterContext routerContext = routerContextFactory.create(request, null, calleeService);
@ -114,22 +114,22 @@ public class RouterContextFactoryTest {
verify(routerRuleLabelResolver).getExpressionLabelKeys(callerService, callerService, calleeService);
verify(springWebRouterLabelResolver).resolve(request, null, expressionKeys);
Assert.assertEquals("v1", routerContext.getLabels(RouterConstant.TRANSITIVE_LABELS).get("k1"));
Assert.assertEquals("v22", routerContext.getLabels(RouterConstant.TRANSITIVE_LABELS).get("k2"));
Assert.assertEquals("v1", routerContext.getLabels(RouterConstant.ROUTER_LABELS).get("k1"));
Assert.assertEquals("v22", routerContext.getLabels(RouterConstant.ROUTER_LABELS).get("k2"));
Assert.assertEquals("v4", routerContext.getLabels(RouterConstant.ROUTER_LABELS).get("k4"));
Assert.assertEquals("GET", routerContext.getLabels(RouterConstant.ROUTER_LABELS)
.get("${http.method}"));
Assert.assertEquals("/user/get", routerContext.getLabels(RouterConstant.ROUTER_LABELS)
.get("${http.uri}"));
assertThat(routerContext.getLabels(RouterConstant.TRANSITIVE_LABELS).get("k1")).isEqualTo("v1");
assertThat(routerContext.getLabels(RouterConstant.TRANSITIVE_LABELS).get("k2")).isEqualTo("v22");
assertThat(routerContext.getLabels(RouterConstant.ROUTER_LABELS).get("k1")).isEqualTo("v1");
assertThat(routerContext.getLabels(RouterConstant.ROUTER_LABELS).get("k2")).isEqualTo("v22");
assertThat(routerContext.getLabels(RouterConstant.ROUTER_LABELS).get("k4")).isEqualTo("v4");
assertThat(routerContext.getLabels(RouterConstant.ROUTER_LABELS)
.get("${http.method}")).isEqualTo("GET");
assertThat(routerContext.getLabels(RouterConstant.ROUTER_LABELS)
.get("${http.uri}")).isEqualTo("/user/get");
}
}
}
static class MockedHttpRequest implements HttpRequest {
private URI uri;
private final URI uri;
MockedHttpRequest(String 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.RouterRuleLabelResolver;
import com.tencent.cloud.polaris.router.spi.SpringWebRouterLabelResolver;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
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.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.web.server.MockServerWebExchange;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
@ -61,9 +61,9 @@ import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.G
/**
* test for ${@link PolarisLoadBalancerClientFilter}.
*
* @author lepdou 2022-06-13
* @author lepdou 2022-07-04
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class PolarisLoadBalancerClientFilterTest {
private static final String callerService = "callerService";
@ -83,8 +83,8 @@ public class PolarisLoadBalancerClientFilterTest {
@Mock
private PolarisContextProperties polarisContextProperties;
@BeforeClass
public static void beforeClass() {
@BeforeAll
static void beforeAll() {
mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class);
mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString()))
.thenReturn(callerService);
@ -101,8 +101,8 @@ public class PolarisLoadBalancerClientFilterTest {
mockedMetadataContextHolder.when(MetadataContextHolder::get).thenReturn(metadataContext);
}
@AfterClass
public static void afterClass() {
@AfterAll
static void afterAll() {
mockedApplicationContextAwareUtils.close();
mockedMetadataContextHolder.close();
}
@ -111,13 +111,13 @@ public class PolarisLoadBalancerClientFilterTest {
public void testGenRouterContext() {
PolarisLoadBalancerClientFilter polarisLoadBalancerClientFilter = new PolarisLoadBalancerClientFilter(
loadBalancerClient, loadBalancerProperties, staticMetadataManager, routerRuleLabelResolver,
Lists.newArrayList(routerLabelResolver), polarisContextProperties);
com.google.common.collect.Lists.newArrayList(routerLabelResolver), polarisContextProperties);
Map<String, String> localMetadata = new HashMap<>();
localMetadata.put("env", "blue");
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);
MockServerHttpRequest request = MockServerHttpRequest.get("/" + calleeService + "/users")
@ -133,11 +133,11 @@ public class PolarisLoadBalancerClientFilterTest {
PolarisRouterContext routerContext = polarisLoadBalancerClientFilter.genRouterContext(webExchange, calleeService);
Map<String, String> routerLabels = routerContext.getLabels(RouterConstant.ROUTER_LABELS);
Assert.assertEquals("v1", routerLabels.get("${http.header.k1}"));
Assert.assertEquals("zhangsan", routerLabels.get("${http.query.userid}"));
Assert.assertEquals("blue", routerLabels.get("env"));
Assert.assertEquals("v1", routerLabels.get("t1"));
Assert.assertEquals("v2", routerLabels.get("t2"));
assertThat(routerLabels.get("${http.header.k1}")).isEqualTo("v1");
assertThat(routerLabels.get("${http.query.userid}")).isEqualTo("zhangsan");
assertThat(routerLabels.get("env")).isEqualTo("blue");
assertThat(routerLabels.get("t1")).isEqualTo("v1");
assertThat(routerLabels.get("t2")).isEqualTo("v2");
}
@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.spi.ServletRouterLabelResolver;
import okhttp3.OkHttpClient;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
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.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.mock.web.MockHttpServletRequest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.times;
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
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class PolarisRibbonRoutingFilterTest {
private static final String callerService = "callerService";
@ -96,8 +96,8 @@ public class PolarisRibbonRoutingFilterTest {
@Mock
private PolarisLoadBalancer polarisLoadBalancer;
@BeforeClass
public static void beforeClass() {
@BeforeAll
static void beforeAll() {
mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class);
mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString()))
.thenReturn(callerService);
@ -114,8 +114,8 @@ public class PolarisRibbonRoutingFilterTest {
mockedMetadataContextHolder.when(MetadataContextHolder::get).thenReturn(metadataContext);
}
@AfterClass
public static void afterClass() {
@AfterAll
static void afterAll() {
mockedApplicationContextAwareUtils.close();
mockedMetadataContextHolder.close();
}
@ -146,11 +146,11 @@ public class PolarisRibbonRoutingFilterTest {
PolarisRouterContext routerContext = polarisRibbonRoutingFilter.genRouterContext(request, calleeService);
Map<String, String> routerLabels = routerContext.getLabels(RouterConstant.ROUTER_LABELS);
Assert.assertEquals("v1", routerLabels.get("${http.header.k1}"));
Assert.assertEquals("zhangsan", routerLabels.get("${http.query.userid}"));
Assert.assertEquals("blue", routerLabels.get("env"));
Assert.assertEquals("v1", routerLabels.get("t1"));
Assert.assertEquals("v2", routerLabels.get("t2"));
assertThat(routerLabels.get("${http.header.k1}")).isEqualTo("v1");
assertThat(routerLabels.get("${http.query.userid}")).isEqualTo("zhangsan");
assertThat(routerLabels.get("env")).isEqualTo("blue");
assertThat(routerLabels.get("t1")).isEqualTo("v1");
assertThat(routerLabels.get("t2")).isEqualTo("v2");
}
@Test

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

@ -21,19 +21,19 @@ import java.util.HashMap;
import java.util.Map;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.autoconfigure.SpringBootApplication;
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}.
*
* @author Haotian Zhang
*/
@RunWith(SpringRunner.class)
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = MetadataContextHolderTest.TestApplication.class,
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.spi.InstanceMetadataProvider;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import uk.org.webcompere.systemstubs.rules.EnvironmentVariablesRule;
import org.springframework.util.CollectionUtils;
import org.mockito.junit.jupiter.MockitoExtension;
import uk.org.webcompere.systemstubs.environment.EnvironmentVariables;
import uk.org.webcompere.systemstubs.jupiter.SystemStub;
import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
/**
* test for {@link StaticMetadataManager}.
*@author lepdou 2022-06-27
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith({MockitoExtension.class, SystemStubsExtension.class})
public class StaticMetadataManagerTest {
@Mock
private MetadataLocalProperties metadataLocalProperties;
/**
* EnvironmentVariablesRule.
*/
@Rule
public EnvironmentVariablesRule rule = new EnvironmentVariablesRule();
@SystemStub
public EnvironmentVariables environmentVariables = new EnvironmentVariables();
@Mock
private MetadataLocalProperties metadataLocalProperties;
@Test
public void testParseConfigMetadata() {
@ -69,20 +66,20 @@ public class StaticMetadataManagerTest {
StaticMetadataManager metadataManager = new StaticMetadataManager(metadataLocalProperties, null);
Map<String, String> metadata = metadataManager.getAllConfigMetadata();
Assert.assertEquals(4, metadata.size());
Assert.assertEquals("v1", metadata.get("k1"));
Assert.assertEquals("v22", metadata.get("k2"));
assertThat(metadata.size()).isEqualTo(4);
assertThat(metadata.get("k1")).isEqualTo("v1");
assertThat(metadata.get("k2")).isEqualTo("v22");
Map<String, String> transitiveMetadata = metadataManager.getConfigTransitiveMetadata();
Assert.assertEquals(1, transitiveMetadata.size());
Assert.assertEquals("v1", transitiveMetadata.get("k1"));
assertThat(transitiveMetadata.size()).isEqualTo(1);
assertThat(transitiveMetadata.get("k1")).isEqualTo("v1");
Assert.assertEquals("zone1", metadataManager.getZone());
Assert.assertEquals("region1", metadataManager.getRegion());
assertThat(metadataManager.getZone()).isEqualTo("zone1");
assertThat(metadataManager.getRegion()).isEqualTo("region1");
Map<String, String> locationInfo = metadataManager.getLocationMetadata();
Assert.assertEquals("zone1", locationInfo.get("zone"));
Assert.assertEquals("region1", locationInfo.get("region"));
assertThat(locationInfo.get("zone")).isEqualTo("zone1");
assertThat(locationInfo.get("region")).isEqualTo("region1");
}
@Test
@ -98,21 +95,21 @@ public class StaticMetadataManagerTest {
new MockedMetadataProvider());
Map<String, String> metadata = metadataManager.getAllCustomMetadata();
Assert.assertEquals(3, metadata.size());
Assert.assertEquals("v1", metadata.get("k1"));
Assert.assertEquals("v22", metadata.get("k2"));
Assert.assertEquals("v33", metadata.get("k3"));
assertThat(metadata.size()).isEqualTo(3);
assertThat(metadata.get("k1")).isEqualTo("v1");
assertThat(metadata.get("k2")).isEqualTo("v22");
assertThat(metadata.get("k3")).isEqualTo("v33");
Map<String, String> transitiveMetadata = metadataManager.getCustomSPITransitiveMetadata();
Assert.assertEquals(1, transitiveMetadata.size());
Assert.assertEquals("v22", metadata.get("k2"));
assertThat(transitiveMetadata.size()).isEqualTo(1);
assertThat(metadata.get("k2")).isEqualTo("v22");
Assert.assertEquals("zone2", metadataManager.getZone());
Assert.assertEquals("region1", metadataManager.getRegion());
assertThat(metadataManager.getZone()).isEqualTo("zone2");
assertThat(metadataManager.getRegion()).isEqualTo("region1");
Map<String, String> locationInfo = metadataManager.getLocationMetadata();
Assert.assertEquals("zone2", locationInfo.get("zone"));
Assert.assertEquals("region1", locationInfo.get("region"));
assertThat(locationInfo.get("zone")).isEqualTo("zone2");
assertThat(locationInfo.get("region")).isEqualTo("region1");
}
@Test
@ -131,53 +128,52 @@ public class StaticMetadataManagerTest {
new MockedMetadataProvider());
Map<String, String> metadata = metadataManager.getMergedStaticMetadata();
Assert.assertEquals(6, metadata.size());
Assert.assertEquals("v1", metadata.get("k1"));
Assert.assertEquals("v22", metadata.get("k2"));
Assert.assertEquals("v33", metadata.get("k3"));
assertThat(metadata.size()).isEqualTo(6);
assertThat(metadata.get("k1")).isEqualTo("v1");
assertThat(metadata.get("k2")).isEqualTo("v22");
assertThat(metadata.get("k3")).isEqualTo("v33");
Map<String, String> transitiveMetadata = metadataManager.getMergedStaticTransitiveMetadata();
Assert.assertEquals(2, transitiveMetadata.size());
Assert.assertEquals("v1", metadata.get("k1"));
Assert.assertEquals("v22", metadata.get("k2"));
assertThat(transitiveMetadata.size()).isEqualTo(2);
assertThat(metadata.get("k1")).isEqualTo("v1");
assertThat(metadata.get("k2")).isEqualTo("v22");
Assert.assertEquals("zone2", metadataManager.getZone());
Assert.assertEquals("region1", metadataManager.getRegion());
assertThat(metadataManager.getAllEnvMetadata()).isEmpty();
assertThat(metadataManager.getEnvTransitiveMetadata()).isEmpty();
Assert.assertTrue(CollectionUtils.isEmpty(metadataManager.getAllEnvMetadata()));
Assert.assertTrue(CollectionUtils.isEmpty(metadataManager.getEnvTransitiveMetadata()));
assertThat(metadataManager.getZone()).isEqualTo("zone2");
assertThat(metadataManager.getRegion()).isEqualTo("region1");
Map<String, String> locationInfo = metadataManager.getLocationMetadata();
Assert.assertEquals("zone2", locationInfo.get("zone"));
Assert.assertEquals("region1", locationInfo.get("region"));
Assert.assertEquals("campus1", locationInfo.get("campus"));
assertThat(locationInfo.get("zone")).isEqualTo("zone2");
assertThat(locationInfo.get("region")).isEqualTo("region1");
assertThat(locationInfo.get("campus")).isEqualTo("campus1");
}
@Test
public void testEnvMetadata() {
// set env
rule.set("SCT_METADATA_CONTENT_TRANSITIVE", "transitiveKey");
rule.set("SCT_METADATA_CONTENT_DISPOSABLE", "disposableKey");
rule.set("SCT_METADATA_CONTENT_transitiveKey", "transitiveValue");
rule.set("SCT_METADATA_CONTENT_disposableKey", "disposableValue");
rule.set("SCT_TRAFFIC_CONTENT_RAW_TRANSHEADERS", "header1,header2,header3");
environmentVariables.set("SCT_METADATA_CONTENT_TRANSITIVE", "transitiveKey")
.set("SCT_METADATA_CONTENT_DISPOSABLE", "disposableKey")
.set("SCT_METADATA_CONTENT_transitiveKey", "transitiveValue")
.set("SCT_METADATA_CONTENT_disposableKey", "disposableValue")
.set("SCT_TRAFFIC_CONTENT_RAW_TRANSHEADERS", "header1,header2,header3");
StaticMetadataManager metadataManager = new StaticMetadataManager(metadataLocalProperties, null);
Map<String, String> allEnvMetadata = metadataManager.getAllEnvMetadata();
Assert.assertTrue(allEnvMetadata.containsKey("transitiveKey"));
Assert.assertTrue(allEnvMetadata.containsKey("disposableKey"));
assertThat(allEnvMetadata).containsKey("transitiveKey");
assertThat(allEnvMetadata).containsKey("disposableKey");
Map<String, String> envDisposableMetadata = metadataManager.getEnvDisposableMetadata();
Assert.assertTrue(envDisposableMetadata.containsKey("disposableKey"));
Assert.assertEquals(envDisposableMetadata.get("disposableKey"), "disposableValue");
assertThat(envDisposableMetadata).containsKey("disposableKey");
assertThat(envDisposableMetadata.get("disposableKey")).isEqualTo("disposableValue");
Map<String, String> envTransitiveMetadata = metadataManager.getEnvTransitiveMetadata();
Assert.assertTrue(envTransitiveMetadata.containsKey("transitiveKey"));
Assert.assertEquals(envTransitiveMetadata.get("transitiveKey"), "transitiveValue");
assertThat(envTransitiveMetadata).containsKey("transitiveKey");
assertThat(envTransitiveMetadata.get("transitiveKey")).isEqualTo("transitiveValue");
String transHeaderFromEnv = metadataManager.getTransHeaderFromEnv();
Assert.assertEquals(transHeaderFromEnv, "header1,header2,header3");
assertThat(transHeaderFromEnv).isEqualTo("header1,header2,header3");
}
static class MockedMetadataProvider implements InstanceMetadataProvider {

@ -19,7 +19,7 @@
package com.tencent.cloud.common.metadata.config;
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.test.context.runner.ApplicationContextRunner;

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

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

@ -21,77 +21,78 @@ package com.tencent.cloud.common.rule;
import java.util.Arrays;
import java.util.Collections;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test for {@link Operation}.
* @author lepdou 2022-07-12
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class OperationTest {
@Test
public void testEqual() {
Assert.assertTrue(Operation.match(Collections.singletonList("v1"), "v1", Operation.EQUALS.getValue()));
Assert.assertFalse(Operation.match(Collections.singletonList("v1"), "v2", Operation.EQUALS.getValue()));
Assert.assertFalse(Operation.match(Collections.singletonList(""), "v2", Operation.EQUALS.getValue()));
Assert.assertFalse(Operation.match(Collections.singletonList("v1"), "", Operation.EQUALS.getValue()));
Assert.assertFalse(Operation.match(Collections.singletonList("v1"), null, Operation.EQUALS.getValue()));
Assert.assertFalse(Operation.match(Collections.emptyList(), "v1", Operation.EQUALS.getValue()));
assertThat(Operation.match(Collections.singletonList("v1"), "v1", Operation.EQUALS.getValue())).isTrue();
assertThat(Operation.match(Collections.singletonList("v1"), "v2", Operation.EQUALS.getValue())).isFalse();
assertThat(Operation.match(Collections.singletonList(""), "v2", Operation.EQUALS.getValue())).isFalse();
assertThat(Operation.match(Collections.singletonList("v1"), "", Operation.EQUALS.getValue())).isFalse();
assertThat(Operation.match(Collections.singletonList("v1"), null, Operation.EQUALS.getValue())).isFalse();
assertThat(Operation.match(Collections.emptyList(), "v1", Operation.EQUALS.getValue())).isFalse();
}
@Test
public void testNotEqual() {
Assert.assertFalse(Operation.match(Collections.singletonList("v1"), "v1", Operation.NOT_EQUALS.getValue()));
Assert.assertTrue(Operation.match(Collections.singletonList("v1"), "v2", Operation.NOT_EQUALS.getValue()));
Assert.assertTrue(Operation.match(Collections.singletonList(""), "v2", Operation.NOT_EQUALS.getValue()));
Assert.assertTrue(Operation.match(Collections.singletonList("v1"), "", Operation.NOT_EQUALS.getValue()));
Assert.assertTrue(Operation.match(Collections.singletonList("v1"), null, Operation.NOT_EQUALS.getValue()));
Assert.assertTrue(Operation.match(Collections.emptyList(), "v1", Operation.NOT_EQUALS.getValue()));
assertThat(Operation.match(Collections.singletonList("v1"), "v1", Operation.NOT_EQUALS.getValue())).isFalse();
assertThat(Operation.match(Collections.singletonList("v1"), "v2", Operation.NOT_EQUALS.getValue())).isTrue();
assertThat(Operation.match(Collections.singletonList(""), "v2", Operation.NOT_EQUALS.getValue())).isTrue();
assertThat(Operation.match(Collections.singletonList("v1"), "", Operation.NOT_EQUALS.getValue())).isTrue();
assertThat(Operation.match(Collections.singletonList("v1"), null, Operation.NOT_EQUALS.getValue())).isTrue();
assertThat(Operation.match(Collections.emptyList(), "v1", Operation.NOT_EQUALS.getValue())).isTrue();
}
@Test
public void testIn() {
Assert.assertTrue(Operation.match(Arrays.asList("v1", "v2", "v3"), "v1", Operation.IN.getValue()));
Assert.assertTrue(Operation.match(Arrays.asList("v1", "v2", "v3"), "v2", Operation.IN.getValue()));
Assert.assertFalse(Operation.match(Arrays.asList("v1", "v2", "v3"), "v4", Operation.IN.getValue()));
Assert.assertFalse(Operation.match(Arrays.asList("v1", "v2", "v3"), "", Operation.IN.getValue()));
Assert.assertFalse(Operation.match(Arrays.asList("v1", "v2", "v3"), null, Operation.IN.getValue()));
Assert.assertFalse(Operation.match(Collections.emptyList(), null, Operation.IN.getValue()));
assertThat(Operation.match(Arrays.asList("v1", "v2", "v3"), "v1", Operation.IN.getValue())).isTrue();
assertThat(Operation.match(Arrays.asList("v1", "v2", "v3"), "v2", Operation.IN.getValue())).isTrue();
assertThat(Operation.match(Arrays.asList("v1", "v2", "v3"), "v4", Operation.IN.getValue())).isFalse();
assertThat(Operation.match(Arrays.asList("v1", "v2", "v3"), "", Operation.IN.getValue())).isFalse();
assertThat(Operation.match(Arrays.asList("v1", "v2", "v3"), null, Operation.IN.getValue())).isFalse();
assertThat(Operation.match(Collections.emptyList(), null, Operation.IN.getValue())).isFalse();
}
@Test
public void testNotIn() {
Assert.assertFalse(Operation.match(Arrays.asList("v1", "v2", "v3"), "v1", Operation.NOT_IN.getValue()));
Assert.assertFalse(Operation.match(Arrays.asList("v1", "v2", "v3"), "v2", Operation.NOT_IN.getValue()));
Assert.assertTrue(Operation.match(Arrays.asList("v1", "v2", "v3"), "v4", Operation.NOT_IN.getValue()));
Assert.assertTrue(Operation.match(Arrays.asList("v1", "v2", "v3"), "", Operation.NOT_IN.getValue()));
Assert.assertTrue(Operation.match(Arrays.asList("v1", "v2", "v3"), null, Operation.NOT_IN.getValue()));
Assert.assertTrue(Operation.match(Collections.emptyList(), null, Operation.NOT_IN.getValue()));
assertThat(Operation.match(Arrays.asList("v1", "v2", "v3"), "v1", Operation.NOT_IN.getValue())).isFalse();
assertThat(Operation.match(Arrays.asList("v1", "v2", "v3"), "v2", Operation.NOT_IN.getValue())).isFalse();
assertThat(Operation.match(Arrays.asList("v1", "v2", "v3"), "v4", Operation.NOT_IN.getValue())).isTrue();
assertThat(Operation.match(Arrays.asList("v1", "v2", "v3"), "", Operation.NOT_IN.getValue())).isTrue();
assertThat(Operation.match(Arrays.asList("v1", "v2", "v3"), null, Operation.NOT_IN.getValue())).isTrue();
assertThat(Operation.match(Collections.emptyList(), null, Operation.NOT_IN.getValue())).isTrue();
}
@Test
public void testEmpty() {
Assert.assertTrue(Operation.match(Collections.singletonList("v1"), null, Operation.BLANK.getValue()));
Assert.assertTrue(Operation.match(Collections.singletonList("v1"), "", Operation.BLANK.getValue()));
Assert.assertTrue(Operation.match(Collections.emptyList(), null, Operation.BLANK.getValue()));
assertThat(Operation.match(Collections.singletonList("v1"), null, Operation.BLANK.getValue())).isTrue();
assertThat(Operation.match(Collections.singletonList("v1"), "", Operation.BLANK.getValue())).isTrue();
assertThat(Operation.match(Collections.emptyList(), null, Operation.BLANK.getValue())).isTrue();
}
@Test
public void testNotEmpty() {
Assert.assertFalse(Operation.match(Collections.singletonList("v1"), null, Operation.NOT_BLANK.getValue()));
Assert.assertFalse(Operation.match(Collections.singletonList("v1"), "", Operation.NOT_BLANK.getValue()));
Assert.assertFalse(Operation.match(Collections.emptyList(), null, Operation.NOT_BLANK.getValue()));
Assert.assertTrue(Operation.match(Collections.emptyList(), "v1", Operation.NOT_BLANK.getValue()));
assertThat(Operation.match(Collections.singletonList("v1"), null, Operation.NOT_BLANK.getValue())).isFalse();
assertThat(Operation.match(Collections.singletonList("v1"), "", Operation.NOT_BLANK.getValue())).isFalse();
assertThat(Operation.match(Collections.emptyList(), null, Operation.NOT_BLANK.getValue())).isFalse();
assertThat(Operation.match(Collections.emptyList(), "v1", Operation.NOT_BLANK.getValue())).isTrue();
}
@Test
public void testRegex() {
Assert.assertTrue(Operation.match(Collections.singletonList("v[1~10]"), "v1", Operation.REGEX.getValue()));
Assert.assertFalse(Operation.match(Collections.singletonList("v[1~10]"), "v12", Operation.REGEX.getValue()));
Assert.assertFalse(Operation.match(Collections.singletonList("v[1~10]*"), "v12", Operation.REGEX.getValue()));
assertThat(Operation.match(Collections.singletonList("v[1~10]"), "v1", Operation.REGEX.getValue())).isTrue();
assertThat(Operation.match(Collections.singletonList("v[1~10]"), "v12", Operation.REGEX.getValue())).isFalse();
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 org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.Assertions.assertThat;
/**
* test for {@link AddressUtils}.
*
* @author lepdou 2022-05-27
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class AddressUtilsTest {
@Test
public void testEmptyStr() {
List<String> result = AddressUtils.parseAddressList("");
Assert.assertEquals(0, result.size());
assertThat(result).isNotNull();
assertThat(result).isEmpty();
}
@Test
public void testNullStr() {
List<String> result = AddressUtils.parseAddressList(null);
Assert.assertEquals(0, result.size());
assertThat(result).isNotNull();
assertThat(result).isEmpty();
}
@Test
public void testOneStr() {
String host1 = "http://localhost";
List<String> result = AddressUtils.parseAddressList(host1);
Assert.assertEquals(1, result.size());
Assert.assertTrue(result.contains("localhost"));
assertThat(result.size()).isEqualTo(1);
assertThat(result).contains("localhost");
}
@Test
@ -59,9 +62,9 @@ public class AddressUtilsTest {
String host2 = "http://localhost2";
String host3 = "http://localhost3";
List<String> result = AddressUtils.parseAddressList(host1 + "," + host2 + "," + host3);
Assert.assertEquals(3, result.size());
Assert.assertTrue(result.contains("localhost"));
Assert.assertTrue(result.contains("localhost2"));
Assert.assertTrue(result.contains("localhost3"));
assertThat(result.size()).isEqualTo(3);
assertThat(result).contains("localhost");
assertThat(result).contains("localhost2");
assertThat(result).contains("localhost3");
}
}

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

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

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

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

@ -21,9 +21,9 @@ package com.tencent.cloud.common.util;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.Assertions.assertThat;
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
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class JacksonUtilsTest {
@Test

@ -20,28 +20,29 @@ package com.tencent.cloud.common.util;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.Assertions.assertThat;
/**
* test for {@link ResourceFileUtils}.
*
* @author lepdou 2022-05-27
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class ResourceFileUtilsTest {
@Test
public void testReadExistedFile() throws IOException {
String content = ResourceFileUtils.readFile("test.txt");
Assert.assertEquals("just for test", content);
assertThat(content).isEqualTo("just for test");
}
@Test
public void testReadNotExistedFile() throws IOException {
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>
<!-- Dependencies -->
<polaris.version>1.10.5</polaris.version>
<polaris.version>1.12.0</polaris.version>
<guava.version>31.0.1-jre</guava.version>
<logback.version>1.2.11</logback.version>
<mocktio.version>4.5.1</mocktio.version>
@ -81,7 +81,7 @@
<jackson.version>2.12.7</jackson.version>
<protobuf-java.version>3.21.7</protobuf-java.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-javadoc-plugin.verison>3.3.0</maven-javadoc-plugin.verison>
@ -272,8 +272,8 @@
<dependency>
<groupId>uk.org.webcompere</groupId>
<artifactId>system-stubs-junit4</artifactId>
<version>${system-stubs-junit4.version}</version>
<artifactId>system-stubs-jupiter</artifactId>
<version>${system-stubs-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>

@ -29,17 +29,18 @@ import com.tencent.polaris.api.pojo.ServiceInstances;
import com.tencent.polaris.api.pojo.ServiceKey;
import com.tencent.polaris.plugins.router.metadata.MetadataRouter;
import com.tencent.polaris.router.api.rpc.ProcessRoutersRequest;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
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}.
* @author lepdou 2022-07-12
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class FeatureEnvRouterRequestInterceptorTest {
@Test
@ -58,8 +59,8 @@ public class FeatureEnvRouterRequestInterceptorTest {
interceptor.apply(request, routerContext);
Map<String, String> metadataRouterLabels = request.getRouterMetadata().get(MetadataRouter.ROUTER_TYPE_METADATA);
Assert.assertEquals(1, metadataRouterLabels.size());
Assert.assertEquals("blue", metadataRouterLabels.get("featureenv"));
assertThat(metadataRouterLabels.size()).isEqualTo(1);
assertThat(metadataRouterLabels.get("featureenv")).isEqualTo("blue");
}
@Test
@ -79,8 +80,8 @@ public class FeatureEnvRouterRequestInterceptorTest {
interceptor.apply(request, routerContext);
Map<String, String> metadataRouterLabels = request.getRouterMetadata().get(MetadataRouter.ROUTER_TYPE_METADATA);
Assert.assertEquals(1, metadataRouterLabels.size());
Assert.assertEquals("blue", metadataRouterLabels.get("specify-env"));
assertThat(metadataRouterLabels.size()).isEqualTo(1);
assertThat(metadataRouterLabels.get("specify-env")).isEqualTo("blue");
}
@Test
@ -99,7 +100,7 @@ public class FeatureEnvRouterRequestInterceptorTest {
interceptor.apply(request, routerContext);
Map<String, String> metadataRouterLabels = request.getRouterMetadata().get(MetadataRouter.ROUTER_TYPE_METADATA);
Assert.assertEquals(1, metadataRouterLabels.size());
Assert.assertEquals("NOT_EXISTED_ENV", metadataRouterLabels.get("specify-env"));
assertThat(metadataRouterLabels.size()).isEqualTo(1);
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.configuration.api.core.ConfigFileService;
import com.tencent.polaris.configuration.factory.ConfigFileServiceFactory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
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;
/**
* Test for {@link SCGPluginsAutoConfiguration}.
* @author derek.yi 2022-11-03
*/
@RunWith(SpringRunner.class)
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = DEFINED_PORT, classes = SCGPluginsAutoConfigurationTest.TestApplication.class,
properties = {"server.port=8081", "spring.config.location = classpath:application-test.yml",
"spring.cloud.tencent.plugin.scg.staining.rule-staining.enabled = true"})
@ -54,11 +54,11 @@ public class SCGPluginsAutoConfigurationTest {
@Test
public void testAutoConfiguration() {
Assert.assertEquals(1, applicationContext.getBeansOfType(RuleStainingProperties.class).size());
Assert.assertEquals(1, applicationContext.getBeansOfType(StainingRuleManager.class).size());
Assert.assertEquals(1, applicationContext.getBeansOfType(TrafficStainingGatewayFilter.class).size());
Assert.assertEquals(1, applicationContext.getBeansOfType(RuleStainingExecutor.class).size());
Assert.assertEquals(1, applicationContext.getBeansOfType(RuleTrafficStainer.class).size());
assertThat(applicationContext.getBeansOfType(RuleStainingProperties.class).size()).isEqualTo(1);
assertThat(applicationContext.getBeansOfType(StainingRuleManager.class).size()).isEqualTo(1);
assertThat(applicationContext.getBeansOfType(TrafficStainingGatewayFilter.class).size()).isEqualTo(1);
assertThat(applicationContext.getBeansOfType(RuleStainingExecutor.class).size()).isEqualTo(1);
assertThat(applicationContext.getBeansOfType(RuleTrafficStainer.class).size()).isEqualTo(1);
}
@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.polaris.configuration.api.core.ConfigFile;
import com.tencent.polaris.configuration.api.core.ConfigFileService;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Mono;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ -55,9 +54,12 @@ import static org.mockito.Mockito.when;
* Test for {@link TrafficStainingGatewayFilter}.
* @author lepdou 2022-07-12
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class TrafficStainingGatewayFilterTest {
private final String testNamespace = "testNamespace";
private final String testGroup = "testGroup";
private final String testFileName = "rule.json";
@Mock
private GatewayFilterChain chain;
@Mock
@ -65,12 +67,8 @@ public class TrafficStainingGatewayFilterTest {
@Mock
private ConfigFileService configFileService;
private final String testNamespace = "testNamespace";
private final String testGroup = "testGroup";
private final String testFileName = "rule.json";
@BeforeClass
public static void before() {
@BeforeAll
static void beforeAll() {
Mockito.mockStatic(ApplicationContextAwareUtils.class);
when(ApplicationContextAwareUtils
.getProperties(any())).thenReturn("fooBar");
@ -108,10 +106,10 @@ public class TrafficStainingGatewayFilterTest {
TrafficStainingGatewayFilter filter = new TrafficStainingGatewayFilter(Arrays.asList(trafficStainer1, trafficStainer2));
Map<String, String> result = filter.getStainedLabels(exchange);
Assert.assertFalse(CollectionUtils.isEmpty(result));
Assert.assertEquals("v1", result.get("k1"));
Assert.assertEquals("v2", result.get("k2"));
Assert.assertEquals("v3", result.get("k3"));
assertThat(result).isNotEmpty();
assertThat(result.get("k1")).isEqualTo("v1");
assertThat(result.get("k2")).isEqualTo("v2");
assertThat(result.get("k3")).isEqualTo("v3");
}
@Test
@ -122,7 +120,7 @@ public class TrafficStainingGatewayFilterTest {
TrafficStainingGatewayFilter filter = new TrafficStainingGatewayFilter(null);
filter.filter(exchange, chain);
Map<String, String> map = metadataContext.getTransitiveMetadata();
Assert.assertTrue(CollectionUtils.isEmpty(map));
assertThat(map).isEmpty();
}
@Test
@ -169,8 +167,8 @@ public class TrafficStainingGatewayFilterTest {
filter.filter(exchange, chain);
Map<String, String> map = metadataContext.getTransitiveMetadata();
Assert.assertNotNull(map);
Assert.assertEquals(1, map.size());
Assert.assertEquals("blue", map.get("env"));
assertThat(map).isNotNull();
assertThat(map.size()).isEqualTo(1);
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.KVPair;
import com.tencent.cloud.common.rule.Operation;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.util.CollectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test for {@link RuleStainingExecutor}.
* @author lepdou 2022-07-12
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class RuleStainingExecutorTest {
@Test
@ -73,9 +73,9 @@ public class RuleStainingExecutorTest {
Map<String, String> stainedLabels = executor.execute(exchange, stainingRule);
Assert.assertNotNull(stainedLabels);
Assert.assertEquals(1, stainedLabels.size());
Assert.assertEquals("blue", stainedLabels.get("env"));
assertThat(stainedLabels).isNotNull();
assertThat(stainedLabels.size()).isEqualTo(1);
assertThat(stainedLabels.get("env")).isEqualTo("blue");
}
@Test
@ -110,8 +110,8 @@ public class RuleStainingExecutorTest {
Map<String, String> stainedLabels = executor.execute(exchange, stainingRule);
Assert.assertNotNull(stainedLabels);
Assert.assertEquals(0, stainedLabels.size());
assertThat(stainedLabels).isNotNull();
assertThat(stainedLabels.size()).isEqualTo(0);
}
@Test
@ -173,17 +173,17 @@ public class RuleStainingExecutorTest {
Map<String, String> stainedLabels = executor.execute(exchange, stainingRule);
Assert.assertNotNull(stainedLabels);
Assert.assertEquals(3, stainedLabels.size());
Assert.assertEquals("blue", stainedLabels.get("env"));
Assert.assertEquals("value1", stainedLabels.get("label1"));
Assert.assertEquals("value2", stainedLabels.get("label2"));
assertThat(stainedLabels).isNotNull();
assertThat(stainedLabels.size()).isEqualTo(3);
assertThat(stainedLabels.get("env")).isEqualTo("blue");
assertThat(stainedLabels.get("label1")).isEqualTo("value1");
assertThat(stainedLabels.get("label2")).isEqualTo("value2");
}
@Test
public void testNoStainingRule() {
RuleStainingExecutor executor = new RuleStainingExecutor();
Assert.assertTrue(CollectionUtils.isEmpty(executor.execute(null, null)));
Assert.assertTrue(CollectionUtils.isEmpty(executor.execute(null, new StainingRule())));
assertThat(executor.execute(null, null)).isEmpty();
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.ConfigFileService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
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.web.server.MockServerWebExchange;
import org.springframework.util.CollectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
/**
* Test for {@link RuleTrafficStainer}.
* @author derek.yi 2022-11-03
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class RuleTrafficStainerTest {
@Mock
private ConfigFileService configFileService;
private final String testNamespace = "testNamespace";
private final String testGroup = "testGroup";
private final String testFileName = "rule.json";
@Mock
private ConfigFileService configFileService;
@Test
public void testNoStainingRule() {
@ -64,7 +62,7 @@ public class RuleTrafficStainerTest {
RuleStainingExecutor ruleStainingExecutor = new RuleStainingExecutor();
RuleTrafficStainer ruleTrafficStainer = new RuleTrafficStainer(stainingRuleManager, ruleStainingExecutor);
Map<String, String> map = ruleTrafficStainer.apply(null);
Assert.assertTrue(CollectionUtils.isEmpty(map));
assertThat(map).isEmpty();
}
@Test
@ -105,8 +103,8 @@ public class RuleTrafficStainerTest {
MockServerWebExchange exchange = new MockServerWebExchange.Builder(request).build();
Map<String, String> map = ruleTrafficStainer.apply(exchange);
Assert.assertNotNull(map);
Assert.assertEquals(1, map.size());
Assert.assertEquals("blue", map.get("env"));
assertThat(map).isNotNull();
assertThat(map.size()).isEqualTo(1);
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.ConfigFileService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
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;
/**
* Test for {@link StainingRuleManager}.
* @author lepdou 2022-07-12
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class StainingRuleManagerTest {
@Mock
private ConfigFileService configFileService;
private final String testNamespace = "testNamespace";
private final String testGroup = "testGroup";
private final String testFileName = "rule.json";
@Mock
private ConfigFileService configFileService;
@Test
public void testNormalRule() {
@ -77,43 +76,45 @@ public class StainingRuleManagerTest {
StainingRule stainingRule = stainingRuleManager.getStainingRule();
Assert.assertNotNull(stainingRule);
Assert.assertEquals(1, stainingRule.getRules().size());
assertThat(stainingRule).isNotNull();
assertThat(stainingRule.getRules().size()).isEqualTo(1);
StainingRule.Rule rule = stainingRule.getRules().get(0);
Assert.assertEquals(1, rule.getConditions().size());
Assert.assertEquals(1, rule.getLabels().size());
assertThat(rule.getConditions().size()).isEqualTo(1);
assertThat(rule.getLabels().size()).isEqualTo(1);
}
@Test(expected = RuntimeException.class)
@Test
public void testWrongRule() {
RuleStainingProperties ruleStainingProperties = new RuleStainingProperties();
ruleStainingProperties.setNamespace(testNamespace);
ruleStainingProperties.setGroup(testGroup);
ruleStainingProperties.setFileName(testFileName);
ConfigFile configFile = Mockito.mock(ConfigFile.class);
when(configFile.getContent()).thenReturn("{\n"
+ " \"rules\":[\n"
+ " {\n"
+ " \"conditionsxxxx\":[\n"
+ " {\n"
+ " \"key\":\"${http.query.uid}\",\n"
+ " \"values\":[\"1000\"],\n"
+ " \"operation\":\"EQUALS\"\n"
+ " }\n"
+ " ],\n"
+ " \"labels\":[\n"
+ " {\n"
+ " \"key\":\"env\",\n"
+ " \"value\":\"blue\"\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ " ]\n"
+ "}");
when(configFileService.getConfigFile(testNamespace, testGroup, testFileName)).thenReturn(configFile);
new StainingRuleManager(ruleStainingProperties, configFileService);
assertThatCode(() -> {
RuleStainingProperties ruleStainingProperties = new RuleStainingProperties();
ruleStainingProperties.setNamespace(testNamespace);
ruleStainingProperties.setGroup(testGroup);
ruleStainingProperties.setFileName(testFileName);
ConfigFile configFile = Mockito.mock(ConfigFile.class);
when(configFile.getContent()).thenReturn("{\n"
+ " \"rules\":[\n"
+ " {\n"
+ " \"conditionsxxxx\":[\n"
+ " {\n"
+ " \"key\":\"${http.query.uid}\",\n"
+ " \"values\":[\"1000\"],\n"
+ " \"operation\":\"EQUALS\"\n"
+ " }\n"
+ " ],\n"
+ " \"labels\":[\n"
+ " {\n"
+ " \"key\":\"env\",\n"
+ " \"value\":\"blue\"\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ " ]\n"
+ "}");
when(configFileService.getConfigFile(testNamespace, testGroup, testFileName)).thenReturn(configFile);
new StainingRuleManager(ruleStainingProperties, configFileService);
}).isInstanceOf(RuntimeException.class);
}
@Test
@ -128,6 +129,6 @@ public class StainingRuleManagerTest {
when(configFileService.getConfigFile(testNamespace, testGroup, testFileName)).thenReturn(configFile);
StainingRuleManager stainingRuleManager = new StainingRuleManager(ruleStainingProperties, configFileService);
Assert.assertNull(stainingRuleManager.getStainingRule());
assertThat(stainingRuleManager.getStainingRule()).isNull();
}
}

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

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

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

Loading…
Cancel
Save