refactor:update to junit 5. (#866)

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

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

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

@ -26,8 +26,7 @@ import java.util.stream.Collectors;
import com.tencent.cloud.metadata.core.EncodeTransferMedataFeignInterceptor;
import com.tencent.cloud.metadata.core.EncodeTransferMedataRestTemplateInterceptor;
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;
@ -38,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}.
*
@ -54,15 +55,12 @@ public class MetadataTransferAutoConfigurationTest {
public void test1() {
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.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);
});
}
@ -73,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,7 +40,7 @@ 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"})
@ -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,8 +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();
}
}

@ -23,17 +23,17 @@ import com.tencent.cloud.common.constant.MetadataConstant;
import com.tencent.cloud.common.metadata.config.MetadataLocalProperties;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
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;
/**
@ -41,7 +41,7 @@ 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"})
@ -65,9 +65,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

@ -23,9 +23,8 @@ 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;
@ -33,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;
/**
@ -44,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", "spring.config.location = classpath:application-test.yml"})
@ -59,9 +59,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

@ -19,9 +19,8 @@ package com.tencent.cloud.metadata.core;
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;
@ -31,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;
/**
@ -43,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"})
@ -62,7 +62,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

@ -23,9 +23,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;
@ -35,9 +34,10 @@ 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;
/**
@ -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 = EncodeTransferMedataScgFilterTest.TestApplication.class,
properties = {"spring.config.location = classpath:application-test.yml",
"spring.main.web-application-type = reactive"})
@ -66,8 +66,8 @@ public class EncodeTransferMedataScgFilterTest {
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

@ -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"})
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;
@ -77,9 +78,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,22 +29,22 @@ 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;
/**
* test for {@link PolarisConfigFileLocator}.
*@author lepdou 2022-06-11
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class PolarisConfigFileLocatorTest {
private final String testNamespace = "testNamespace";
@ -88,9 +88,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
@ -131,9 +131,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
@ -180,8 +180,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");
}
}

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

@ -32,16 +32,16 @@ import com.tencent.cloud.polaris.config.spring.property.SpringValueRegistry;
import com.tencent.polaris.configuration.api.core.ChangeType;
import com.tencent.polaris.configuration.api.core.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();
}

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

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

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

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

@ -26,10 +26,10 @@ import com.tencent.cloud.polaris.config.adapter.MockedConfigKVFile;
import com.tencent.cloud.polaris.config.adapter.PolarisPropertySource;
import com.tencent.cloud.polaris.config.adapter.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,7 +45,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
*
* @author lepdou 2022-06-11
*/
@RunWith(SpringRunner.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 {

@ -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();
}
@ -92,19 +92,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);
});
}
@ -127,19 +127,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");
});
}
@ -163,31 +163,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();
}
}

@ -32,6 +32,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,9 +24,9 @@ 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;
@ -60,13 +60,13 @@ public class PolarisDiscoveryEndpointTest {
.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() {
@AfterAll
static void afterAll() {
if (null != namingServer) {
namingServer.terminate();
}

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

@ -25,14 +25,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;
@ -42,7 +42,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 {
@ -75,7 +75,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();

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

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

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

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

@ -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.test.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.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,13 +39,13 @@ import static org.mockito.Mockito.when;
*
* @author Haotian Zhang
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class RateLimitRuleLabelResolverTest {
private RateLimitRuleLabelResolver rateLimitRuleLabelResolver;
@Before
public void setUp() {
@BeforeEach
void setUp() {
ServiceRuleManager serviceRuleManager = mock(ServiceRuleManager.class);
when(serviceRuleManager.getServiceRateLimitRule(any(), anyString())).thenAnswer(invocationOnMock -> {
String serviceName = invocationOnMock.getArgument(1).toString();
@ -61,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.test.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", "spring.cloud.polaris.discovery.namespace=Test",
@ -72,8 +73,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
@ -85,15 +86,15 @@ public class CalleeControllerTests {
namingServer.getNamingService().batchAddInstances(serviceKey, PORT, 3, 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);
@ -124,12 +125,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 final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
@ -66,8 +66,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();
@ -83,7 +83,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,7 +71,8 @@ import static org.mockito.Mockito.when;
*
* @author Haotian Zhang, kaiy
*/
@RunWith(MockitoJUnitRunner.class)
@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 {
@ -82,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"));
@ -93,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();

@ -38,14 +38,16 @@ import com.tencent.polaris.ratelimit.api.rpc.QuotaResponse;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
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;
@ -68,7 +70,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"
})
@ -83,8 +86,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"));
@ -94,14 +97,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);
@ -238,6 +241,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();

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

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

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

@ -24,31 +24,30 @@ import java.util.List;
import java.util.Map;
import java.util.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;
/**
* test for {@link RouterRuleLabelResolver}.
*@author lepdou 2022-05-26
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class RouterRuleLabelResolverTest {
@Mock
private ServiceRuleManager serviceRuleManager;
private final String testNamespace = "testNamespace";
private final String testSourceService = "sourceService";
private final String testDstService = "dstService";
@Mock
private ServiceRuleManager serviceRuleManager;
@Test
public void test() {
@ -73,7 +72,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 +82,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);
}
}

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

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

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

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

@ -20,7 +20,7 @@ package com.tencent.cloud.polaris.router.config;
import com.tencent.cloud.common.metadata.config.MetadataAutoConfiguration;
import com.tencent.cloud.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.WebApplicationContextRunner;

@ -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;
@ -46,7 +46,7 @@ import static org.mockito.Mockito.when;
*
* @author lepdou 2022-07-25
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class PolarisRouterEndpointTest {
private static final String testDestService = "dstService";
@ -57,15 +57,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();
}
@ -92,27 +92,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);
}
}

@ -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;
@ -54,7 +53,7 @@ import static org.mockito.Mockito.when;
* test for {@link RouterLabelFeignInterceptor}.
* @author lepdou 2022-05-26
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class RouterLabelFeignInterceptorTest {
@Mock
@ -123,16 +122,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("");
}
}
}

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

@ -18,7 +18,6 @@
package com.tencent.cloud.polaris.router.resttemplate;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
@ -40,14 +39,12 @@ import com.tencent.cloud.common.util.expresstion.SpringWebExpressionLabelUtils;
import com.tencent.cloud.polaris.context.config.PolarisContextProperties;
import com.tencent.cloud.polaris.router.RouterRuleLabelResolver;
import com.tencent.cloud.polaris.router.spi.SpringWebRouterLabelResolver;
import org.junit.AfterClass;
import org.junit.BeforeClass;
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.core.Ordered;
import org.springframework.http.HttpHeaders;
@ -63,6 +60,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ -71,12 +69,12 @@ import static org.mockito.Mockito.when;
*
* @author liuye, Haotian Zhang
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class RouterLabelRestTemplateInterceptorTest {
private static MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils;
private static MockedStatic<MetadataContextHolder> mockedMetadataContextHolder;
private static final String testNamespaceAndService = "testNamespaceAndService";
@Mock
private SpringWebRouterLabelResolver routerLabelResolver;
@Mock
private StaticMetadataManager staticMetadataManager;
@ -88,91 +86,83 @@ public class RouterLabelRestTemplateInterceptorTest {
@Mock
private ClientHttpRequestExecution clientHttpRequestExecution;
@BeforeClass
public static void beforeClass() {
mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class);
mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString()))
.thenReturn("callerService");
mockedMetadataContextHolder = Mockito.mockStatic(MetadataContextHolder.class);
}
@AfterClass
public static void afterClass() {
mockedApplicationContextAwareUtils.close();
mockedMetadataContextHolder.close();
}
@Test
public void testRouterContext() throws Exception {
String callerService = "callerService";
String calleeService = "calleeService";
HttpRequest request = new MockedHttpRequest("http://" + calleeService + "/user/get");
// mock local metadata
Map<String, String> localMetadata = new HashMap<>();
localMetadata.put("k1", "v1");
localMetadata.put("k2", "v2");
when(staticMetadataManager.getMergedStaticMetadata()).thenReturn(localMetadata);
Map<String, String> routerLabels = new HashMap<>(localMetadata);
// mock expression rule labels
Set<String> expressionKeys = new HashSet<>();
expressionKeys.add("${http.method}");
expressionKeys.add("${http.uri}");
when(routerRuleLabelResolver.getExpressionLabelKeys(callerService, callerService, calleeService)).thenReturn(expressionKeys);
routerLabels.putAll(SpringWebExpressionLabelUtils.resolve(request, expressionKeys));
// mock custom resolved from request
Map<String, String> customResolvedLabels = new HashMap<>();
customResolvedLabels.put("k2", "v22");
customResolvedLabels.put("k4", "v4");
when(routerLabelResolver.resolve(request, null, expressionKeys)).thenReturn(customResolvedLabels);
routerLabels.putAll(customResolvedLabels);
MetadataContext metadataContext = Mockito.mock(MetadataContext.class);
// mock transitive metadata
Map<String, String> transitiveLabels = new HashMap<>();
transitiveLabels.put("k1", "v1");
transitiveLabels.put("k2", "v22");
when(metadataContext.getTransitiveMetadata()).thenReturn(transitiveLabels);
routerLabels.putAll(transitiveLabels);
mockedMetadataContextHolder.when(MetadataContextHolder::get).thenReturn(metadataContext);
RouterLabelRestTemplateInterceptor routerLabelRestTemplateInterceptor = new RouterLabelRestTemplateInterceptor(
Collections.singletonList(routerLabelResolver), staticMetadataManager, routerRuleLabelResolver, polarisContextProperties);
ClientHttpResponse mockedResponse = new MockClientHttpResponse(new byte[] {}, HttpStatus.OK);
when(clientHttpRequestExecution.execute(eq(request), any())).thenReturn(mockedResponse);
assertThat(routerLabelRestTemplateInterceptor.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE);
routerLabelRestTemplateInterceptor.intercept(request, null, clientHttpRequestExecution);
verify(staticMetadataManager).getMergedStaticMetadata();
verify(routerRuleLabelResolver).getExpressionLabelKeys(callerService, callerService, calleeService);
verify(routerLabelResolver).resolve(request, null, expressionKeys);
Map<String, String> headers = JacksonUtils.deserialize2Map(URLDecoder.decode(Objects.requireNonNull(request.getHeaders()
.get(RouterConstant.ROUTER_LABEL_HEADER)).get(0), "UTF-8"));
assertThat("v1").isEqualTo(headers.get("k1"));
assertThat("v22").isEqualTo(headers.get("k2"));
assertThat("v4").isEqualTo(headers.get("k4"));
assertThat("GET").isEqualTo(headers.get("${http.method}"));
assertThat("/user/get").isEqualTo(headers.get("${http.uri}"));
String encodedLabelsContent;
try {
encodedLabelsContent = URLEncoder.encode(JacksonUtils.serialize2Json(routerLabels), UTF_8);
try (
MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils = mockStatic(ApplicationContextAwareUtils.class);
MockedStatic<MetadataContextHolder> mockedMetadataContextHolder = mockStatic(MetadataContextHolder.class)
) {
mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString()))
.thenReturn(testNamespaceAndService);
String calleeService = "calleeService";
HttpRequest request = new MockedHttpRequest("http://" + calleeService + "/user/get");
// mock local metadata
Map<String, String> localMetadata = new HashMap<>();
localMetadata.put("k1", "v1");
localMetadata.put("k2", "v2");
when(staticMetadataManager.getMergedStaticMetadata()).thenReturn(localMetadata);
Map<String, String> routerLabels = new HashMap<>(localMetadata);
// mock expression rule labels
Set<String> expressionKeys = new HashSet<>();
expressionKeys.add("${http.method}");
expressionKeys.add("${http.uri}");
when(routerRuleLabelResolver.getExpressionLabelKeys(testNamespaceAndService, testNamespaceAndService, calleeService)).thenReturn(expressionKeys);
routerLabels.putAll(SpringWebExpressionLabelUtils.resolve(request, expressionKeys));
// mock custom resolved from request
Map<String, String> customResolvedLabels = new HashMap<>();
customResolvedLabels.put("k2", "v22");
customResolvedLabels.put("k4", "v4");
when(routerLabelResolver.resolve(request, null, expressionKeys)).thenReturn(customResolvedLabels);
routerLabels.putAll(customResolvedLabels);
MetadataContext metadataContext = Mockito.mock(MetadataContext.class);
// mock transitive metadata
Map<String, String> transitiveLabels = new HashMap<>();
transitiveLabels.put("k1", "v1");
transitiveLabels.put("k2", "v22");
when(metadataContext.getTransitiveMetadata()).thenReturn(transitiveLabels);
routerLabels.putAll(transitiveLabels);
mockedMetadataContextHolder.when(MetadataContextHolder::get).thenReturn(metadataContext);
RouterLabelRestTemplateInterceptor routerLabelRestTemplateInterceptor = new RouterLabelRestTemplateInterceptor(
Collections.singletonList(routerLabelResolver), staticMetadataManager, routerRuleLabelResolver, polarisContextProperties);
ClientHttpResponse mockedResponse = new MockClientHttpResponse(new byte[] {}, HttpStatus.OK);
when(clientHttpRequestExecution.execute(eq(request), any())).thenReturn(mockedResponse);
assertThat(routerLabelRestTemplateInterceptor.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE);
routerLabelRestTemplateInterceptor.intercept(request, null, clientHttpRequestExecution);
verify(staticMetadataManager).getMergedStaticMetadata();
verify(routerRuleLabelResolver).getExpressionLabelKeys(testNamespaceAndService, testNamespaceAndService, calleeService);
verify(routerLabelResolver).resolve(request, null, expressionKeys);
Map<String, String> headers = JacksonUtils.deserialize2Map(URLDecoder.decode(Objects.requireNonNull(request.getHeaders()
.get(RouterConstant.ROUTER_LABEL_HEADER)).get(0), "UTF-8"));
assertThat("v1").isEqualTo(headers.get("k1"));
assertThat("v22").isEqualTo(headers.get("k2"));
assertThat("v4").isEqualTo(headers.get("k4"));
assertThat("GET").isEqualTo(headers.get("${http.method}"));
assertThat("/user/get").isEqualTo(headers.get("${http.uri}"));
String encodedLabelsContent;
try {
encodedLabelsContent = URLEncoder.encode(JacksonUtils.serialize2Json(routerLabels), UTF_8);
}
catch (UnsupportedEncodingException e) {
throw new RuntimeException("unsupported charset exception " + UTF_8);
}
assertThat(mockedResponse.getHeaders().get(RouterConstant.ROUTER_LABEL_HEADER).get(0))
.isEqualTo(encodedLabelsContent);
}
catch (UnsupportedEncodingException e) {
throw new RuntimeException("unsupported charset exception " + UTF_8);
}
assertThat(mockedResponse.getHeaders().get(RouterConstant.ROUTER_LABEL_HEADER).get(0))
.isEqualTo(encodedLabelsContent);
}
static class MockedHttpRequest implements HttpRequest {

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

@ -102,7 +102,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,35 +26,32 @@ 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() {
@ -70,20 +67,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
@ -99,21 +96,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
@ -132,53 +129,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.assertTrue(CollectionUtils.isEmpty(metadataManager.getAllEnvMetadata()));
Assert.assertTrue(CollectionUtils.isEmpty(metadataManager.getEnvTransitiveMetadata()));
assertThat(metadataManager.getAllEnvMetadata()).isEmpty();
assertThat(metadataManager.getEnvTransitiveMetadata()).isEmpty();
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"));
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
*/
@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,13 +73,13 @@
<revision>1.10.0-2022.0.1-SNAPSHOT</revision>
<!-- Dependencies -->
<polaris.version>1.10.5</polaris.version>
<polaris.version>1.11.0-SNAPSHOT</polaris.version>
<guava.version>31.1-jre</guava.version>
<mocktio.version>4.9.0</mocktio.version>
<byte-buddy.version>1.12.19</byte-buddy.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 -->
<flatten-maven-plugin.version>1.3.0</flatten-maven-plugin.version>
@ -231,8 +231,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,18 +29,19 @@ 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, Hoatian Zhang
*/
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class FeatureEnvRouterRequestInterceptorTest {
@Test
@ -59,8 +60,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
@ -80,8 +81,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
@ -100,7 +101,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

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

Loading…
Cancel
Save