diff --git a/CHANGELOG.md b/CHANGELOG.md index 04379955d..fde6f9a82 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,3 +24,4 @@ - [feat:support TSF certificate manager.](https://github.com/Tencent/spring-cloud-tencent/pull/1715) - [feat:support tsf unit.](https://github.com/Tencent/spring-cloud-tencent/pull/1681) - [feat: support service registry and discovery with Polaris and Nacos](https://github.com/Tencent/spring-cloud-tencent/pull/1718) +- [test:add junit tests to sct-common.](https://github.com/Tencent/spring-cloud-tencent/pull/1726) diff --git a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/rule/Condition.java b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/rule/Condition.java deleted file mode 100644 index 98e826e99..000000000 --- a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/rule/Condition.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Tencent is pleased to support the open source community by making spring-cloud-tencent available. - * - * Copyright (C) 2021 Tencent. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.tencent.cloud.common.rule; - -import java.util.List; - -/** - * Condition expression. - * @author lepdou 2022-07-06 - */ -public class Condition { - - private String key; - private String operation; - private List values; - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public List getValues() { - return values; - } - - public void setValues(List values) { - this.values = values; - } - - public String getOperation() { - return operation; - } - - public void setOperation(String operation) { - this.operation = operation; - } - - @Override - public String toString() { - return "Condition{" + - "key='" + key + '\'' + - ", values='" + values + '\'' + - ", operation='" + operation + '\'' + - '}'; - } -} diff --git a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/rule/ConditionUtils.java b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/rule/ConditionUtils.java deleted file mode 100644 index 6c3ff75dc..000000000 --- a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/rule/ConditionUtils.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Tencent is pleased to support the open source community by making spring-cloud-tencent available. - * - * Copyright (C) 2021 Tencent. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.tencent.cloud.common.rule; - -import java.util.List; -import java.util.Map; - -/** - * The util for condition expression. - * @author lepdou 2022-07-11 - */ -public final class ConditionUtils { - - private ConditionUtils() { - } - - public static boolean match(Map actualValues, List conditions) { - for (Condition condition : conditions) { - List expectedValues = condition.getValues(); - String operation = condition.getOperation(); - String key = condition.getKey(); - String actualValue = actualValues.get(key); - - if (!Operation.match(expectedValues, actualValue, operation)) { - return false; - } - } - return true; - } -} diff --git a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/rule/KVPairUtils.java b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/rule/KVPairUtils.java deleted file mode 100644 index 12210cb4a..000000000 --- a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/rule/KVPairUtils.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Tencent is pleased to support the open source community by making spring-cloud-tencent available. - * - * Copyright (C) 2021 Tencent. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.tencent.cloud.common.rule; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.util.CollectionUtils; - -/** - * The util for key/value pair. - * @author lepdou 2022-07-11 - */ -public final class KVPairUtils { - - private KVPairUtils() { - } - - public static Map toMap(List labels) { - if (CollectionUtils.isEmpty(labels)) { - return Collections.emptyMap(); - } - - Map result = new HashMap<>(); - labels.forEach(label -> { - result.put(label.getKey(), label.getValue()); - }); - - return result; - } -} diff --git a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/rule/Operation.java b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/rule/Operation.java deleted file mode 100644 index 2259da45c..000000000 --- a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/rule/Operation.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Tencent is pleased to support the open source community by making spring-cloud-tencent available. - * - * Copyright (C) 2021 Tencent. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.tencent.cloud.common.rule; - -import java.util.List; -import java.util.regex.Pattern; - -import com.tencent.polaris.api.utils.CollectionUtils; -import com.tencent.polaris.api.utils.StringUtils; - - -/** - * The condition operation. - * @author lepdou 2022-07-11 - */ -public enum Operation { - - /** - * case sensitive string equals. - */ - EQUALS("EQUALS"), - /** - * case sensitive string not equals. - */ - NOT_EQUALS("NOT_EQUALS"), - /** - * whether element in collection. - */ - IN("IN"), - /** - * whether element not in collection. - */ - NOT_IN("NOT_IN"), - /** - * regex operation. - */ - REGEX("REGEX"), - /** - * whether element is blank. - */ - BLANK("BLANK"), - /** - * whether element is not blank. - */ - NOT_BLANK("NOT_BLANK"); - - private final String value; - - Operation(String value) { - this.value = value; - } - - public static boolean match(List expectedValues, String actualValue, String rawOperation) { - String firstExpectedValue = null; - if (!CollectionUtils.isEmpty(expectedValues)) { - firstExpectedValue = expectedValues.get(0); - } - - switch (getOperation(rawOperation)) { - case EQUALS: - return firstExpectedValue != null && StringUtils.equals(actualValue, firstExpectedValue); - case NOT_EQUALS: - return firstExpectedValue == null || !StringUtils.equals(actualValue, firstExpectedValue); - case BLANK: - return StringUtils.isBlank(actualValue); - case NOT_BLANK: - return !StringUtils.isBlank(actualValue); - case IN: - if (CollectionUtils.isEmpty(expectedValues)) { - return false; - } - return expectedValues.contains(actualValue); - case NOT_IN: - if (CollectionUtils.isEmpty(expectedValues)) { - return true; - } - return !expectedValues.contains(actualValue); - case REGEX: - if (firstExpectedValue == null) { - return false; - } - Pattern r = Pattern.compile(firstExpectedValue); - return r.matcher(actualValue).matches(); - default: - return false; - } - } - - public static Operation getOperation(String operation) { - if (StringUtils.equalsIgnoreCase(operation, EQUALS.value)) { - return EQUALS; - } - if (StringUtils.equalsIgnoreCase(operation, NOT_EQUALS.value)) { - return NOT_EQUALS; - } - if (StringUtils.equalsIgnoreCase(operation, IN.value)) { - return IN; - } - if (StringUtils.equalsIgnoreCase(operation, NOT_IN.value)) { - return NOT_IN; - } - if (StringUtils.equalsIgnoreCase(operation, REGEX.value)) { - return REGEX; - } - if (StringUtils.equalsIgnoreCase(operation, BLANK.value)) { - return BLANK; - } - if (StringUtils.equalsIgnoreCase(operation, NOT_BLANK.value)) { - return NOT_BLANK; - } - throw new RuntimeException("Unsupported operation. operation = " + operation); - } - - public String getValue() { - return value; - } -} diff --git a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/BeanFactoryUtils.java b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/BeanFactoryUtils.java index 70021c2c4..7fcdcfae1 100644 --- a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/BeanFactoryUtils.java +++ b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/BeanFactoryUtils.java @@ -21,6 +21,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import com.tencent.polaris.annonation.JustForTest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -73,6 +74,11 @@ public final class BeanFactoryUtils implements BeanFactoryAware { return new ArrayList<>(beanMap.values()); } + @JustForTest + static void resetBeanFactory() { + BeanFactoryUtils.beanFactory = null; + } + @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { BeanFactoryUtils.beanFactory = beanFactory; diff --git a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/async/PolarisAsyncConfigurationTest.java b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/async/PolarisAsyncConfigurationTest.java new file mode 100644 index 000000000..3c2e0a640 --- /dev/null +++ b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/async/PolarisAsyncConfigurationTest.java @@ -0,0 +1,67 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.cloud.common.async; + +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.Test; + +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.task.TaskExecutor; +import org.springframework.scheduling.annotation.Async; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link PolarisAsyncConfiguration}. + * + * @author Haotian Zhang + */ +public class PolarisAsyncConfigurationTest { + + private final ApplicationContextRunner contextRunnerWithoutPolarisAsyncConfiguration + = new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(PolarisAsyncConfiguration.class)); + + private final ApplicationContextRunner contextRunnerWithPolarisAsyncConfiguration + = new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(PolarisAsyncConfiguration.class, TestConfiguration.class)) + .withPropertyValues("spring.cloud.tencent.async.enabled=true"); + + @Test + public void testAsyncExecutor() { + this.contextRunnerWithoutPolarisAsyncConfiguration.run(context -> { + assertThat(context).doesNotHaveBean(PolarisAsyncConfiguration.class); + }); + + this.contextRunnerWithPolarisAsyncConfiguration.run(context -> { + assertThat(context).hasSingleBean(PolarisAsyncConfiguration.class); + assertThat(context).hasSingleBean(TaskExecutor.class); + String[] executorNames = context.getBeanNamesForType(TaskExecutor.class); + List executorNameList = Arrays.asList(executorNames); + assertThat(executorNameList).contains("polarisAsyncExecutor"); + }); + } + + @Configuration + @Async + protected static class TestConfiguration { + + } +} diff --git a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/rule/OperationTest.java b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/rule/OperationTest.java deleted file mode 100644 index c695c86fe..000000000 --- a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/rule/OperationTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Tencent is pleased to support the open source community by making spring-cloud-tencent available. - * - * Copyright (C) 2021 Tencent. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * Unless required by applicable law or agreed to in writing, software distributed - * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -package com.tencent.cloud.common.rule; - -import java.util.Arrays; -import java.util.Collections; - -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 - */ -@ExtendWith(MockitoExtension.class) -public class OperationTest { - - @Test - public void testEqual() { - 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() { - 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() { - 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() { - 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() { - 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() { - 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() { - 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(); - } -} diff --git a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/ApplicationContextAwareUtilsTest.java b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/ApplicationContextAwareUtilsTest.java new file mode 100644 index 000000000..56c969d02 --- /dev/null +++ b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/ApplicationContextAwareUtilsTest.java @@ -0,0 +1,66 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.cloud.common.util; + +import com.tencent.cloud.common.async.PolarisAsyncConfiguration; +import org.junit.jupiter.api.Test; + +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * Test for {@link ApplicationContextAwareUtils}. + * + * @author Haotian Zhang + */ +public class ApplicationContextAwareUtilsTest { + + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(ApplicationContextAwareUtils.class)) + .withPropertyValues("key1=value1"); + + @Test + public void testApplicationContextAwareUtils() { + this.contextRunner.run(context -> { + assertThat(context).hasSingleBean(ApplicationContextAwareUtils.class); + assertThat(ApplicationContextAwareUtils.getApplicationContext()).isNotNull(); + + // test getProperties + assertThat(ApplicationContextAwareUtils.getProperties("key1")).isEqualTo("value1"); + assertThat(ApplicationContextAwareUtils.getProperties("key2")).isNull(); + + // test getProperties with default value + assertThat(ApplicationContextAwareUtils.getProperties("key1", "defaultValue")).isEqualTo("value1"); + assertThat(ApplicationContextAwareUtils.getProperties("key2", "defaultValue")).isEqualTo("defaultValue"); + + // test getBean + assertThat(ApplicationContextAwareUtils.getBean(ApplicationContextAwareUtils.class)).isNotNull(); + assertThatThrownBy(() -> { + ApplicationContextAwareUtils.getBean(PolarisAsyncConfiguration.class); + }).isInstanceOf(NoSuchBeanDefinitionException.class); + + // test getBeanIfExists + assertThat(ApplicationContextAwareUtils.getBeanIfExists(ApplicationContextAwareUtils.class)).isNotNull(); + assertThat(ApplicationContextAwareUtils.getBeanIfExists(PolarisAsyncConfiguration.class)).isNull(); + }); + } +} diff --git a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/BeanFactoryUtilsTest.java b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/BeanFactoryUtilsTest.java index 2c131cc9a..09a930ec0 100644 --- a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/BeanFactoryUtilsTest.java +++ b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/BeanFactoryUtilsTest.java @@ -23,12 +23,15 @@ import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.core.ResolvableType; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; /** * Test for {@link BeanFactoryUtils}. @@ -54,6 +57,19 @@ public class BeanFactoryUtilsTest { .hasMessageContaining("bean factory not support get list bean."); } + @Test + public void testResolve() { + ConfigurableBeanFactory beanFactory = mock(ConfigurableBeanFactory.class); + when(beanFactory.resolveEmbeddedValue("${foo}")).thenReturn("bar"); + when(beanFactory.resolveEmbeddedValue("${bar}")).thenThrow(new RuntimeException("mock exception")); + + BeanFactoryUtils beanFactoryUtils = new BeanFactoryUtils(); + beanFactoryUtils.setBeanFactory(beanFactory); + assertThat(BeanFactoryUtils.resolve("${foo}")).isEqualTo("bar"); + assertThat(BeanFactoryUtils.resolve("${bar}")).isNull(); + BeanFactoryUtils.resetBeanFactory(); + } + static class Foo { } diff --git a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/GzipUtilTest.java b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/GzipUtilTest.java new file mode 100644 index 000000000..b6bb8a9ed --- /dev/null +++ b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/GzipUtilTest.java @@ -0,0 +1,57 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.cloud.common.util; + +import java.io.IOException; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.fail; + +/** + * Tests for {@link GzipUtil}. + * + * @author Haotian Zhang + */ +public class GzipUtilTest { + + @Test + public void testGzip() { + try { + String testData = "1234567890"; + String compressed = GzipUtil.compressBase64Encode(testData, "UTF-8"); + String decompressed = GzipUtil.base64DecodeDecompress(compressed, "UTF-8"); + assertThat(decompressed).isEqualTo(testData); + + assertThatThrownBy(() -> { + GzipUtil.compressBase64Encode(testData, "UTF-7"); + }).isInstanceOf(IOException.class); + + compressed = GzipUtil.compressBase64Encode(testData.getBytes(), "UTF-8"); + decompressed = GzipUtil.base64DecodeDecompress(compressed, "UTF-8"); + assertThat(decompressed).isEqualTo(testData); + decompressed = GzipUtil.base64DecodeDecompress(compressed); + assertThat(decompressed).isEqualTo(testData); + } + catch (IOException e) { + fail("Gzip compress or decompress failed", e); + } + } +} diff --git a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/JacksonUtilsTest.java b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/JacksonUtilsTest.java index c1ef01b45..e31efb849 100644 --- a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/JacksonUtilsTest.java +++ b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/JacksonUtilsTest.java @@ -18,12 +18,15 @@ package com.tencent.cloud.common.util; import java.util.HashMap; +import java.util.List; import java.util.Map; +import com.fasterxml.jackson.core.type.TypeReference; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.tsf.core.entity.Tag; import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; @@ -47,6 +50,24 @@ public class JacksonUtilsTest { assertThat(StringUtils.trimAllWhitespace(JacksonUtils.serialize2Json(sourceMap, true))).isEqualTo("{\"k1\":\"v1\",\"k2\":\"v2\",\"k3\":\"v3\"}"); } + @Test + public void testDeserialize() { + Tag originalTag = new Tag("k1", "v1"); + Tag deserializedTag = JacksonUtils.deserialize("{\"k\":\"k1\",\"v\":\"v1\"}", Tag.class); + assertThat(deserializedTag).isEqualTo(originalTag); + assertThat(deserializedTag.hashCode()).isEqualTo(originalTag.hashCode()); + assertThat(deserializedTag.toString()).isEqualTo(originalTag.toString()); + + deserializedTag = JacksonUtils.deserialize("{\"k\":\"k2\",\"v\":\"v2\"}", new TypeReference<>() { }); + assertThat(deserializedTag.getKey()).isEqualTo("k2"); + assertThat(deserializedTag.getValue()).isEqualTo("v2"); + + assertThatThrownBy(() -> JacksonUtils.deserialize("{", Tag.class)) + .isInstanceOf(RuntimeException.class).hasMessage("Json to object failed."); + assertThatThrownBy(() -> JacksonUtils.deserialize("{", new TypeReference() { })) + .isInstanceOf(RuntimeException.class).hasMessage("Json to object failed."); + } + @Test public void testDeserialize2Map() { String jsonStr = "{\"k1\":\"v1\",\"k2\":\"v2\",\"k3\":\"v3\"}"; @@ -70,4 +91,19 @@ public class JacksonUtilsTest { assertThatThrownBy(() -> JacksonUtils.deserialize2Map(jsonStr)) .isExactlyInstanceOf(RuntimeException.class).hasMessage("Json to map failed."); } + + @Test + public void testDeserializeCollection() { + String jsonStr = "[{\"k\":\"k1\",\"v\":\"v1\"},{\"k\":\"k2\",\"v\":\"v2\"}]"; + List list = JacksonUtils.deserializeCollection(jsonStr, Tag.class); + assertThat(list).isNotNull(); + assertThat(list.size()).isEqualTo(2); + assertThat(list.get(0).getKey()).isEqualTo("k1"); + assertThat(list.get(0).getValue()).isEqualTo("v1"); + assertThat(list.get(1).getKey()).isEqualTo("k2"); + assertThat(list.get(1).getValue()).isEqualTo("v2"); + + assertThatThrownBy(() -> JacksonUtils.deserializeCollection("{", Tag.class)) + .isExactlyInstanceOf(RuntimeException.class); + } } diff --git a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/rule/KVPair.java b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/OtUtilsTest.java similarity index 56% rename from spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/rule/KVPair.java rename to spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/OtUtilsTest.java index a172ad230..a56db38c8 100644 --- a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/rule/KVPair.java +++ b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/OtUtilsTest.java @@ -15,39 +15,27 @@ * specific language governing permissions and limitations under the License. */ -package com.tencent.cloud.common.rule; +package com.tencent.cloud.common.util; -/** - * Key/value pair. - * @author lepdou 2022-07-06 - */ -public class KVPair { - - private String key; - private String value; +import org.junit.jupiter.api.Test; - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } +import static com.tencent.cloud.common.util.OtUtils.OTEL_RESOURCE_ATTRIBUTES; +import static org.assertj.core.api.Assertions.assertThat; - public String getValue() { - return value; - } +/** + * Test for {@link OtUtils}. + * + * @author Haotian Zhang + */ +public class OtUtilsTest { - public void setValue(String value) { - this.value = value; - } + @Test + public void testOtUtils() { + String serviceName = "test-service"; + System.setProperty(OTEL_RESOURCE_ATTRIBUTES, "service.name=" + serviceName); + OtUtils.setOtServiceNameIfNeeded(serviceName); - @Override - public String toString() { - return "KVPair{" + - "key='" + key + '\'' + - ", value='" + value + '\'' + - '}'; + assertThat(OtUtils.getOtServiceName()).isEqualTo(serviceName); } } diff --git a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/PolarisCompletableFutureUtilsTest.java b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/PolarisCompletableFutureUtilsTest.java new file mode 100644 index 000000000..70fd5fc2f --- /dev/null +++ b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/PolarisCompletableFutureUtilsTest.java @@ -0,0 +1,78 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.cloud.common.util; + +import com.tencent.cloud.common.metadata.MetadataContext; +import com.tencent.cloud.common.metadata.MetadataContextHolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link PolarisCompletableFutureUtils}. + * + * @author Haotian Zhang + */ +public class PolarisCompletableFutureUtilsTest { + + @BeforeEach + void setUp() { + MetadataContext metadataContext = MetadataContextHolder.get(); + metadataContext.putContext(MetadataContext.FRAGMENT_TRANSITIVE, "key1", "value1"); + } + + @AfterEach + void tearDown() { + MetadataContextHolder.remove(); + } + + @Test + public void testSupplyAsync() { + PolarisCompletableFutureUtils.supplyAsync(() -> { + assertThat(MetadataContextHolder.get() + .getContext(MetadataContext.FRAGMENT_TRANSITIVE, "key1")).isEqualTo("value1"); + assertThat(MetadataContextHolder.get() + .getContext(MetadataContext.FRAGMENT_TRANSITIVE, "key2")).isNull(); + MetadataContextHolder.get().putContext(MetadataContext.FRAGMENT_TRANSITIVE, "key2", "value2"); + return "test"; + }).thenAccept(result -> { + assertThat(result).isEqualTo("test"); + }).join(); + assertThat(MetadataContextHolder.get() + .getContext(MetadataContext.FRAGMENT_TRANSITIVE, "key1")).isEqualTo("value1"); + assertThat(MetadataContextHolder.get() + .getContext(MetadataContext.FRAGMENT_TRANSITIVE, "key2")).isEqualTo("value2"); + } + + @Test + public void testRunAsync() { + PolarisCompletableFutureUtils.runAsync(() -> { + assertThat(MetadataContextHolder.get() + .getContext(MetadataContext.FRAGMENT_TRANSITIVE, "key1")).isEqualTo("value1"); + assertThat(MetadataContextHolder.get() + .getContext(MetadataContext.FRAGMENT_TRANSITIVE, "key2")).isNull(); + MetadataContextHolder.get().putContext(MetadataContext.FRAGMENT_TRANSITIVE, "key2", "value3"); + }).join(); + assertThat(MetadataContextHolder.get() + .getContext(MetadataContext.FRAGMENT_TRANSITIVE, "key1")).isEqualTo("value1"); + assertThat(MetadataContextHolder.get() + .getContext(MetadataContext.FRAGMENT_TRANSITIVE, "key2")).isEqualTo("value3"); + } +} diff --git a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/ReflectionUtilsTest.java b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/ReflectionUtilsTest.java new file mode 100644 index 000000000..70c956aaa --- /dev/null +++ b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/ReflectionUtilsTest.java @@ -0,0 +1,67 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.cloud.common.util; + +import java.lang.reflect.Field; +import java.util.Set; + +import org.junit.jupiter.api.Test; + +import org.springframework.tsf.core.entity.Tag; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link ReflectionUtils}. + * + * @author Haotian Zhang + */ +public class ReflectionUtilsTest { + + @Test + public void testWritableBeanField() { + Field field = ReflectionUtils.findField(Tag.class, "key"); + assertThat(field).isNotNull(); + assertThat(ReflectionUtils.writableBeanField(field)).isTrue(); + } + + @Test + public void testCapitalize() { + String name = "test"; + assertThat(ReflectionUtils.capitalize(name)).isEqualTo("Test"); + + String gender = ""; + assertThat(ReflectionUtils.capitalize(gender)).isEqualTo(""); + } + + @Test + public void testGetFieldValue() { + Tag tag = new Tag("key", "value"); + assertThat(ReflectionUtils.getFieldValue(tag, "key")).isEqualTo("key"); + assertThat(ReflectionUtils.getFieldValue(tag, "value")).isEqualTo("value"); + assertThat(ReflectionUtils.getFieldValue(tag, "flags")).isNotNull().isInstanceOf(Set.class); + } + + @Test + public void testSetFieldValue() { + Tag tag = new Tag("key", null); + ReflectionUtils.setFieldValue(tag, "key", "newKey"); + assertThat(ReflectionUtils.getFieldValue(tag, "key")).isEqualTo("newKey"); + ReflectionUtils.setFieldValue(tag, "value1", "newValue"); + } +} diff --git a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/TsfTagUtilsTest.java b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/TsfTagUtilsTest.java index 341b70227..d2230469d 100644 --- a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/TsfTagUtilsTest.java +++ b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/TsfTagUtilsTest.java @@ -21,6 +21,7 @@ import java.util.List; import org.junit.jupiter.api.Test; +import org.springframework.tsf.core.entity.Metadata; import org.springframework.tsf.core.entity.Tag; import static org.assertj.core.api.Assertions.assertThat; @@ -31,7 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class TsfTagUtilsTest { @Test - public void deserializeTagList() { + public void testDeserializeTagList() { String data = "%5B%7B%22k%22%3A%22tsf-gateway-ratelimit-context%22%2C%22v%22%3A%22grp-vyiwvq5t%22%2C%22f%22%3A%5B%5D%7D%2C%7B%22k%22%3A%22feat%22%2C%22v%22%3A%22test%22%2C%22f%22%3A%5B%220%22%5D%7D%5D"; List tagList = TsfTagUtils.deserializeTagList(data); for (Tag tag : tagList) { @@ -39,5 +40,43 @@ public class TsfTagUtilsTest { assertThat(tag.getValue()).isNotNull(); assertThat(tag.getFlags()).isNotNull(); } + + assertThat(TsfTagUtils.deserializeTagList(null)).isNull(); + assertThat(TsfTagUtils.deserializeTagList("")).isNull(); + } + + @Test + public void testDeserializeMetadata() { + String encodedInput = "%7B%22ai%22%3A%22applicationId%22%2C%22av%22%3A%22applicationVersion%22%2C%22sn%22%3A%22serviceName%22%2C%22ii%22%3A%22instanceId%22%2C%22gi%22%3A%22groupId%22%2C%22li%22%3A%22127.0.0.1%22%2C%22lis%22%3A%22127.0.0.1%22%2C%22ni%22%3A%22namespaceId%22%2C%22pi%22%3Atrue%7D"; + Metadata expectedMetadata = new Metadata(); + expectedMetadata.setApplicationId("applicationId"); + expectedMetadata.setApplicationVersion("applicationVersion"); + expectedMetadata.setServiceName("serviceName"); + expectedMetadata.setInstanceId("instanceId"); + expectedMetadata.setGroupId("groupId"); + expectedMetadata.setLocalIp("127.0.0.1"); + expectedMetadata.setLocalIps("127.0.0.1"); + expectedMetadata.setNamespaceId("namespaceId"); + expectedMetadata.setPreferIpv6(true); + + String json = JacksonUtils.serialize2Json(expectedMetadata); + String buffer = UrlUtils.encode(json); + System.out.println(buffer); + + Metadata result = TsfTagUtils.deserializeMetadata(encodedInput); + assertThat(result).isNotNull(); + assertThat(result.toString()).isEqualTo(expectedMetadata.toString()); + assertThat(result.getApplicationId()).isEqualTo(expectedMetadata.getApplicationId()); + assertThat(result.getApplicationVersion()).isEqualTo(expectedMetadata.getApplicationVersion()); + assertThat(result.getServiceName()).isEqualTo(expectedMetadata.getServiceName()); + assertThat(result.getInstanceId()).isEqualTo(expectedMetadata.getInstanceId()); + assertThat(result.getGroupId()).isEqualTo(expectedMetadata.getGroupId()); + assertThat(result.getLocalIp()).isEqualTo(expectedMetadata.getLocalIp()); + assertThat(result.getLocalIps()).isEqualTo(expectedMetadata.getLocalIps()); + assertThat(result.getNamespaceId()).isEqualTo(expectedMetadata.getNamespaceId()); + assertThat(result.isPreferIpv6()).isEqualTo(expectedMetadata.isPreferIpv6()); + + assertThat(TsfTagUtils.deserializeMetadata(null)).isNull(); + assertThat(TsfTagUtils.deserializeMetadata("")).isNull(); } } diff --git a/spring-cloud-tencent-commons/src/test/java/org/springframework/tsf/core/util/TsfSpringContextAwareTest.java b/spring-cloud-tencent-commons/src/test/java/org/springframework/tsf/core/util/TsfSpringContextAwareTest.java new file mode 100644 index 000000000..1a76adb15 --- /dev/null +++ b/spring-cloud-tencent-commons/src/test/java/org/springframework/tsf/core/util/TsfSpringContextAwareTest.java @@ -0,0 +1,65 @@ +/* + * Tencent is pleased to support the open source community by making spring-cloud-tencent available. + * + * Copyright (C) 2021 Tencent. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package org.springframework.tsf.core.util; + +import com.tencent.cloud.common.async.PolarisAsyncConfiguration; +import com.tencent.cloud.common.util.ApplicationContextAwareUtils; +import org.junit.jupiter.api.Test; + +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatNoException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * Test for {@link TsfSpringContextAware}. + * + * @author Haotian Zhang + */ +public class TsfSpringContextAwareTest { + + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(ApplicationContextAwareUtils.class)) + .withPropertyValues("key1=value1"); + + @Test + public void testApplicationContextAwareUtils() { + this.contextRunner.run(context -> { + assertThat(TsfSpringContextAware.getApplicationContext()).isNotNull(); + TsfSpringContextAware tsfSpringContextAware = new TsfSpringContextAware(); + assertThatNoException().isThrownBy(() -> tsfSpringContextAware.setApplicationContext(context)); + + // test getProperties + assertThat(TsfSpringContextAware.getProperties("key1")).isEqualTo("value1"); + assertThat(TsfSpringContextAware.getProperties("key2")).isNull(); + + // test getProperties with default value + assertThat(TsfSpringContextAware.getProperties("key1", "defaultValue")).isEqualTo("value1"); + assertThat(TsfSpringContextAware.getProperties("key2", "defaultValue")).isEqualTo("defaultValue"); + + // test getBean + assertThat(TsfSpringContextAware.getBean(ApplicationContextAwareUtils.class)).isNotNull(); + assertThatThrownBy(() -> { + TsfSpringContextAware.getBean(PolarisAsyncConfiguration.class); + }).isInstanceOf(NoSuchBeanDefinitionException.class); + }); + } +}