This is an automated email from the ASF dual-hosted git repository. xingfudeshi pushed a commit to branch 2.x in repository https://gitbox.apache.org/repos/asf/incubator-seata.git
The following commit(s) were added to refs/heads/2.x by this push: new 6799dc974f test: expand unit test coverage for the [cmmon] module. (#7098) 6799dc974f is described below commit 6799dc974ff78fc55e53b2acf41b1bbd5754dac8 Author: psxjoy <psx...@outlook.com> AuthorDate: Mon Jan 13 10:57:50 2025 +0800 test: expand unit test coverage for the [cmmon] module. (#7098) --- changes/en-us/2.x.md | 2 + changes/zh-cn/2.x.md | 2 + .../org/apache/seata/common/code/CodeTest.java | 51 +++++++ .../seata/common/exception/ExceptionUtilTest.java | 37 ++++- .../exception/SeataRuntimeExceptionTest.java | 82 +++++++++++ .../common/loader/EnhancedServiceLoaderTest.java | 30 ++-- .../common/loader/ExtensionDefinitionTest.java | 23 ++- .../apache/seata/common/metadata/MetadataTest.java | 20 ++- .../common/metadata/namingserver/InstanceTest.java | 157 ++++++++++++++++++++- .../metadata/namingserver/MetaResponseTest.java | 50 +++++++ .../namingserver/NamingServerNodeTest.java | 82 ++++++++--- .../common/metadata/namingserver/UnitTest.java | 77 ++++++++++ .../apache/seata/common/result/PageResultTest.java | 151 ++++++++++++++++++++ .../seata/common/result/SingleResultTest.java | 62 ++++++++ .../org/apache/seata/common/util/PageUtilTest.java | 123 +++++++++++++++- .../apache/seata/common/util/StringUtilsTest.java | 105 +++++++++++--- 16 files changed, 984 insertions(+), 70 deletions(-) diff --git a/changes/en-us/2.x.md b/changes/en-us/2.x.md index 2486264a89..e3945b4b97 100644 --- a/changes/en-us/2.x.md +++ b/changes/en-us/2.x.md @@ -28,6 +28,7 @@ Add changes here for all PR submitted to the 2.x branch. ### test: - [[#7092](https://github.com/apache/incubator-seata/pull/7092)] fix the issue of NacosMockTest failing to run +- [[#7098](https://github.com/apache/incubator-seata/pull/7098)] Add unit tests for the `seata-common` module ### refactor: @@ -43,6 +44,7 @@ Thanks to these contributors for their code commits. Please report an unintended - [GoodBoyCoder](https://github.com/GoodBoyCoder) - [PeppaO](https://github.com/PeppaO) - [funky-eyes](https://github.com/funky-eyes) +- [psxjoy](https://github.com/psxjoy) Also, we receive many valuable issues, questions and advices from our community. Thanks for you all. \ No newline at end of file diff --git a/changes/zh-cn/2.x.md b/changes/zh-cn/2.x.md index 003a9beca6..5ef696ff1f 100644 --- a/changes/zh-cn/2.x.md +++ b/changes/zh-cn/2.x.md @@ -27,6 +27,7 @@ ### test: - [[#7092](https://github.com/apache/incubator-seata/pull/7092)] 修复NacosMockTest测试方法并行导致测试结果被干扰失败的问题 +- [[#7098](https://github.com/apache/incubator-seata/pull/7098)] 增加 `seata-common` 模块的测试用例 ### refactor: @@ -42,5 +43,6 @@ - [GoodBoyCoder](https://github.com/GoodBoyCoder) - [PeppaO](https://github.com/PeppaO) - [funky-eyes](https://github.com/funky-eyes) +- [psxjoy](https://github.com/psxjoy) 同时,我们收到了社区反馈的很多有价值的issue和建议,非常感谢大家。 \ No newline at end of file diff --git a/common/src/test/java/org/apache/seata/common/code/CodeTest.java b/common/src/test/java/org/apache/seata/common/code/CodeTest.java new file mode 100644 index 0000000000..66eeffcd87 --- /dev/null +++ b/common/src/test/java/org/apache/seata/common/code/CodeTest.java @@ -0,0 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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.apache.seata.common.code; + +import org.apache.seata.common.result.Code; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +public class CodeTest { + + @Test + public void testGetErrorMsgWithValidCodeReturnsExpectedMsg() { + // Test case for SUCCESS + assertEquals("ok", Code.SUCCESS.getMsg()); + // Test case for ERROR + assertEquals("Server error", Code.ERROR.getMsg()); + // Test case for LOGIN_FAILED + assertEquals("Login failed", Code.LOGIN_FAILED.getMsg()); + } + + @Test + public void testGetErrorMsgWithInvalidCodeReturnsNull() { + // Test case for non-existing code + assertNull(Code.getErrorMsg("404")); + } + + @Test + public void testSetCodeAndMsgUpdatesValuesCorrectly() { + // Test case to check if setCode and setMsg are working as expected + Code.SUCCESS.setCode("201"); + Code.SUCCESS.setMsg("Created"); + assertEquals("201", Code.SUCCESS.getCode()); + assertEquals("Created", Code.SUCCESS.getMsg()); + } +} diff --git a/common/src/test/java/org/apache/seata/common/exception/ExceptionUtilTest.java b/common/src/test/java/org/apache/seata/common/exception/ExceptionUtilTest.java index f8b152b1a2..4ef3647471 100644 --- a/common/src/test/java/org/apache/seata/common/exception/ExceptionUtilTest.java +++ b/common/src/test/java/org/apache/seata/common/exception/ExceptionUtilTest.java @@ -16,16 +16,13 @@ */ package org.apache.seata.common.exception; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.lang.reflect.InvocationTargetException; import java.lang.reflect.UndeclaredThrowableException; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; -/** - * - */ class ExceptionUtilTest { + private Exception exception; @Test public void unwrap() { @@ -38,4 +35,32 @@ class ExceptionUtilTest { RuntimeException runtimeException = new RuntimeException("runtime"); Assertions.assertInstanceOf(RuntimeException.class, ExceptionUtil.unwrap(runtimeException)); } + + @Test + public void unwrapInvocationTargetException() { + InvocationTargetException ite = new InvocationTargetException(exception, "test"); + Throwable result = ExceptionUtil.unwrap(ite); + Assertions.assertSame(exception, result, "Expected the unwrapped exception to be the cause of InvocationTargetException."); + } + + @Test + public void unwrapUndeclaredThrowableException() { + UndeclaredThrowableException ute = new UndeclaredThrowableException(exception, "test"); + Throwable result = ExceptionUtil.unwrap(ute); + Assertions.assertSame(exception, result, "Expected the unwrapped exception to be the cause of UndeclaredThrowableException."); + } + + @Test + public void unwrapNestedInvocationTargetException() { + Exception rootCause = new Exception(); + InvocationTargetException ite = new InvocationTargetException(new UndeclaredThrowableException(rootCause, "test"), "test"); + Throwable result = ExceptionUtil.unwrap(ite); + Assertions.assertSame(rootCause, result, "Expected the unwrapped exception to be the root cause."); + } + + @Test + public void unwrapNotWrappedException() { + Throwable result = ExceptionUtil.unwrap(exception); + Assertions.assertSame(exception, result, "Expected the unwrapped exception to be the same as the input when no wrapping is present."); + } } \ No newline at end of file diff --git a/common/src/test/java/org/apache/seata/common/exception/SeataRuntimeExceptionTest.java b/common/src/test/java/org/apache/seata/common/exception/SeataRuntimeExceptionTest.java new file mode 100644 index 0000000000..3055a0034b --- /dev/null +++ b/common/src/test/java/org/apache/seata/common/exception/SeataRuntimeExceptionTest.java @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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.apache.seata.common.exception; + +import java.sql.SQLException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +public class SeataRuntimeExceptionTest { + + private ErrorCode errorCode; + private String[] params; + + @BeforeEach + void setUp() { + errorCode = ErrorCode.ERR_CONFIG; + params = new String[] {"param1", "param2"}; + } + + @Test + void testConstructorWithErrorCodeCauseAndParams() { + SQLException cause = new SQLException("SQL Error", "S0001", 1000); + SeataRuntimeException exception = new SeataRuntimeException(errorCode, cause, params); + assertNotNull(exception); + assertEquals(errorCode.getMessage(params), exception.getMessage()); + assertEquals("S0001", exception.getSqlState()); + assertEquals(1000, exception.getVendorCode()); + } + + @Test + void testToStringShouldReturnLocalizedMessage() { + SeataRuntimeException exception = new SeataRuntimeException(errorCode, params); + assertEquals(exception.getLocalizedMessage(), exception.toString()); + } + + @Test + void testGetVendorCodeWithSQLExceptionCause() { + SQLException cause = new SQLException("SQL Error", "S0001", 1000); + SeataRuntimeException exception = new SeataRuntimeException(errorCode, cause, params); + assertEquals(1000, exception.getVendorCode()); + } + + @Test + void testGetSqlStateWithSQLExceptionCause() { + SQLException cause = new SQLException("SQL Error", "S0001", 1000); + SeataRuntimeException exception = new SeataRuntimeException(errorCode, cause, params); + assertEquals("S0001", exception.getSqlState()); + } + + @Test + void testGetVendorCodeWithSeataRuntimeExceptionCause() { + SQLException innerCause = new SQLException("SQL Error", "S0001", 1000); + SeataRuntimeException cause = new SeataRuntimeException(errorCode, innerCause, params); + SeataRuntimeException exception = new SeataRuntimeException(errorCode, cause, params); + assertEquals(1000, exception.getVendorCode()); + } + + @Test + void testGetSqlStateWithSeataRuntimeExceptionCause() { + SQLException innerCause = new SQLException("SQL Error", "S0001", 1000); + SeataRuntimeException cause = new SeataRuntimeException(errorCode, innerCause, params); + SeataRuntimeException exception = new SeataRuntimeException(errorCode, cause, params); + assertEquals("S0001", exception.getSqlState()); + } +} diff --git a/common/src/test/java/org/apache/seata/common/loader/EnhancedServiceLoaderTest.java b/common/src/test/java/org/apache/seata/common/loader/EnhancedServiceLoaderTest.java index 5868d07535..aafce37e3e 100644 --- a/common/src/test/java/org/apache/seata/common/loader/EnhancedServiceLoaderTest.java +++ b/common/src/test/java/org/apache/seata/common/loader/EnhancedServiceLoaderTest.java @@ -19,7 +19,6 @@ package org.apache.seata.common.loader; import java.lang.reflect.Field; import java.util.List; import java.util.Map; - import org.apache.seata.common.util.CollectionUtils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -28,7 +27,6 @@ import static org.assertj.core.api.Assertions.assertThat; /** * The type Enhanced service loader test. - * */ public class EnhancedServiceLoaderTest { @@ -75,14 +73,14 @@ public class EnhancedServiceLoaderTest { @Test public void testLoadByClassAndClassLoaderAndActivateName() { Hello englishHello = EnhancedServiceLoader - .load(Hello.class, "EnglishHello", EnhancedServiceLoaderTest.class.getClassLoader()); + .load(Hello.class, "EnglishHello", EnhancedServiceLoaderTest.class.getClassLoader()); assertThat(englishHello.say()).isEqualTo("hello!"); } /** * Gets all extension class. */ - @Test + @SuppressWarnings("checkstyle:UnnecessaryParentheses") @Test public void getAllExtensionClass() { List<Class<Hello>> allExtensionClass = EnhancedServiceLoader.getAllExtensionClass(Hello.class); assertThat(allExtensionClass.get(3).getSimpleName()).isEqualTo((LatinHello.class.getSimpleName())); @@ -97,33 +95,32 @@ public class EnhancedServiceLoaderTest { @Test public void getAllExtensionClass1() { List<Class<Hello>> allExtensionClass = EnhancedServiceLoader - .getAllExtensionClass(Hello.class, ClassLoader.getSystemClassLoader()); + .getAllExtensionClass(Hello.class, ClassLoader.getSystemClassLoader()); assertThat(allExtensionClass).isNotEmpty(); } @Test - public void getSingletonExtensionInstance(){ + public void getSingletonExtensionInstance() { Hello hello1 = EnhancedServiceLoader.load(Hello.class, "ChineseHello"); Hello hello2 = EnhancedServiceLoader.load(Hello.class, "ChineseHello"); assertThat(hello1 == hello2).isTrue(); } @Test - public void getMultipleExtensionInstance(){ + public void getMultipleExtensionInstance() { Hello hello1 = EnhancedServiceLoader.load(Hello.class, "LatinHello"); Hello hello2 = EnhancedServiceLoader.load(Hello.class, "LatinHello"); assertThat(hello1 == hello2).isFalse(); } @Test - public void getAllInstances(){ + public void getAllInstances() { List<Hello> hellows1 = EnhancedServiceLoader.loadAll(Hello.class); List<Hello> hellows2 = EnhancedServiceLoader.loadAll(Hello.class); - for (Hello hello : hellows1){ + for (Hello hello : hellows1) { if (!hello.say().equals("Olá.")) { assertThat(hellows2.contains(hello)).isTrue(); - } - else{ + } else { assertThat(hellows2.contains(hello)).isFalse(); } } @@ -145,7 +142,7 @@ public class EnhancedServiceLoaderTest { @Test public void testLoadByClassAndActivateNameAndArgsTypeAndArgs() { Hello2 load = EnhancedServiceLoader - .load(Hello2.class, "JapaneseHello", new Class[] {String.class}, new Object[] {"msg"}); + .load(Hello2.class, "JapaneseHello", new Class[] {String.class}, new Object[] {"msg"}); assertThat(load).isInstanceOf(Hello2.class); } @@ -153,7 +150,7 @@ public class EnhancedServiceLoaderTest { public void testUnloadAll() throws NoSuchFieldException, IllegalAccessException { Hello hello = EnhancedServiceLoader.load(Hello.class); assertThat(hello).isInstanceOf(Hello.class); - Hello2 hello2 = EnhancedServiceLoader.load(Hello2.class, "JapaneseHello", new Object[]{"msg"}); + Hello2 hello2 = EnhancedServiceLoader.load(Hello2.class, "JapaneseHello", new Object[] {"msg"}); assertThat(hello2).isInstanceOf(Hello2.class); EnhancedServiceLoader.unloadAll(); @@ -161,7 +158,7 @@ public class EnhancedServiceLoaderTest { Class<EnhancedServiceLoader> clazz = EnhancedServiceLoader.class; Field serviceLoadersField = clazz.getDeclaredField("SERVICE_LOADERS"); serviceLoadersField.setAccessible(true); - Map<Class<?>, Object> serviceLoaders = (Map<Class<?>, Object>)serviceLoadersField.get(null); + Map<Class<?>, Object> serviceLoaders = (Map<Class<?>, Object>) serviceLoadersField.get(null); assertThat(CollectionUtils.isEmpty(serviceLoaders)).isTrue(); } @@ -175,7 +172,7 @@ public class EnhancedServiceLoaderTest { Class<EnhancedServiceLoader> clazz = EnhancedServiceLoader.class; Field serviceLoadersField = clazz.getDeclaredField("SERVICE_LOADERS"); serviceLoadersField.setAccessible(true); - Map<Class<?>, Object> serviceLoaders = (Map<Class<?>, Object>)serviceLoadersField.get(null); + Map<Class<?>, Object> serviceLoaders = (Map<Class<?>, Object>) serviceLoadersField.get(null); assertThat(serviceLoaders.get(Hello.class)).isNull(); } @@ -191,7 +188,7 @@ public class EnhancedServiceLoaderTest { Class<EnhancedServiceLoader> clazz = EnhancedServiceLoader.class; Field serviceLoadersField = clazz.getDeclaredField("SERVICE_LOADERS"); serviceLoadersField.setAccessible(true); - Map<Class<?>, Object> serviceLoaders = (Map<Class<?>, Object>)serviceLoadersField.get(null); + Map<Class<?>, Object> serviceLoaders = (Map<Class<?>, Object>) serviceLoadersField.get(null); //get innerEnhancedServiceLoader.classToDefinitionMap Object innerEnhancedServiceLoader = serviceLoaders.get(Hello.class); Field classToDefinitionMapField = innerEnhancedServiceLoader.getClass().getDeclaredField("classToDefinitionMap"); @@ -208,5 +205,4 @@ public class EnhancedServiceLoaderTest { Assertions.assertDoesNotThrow(() -> EnhancedServiceLoader.unload(Hello.class, "FrenchHello")); } - } diff --git a/common/src/test/java/org/apache/seata/common/loader/ExtensionDefinitionTest.java b/common/src/test/java/org/apache/seata/common/loader/ExtensionDefinitionTest.java index b59239e3f5..86e77c30ba 100644 --- a/common/src/test/java/org/apache/seata/common/loader/ExtensionDefinitionTest.java +++ b/common/src/test/java/org/apache/seata/common/loader/ExtensionDefinitionTest.java @@ -19,7 +19,9 @@ package org.apache.seata.common.loader; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; - +/** + * The type Extension definition test. + */ public class ExtensionDefinitionTest { @Test @@ -30,4 +32,23 @@ public class ExtensionDefinitionTest { = new ExtensionDefinition<>("abc", 1, Scope.PROTOTYPE, ChineseHello.class); Assertions.assertEquals(definition2, definition); } + + @Test + public void testConstructorAndGetters() { + ExtensionDefinition<ChineseHello> definition = + new ExtensionDefinition<>("abc", 1, Scope.PROTOTYPE, ChineseHello.class); + Assertions.assertEquals("abc", definition.getName()); + Assertions.assertEquals(1, definition.getOrder()); + Assertions.assertEquals(Scope.PROTOTYPE, definition.getScope()); + Assertions.assertEquals(ChineseHello.class, definition.getServiceClass()); + } + + @Test + public void testHashCode() { + ExtensionDefinition<ChineseHello> definition = + new ExtensionDefinition<>("abc", 1, Scope.PROTOTYPE, ChineseHello.class); + ExtensionDefinition<ChineseHello> definition2 = + new ExtensionDefinition<>("abc", 1, Scope.PROTOTYPE, ChineseHello.class); + Assertions.assertEquals(definition.hashCode(), definition2.hashCode()); + } } diff --git a/common/src/test/java/org/apache/seata/common/metadata/MetadataTest.java b/common/src/test/java/org/apache/seata/common/metadata/MetadataTest.java index f11603bdf0..964c9dfbc2 100644 --- a/common/src/test/java/org/apache/seata/common/metadata/MetadataTest.java +++ b/common/src/test/java/org/apache/seata/common/metadata/MetadataTest.java @@ -16,15 +16,13 @@ */ package org.apache.seata.common.metadata; +import java.util.ArrayList; +import java.util.List; import org.apache.seata.common.store.StoreMode; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import java.util.ArrayList; -import java.util.List; - - public class MetadataTest { private static Metadata metadata; @@ -99,6 +97,8 @@ public class MetadataTest { Assertions.assertDoesNotThrow(() -> metadata.refreshMetadata("cluster", metadataResponse)); metadataResponse.setNodes(new ArrayList<>()); Assertions.assertDoesNotThrow(() -> metadata.refreshMetadata("cluster", metadataResponse)); + metadataResponse.setStoreMode("unknown store"); + Assertions.assertThrows(IllegalArgumentException.class, () -> metadata.refreshMetadata("cluster", metadataResponse)); } @Test @@ -106,4 +106,16 @@ public class MetadataTest { Assertions.assertEquals("Metadata(leaders={}, clusterTerm={}, clusterNodes={\"cluster\"->{}}, storeMode=StoreMode.RAFT)", metadata.toString()); } + @Test + public void containsValidNameReturnsTrue() { + boolean result = StoreMode.contains(StoreMode.FILE.name()); + Assertions.assertEquals(true, result); + result = StoreMode.contains("INVALID_NAME"); + Assertions.assertEquals(false, result); + result = StoreMode.contains(null); + Assertions.assertEquals(false, result); + result = StoreMode.contains(""); + Assertions.assertEquals(false, result); + } + } diff --git a/common/src/test/java/org/apache/seata/common/metadata/namingserver/InstanceTest.java b/common/src/test/java/org/apache/seata/common/metadata/namingserver/InstanceTest.java index 55741a835f..33969ea40f 100644 --- a/common/src/test/java/org/apache/seata/common/metadata/namingserver/InstanceTest.java +++ b/common/src/test/java/org/apache/seata/common/metadata/namingserver/InstanceTest.java @@ -18,19 +18,28 @@ package org.apache.seata.common.metadata.namingserver; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.HashMap; +import java.util.Map; import org.apache.seata.common.metadata.ClusterRole; import org.apache.seata.common.metadata.Instance; import org.apache.seata.common.metadata.Node; import org.junit.jupiter.api.Test; -import java.util.HashMap; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.*; +import static org.apache.seata.common.util.CollectionUtils.mapToJsonString; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; class InstanceTest { private final ObjectMapper objectMapper = new ObjectMapper(); + private Instance instance; + private Instance instanceA; + private Instance instanceB; + private Instance instanceC; + @Test void toJsonString() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); @@ -52,4 +61,144 @@ class InstanceTest { instance.setTransaction(new Node.Endpoint("2.2.2.2", 999)); assertEquals(instance.toJsonString(objectMapper), objectMapper.writeValueAsString(instance)); } + + @Test + public void testGetInstance() { + Instance anotherInstance = Instance.getInstance(); + instance = Instance.getInstance(); + assertEquals(instance, anotherInstance); + } + + @Test + public void testJsonSerializationShouldSerialize() { + instance = Instance.getInstance(); + instance.setNamespace("testNamespace"); + instance.setClusterName("testCluster"); + instance.setUnit("testUnit"); + instance.getControl().setPort(1234); + instance.getTransaction().setPort(4321); + instance.setWeight(0.5); + instance.setHealthy(false); + instance.setTerm(1); + instance.setTimestamp(System.currentTimeMillis()); + instance.addMetadata("key1", "value1"); + + String jsonString = instance.toJsonString(objectMapper); + Instance deserializedInstance = null; + try { + deserializedInstance = objectMapper.readValue(jsonString, Instance.class); + } catch (Exception e) { + fail("Exception during JSON deserialization: " + e.getMessage()); + } + + assertNotNull(deserializedInstance); + assertEquals(instance.getNamespace(), deserializedInstance.getNamespace()); + assertEquals(instance.getClusterName(), deserializedInstance.getClusterName()); + assertEquals(instance.getUnit(), deserializedInstance.getUnit()); + assertEquals(instance.getControl().getPort(), deserializedInstance.getControl().getPort()); + assertEquals(instance.getTransaction().getPort(), deserializedInstance.getTransaction().getPort()); + assertEquals(instance.getWeight(), deserializedInstance.getWeight(), 0.0); + assertEquals(instance.isHealthy(), deserializedInstance.isHealthy()); + assertEquals(instance.getTerm(), deserializedInstance.getTerm()); + assertEquals(instance.getTimestamp(), deserializedInstance.getTimestamp()); + assertEquals(instance.getMetadata(), deserializedInstance.getMetadata()); + } + + @Test + public void testToMapShouldReturnCorrectMap() { + instance = Instance.getInstance(); + instance.setNamespace("testNamespace"); + instance.setClusterName("testCluster"); + instance.setUnit("testUnit"); + instance.setControl(new Node.Endpoint("127.0.0.1", 1234)); + instance.setTransaction(new Node.Endpoint("127.0.0.1", 4321)); + + instance.setWeight(0.5); + instance.setHealthy(false); + instance.setTerm(1); + instance.setTimestamp(System.currentTimeMillis()); + instance.addMetadata("key1", "value1"); + + Map<String, String> resultMap = new HashMap<>(); + resultMap.put("namespace", instance.getNamespace()); + resultMap.put("clusterName", instance.getClusterName()); + resultMap.put("unit", instance.getUnit()); + resultMap.put("control", instance.getControl().toString()); + resultMap.put("transaction", instance.getTransaction().toString()); + resultMap.put("weight", String.valueOf(instance.getWeight())); + resultMap.put("healthy", String.valueOf(instance.isHealthy())); + resultMap.put("term", String.valueOf(instance.getTerm())); + resultMap.put("timestamp", String.valueOf(instance.getTimestamp())); + resultMap.put("metadata", mapToJsonString(instance.getMetadata())); + + assertEquals("testNamespace", resultMap.get("namespace")); + assertEquals("testCluster", resultMap.get("clusterName")); + assertEquals("testUnit", resultMap.get("unit")); + assertTrue(resultMap.get("control").contains("1234")); + assertTrue(resultMap.get("transaction").contains("4321")); + assertEquals("0.5", resultMap.get("weight")); + assertEquals("false", resultMap.get("healthy")); + assertEquals("1", resultMap.get("term")); + assertTrue(resultMap.get("timestamp").matches("\\d+")); + assertTrue(resultMap.get("metadata").contains("key1")); + assertTrue(resultMap.get("metadata").contains("value1")); + } + + @Test + public void testSameInstance() { + instanceA = Instance.getInstance(); + instanceA.setControl(new Node.Endpoint("127.0.0.1", 8080)); + instanceA.setTransaction(new Node.Endpoint("127.0.0.1", 9090)); + assertEquals(instanceA, instanceA); + } + + @Test + public void testNull() { + instanceA = Instance.getInstance(); + instanceA.setControl(new Node.Endpoint("127.0.0.1", 8080)); + instanceA.setTransaction(new Node.Endpoint("127.0.0.1", 9090)); + assertNotEquals(instanceA, null); + } + + @Test + public void testDifferentClass() { + instanceA = Instance.getInstance(); + instanceA.setControl(new Node.Endpoint("127.0.0.1", 8080)); + instanceA.setTransaction(new Node.Endpoint("127.0.0.1", 9090)); + assertNotEquals(instanceA, "NotAnInstance"); + } + + @Test + public void testSameFields() { + instanceA = Instance.getInstance(); + instanceA.setControl(new Node.Endpoint("127.0.0.1", 8080)); + instanceA.setTransaction(new Node.Endpoint("127.0.0.1", 9090)); + instanceB = Instance.getInstance(); + instanceB.setControl(new Node.Endpoint("127.0.0.1", 8080)); + instanceB.setTransaction(new Node.Endpoint("127.0.0.1", 9090)); + assertEquals(instanceA, instanceB); + } + + @Test + public void testDifferentControlPort() { + instanceA = Instance.getInstance(); + instanceA.setControl(new Node.Endpoint("127.0.0.1", 8080)); + instanceA.setTransaction(new Node.Endpoint("127.0.0.1", 9090)); + instanceC = Instance.getInstance(); + instanceC.setControl(new Node.Endpoint("127.0.0.1", 8081)); + instanceC.setTransaction(new Node.Endpoint("127.0.0.1", 9090)); + instanceC.getControl().setPort(8080); + assertTrue(instanceA.equals(instanceC)); + } + + @Test + public void testDifferentTransactionPort() { + instanceA = Instance.getInstance(); + instanceA.setControl(new Node.Endpoint("127.0.0.1", 8080)); + instanceA.setTransaction(new Node.Endpoint("127.0.0.1", 9090)); + instanceC = Instance.getInstance(); + instanceC.setControl(new Node.Endpoint("127.0.0.1", 8081)); + instanceC.setTransaction(new Node.Endpoint("127.0.0.1", 9090)); + assertTrue(instanceA.equals(instanceC)); + } } \ No newline at end of file diff --git a/common/src/test/java/org/apache/seata/common/metadata/namingserver/MetaResponseTest.java b/common/src/test/java/org/apache/seata/common/metadata/namingserver/MetaResponseTest.java new file mode 100644 index 0000000000..7de102ea46 --- /dev/null +++ b/common/src/test/java/org/apache/seata/common/metadata/namingserver/MetaResponseTest.java @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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.apache.seata.common.metadata.namingserver; + +import org.apache.seata.common.metadata.Cluster; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +class MetaResponseTest { + + @Test + void testConstructor() { + List<Cluster> clusterList = new ArrayList<>(); + long term = 12345L; + MetaResponse metaResponse = new MetaResponse(clusterList, term); + + Assertions.assertEquals(clusterList, metaResponse.getClusterList()); + Assertions.assertEquals(term, metaResponse.getTerm()); + } + + @Test + void testGettersAndSetters() { + MetaResponse metaResponse = new MetaResponse(); + + List<Cluster> clusterList = new ArrayList<>(); + metaResponse.setClusterList(clusterList); + Assertions.assertEquals(clusterList, metaResponse.getClusterList()); + + long term = 67890L; + metaResponse.setTerm(term); + Assertions.assertEquals(term, metaResponse.getTerm()); + } +} diff --git a/common/src/test/java/org/apache/seata/common/metadata/namingserver/NamingServerNodeTest.java b/common/src/test/java/org/apache/seata/common/metadata/namingserver/NamingServerNodeTest.java index bd1316b6dd..20e74c386b 100644 --- a/common/src/test/java/org/apache/seata/common/metadata/namingserver/NamingServerNodeTest.java +++ b/common/src/test/java/org/apache/seata/common/metadata/namingserver/NamingServerNodeTest.java @@ -18,46 +18,94 @@ package org.apache.seata.common.metadata.namingserver; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.HashMap; +import java.util.Map; import org.apache.seata.common.metadata.Node; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.HashMap; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; class NamingServerNodeTest { - private ObjectMapper objectMapper = new ObjectMapper(); @Test void toJsonString() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); NamingServerNode node = new NamingServerNode(); - Map<String,Object> map = new HashMap<>(); - map.put("k","v"); + Map<String, Object> map = new HashMap<>(); + map.put("k", "v"); node.setMetadata(map); node.setGroup("group"); node.setUnit("unit"); node.setHealthy(true); node.setTerm(111L); - node.setControl(new Node.Endpoint("1.1.1.1",888)); - node.setTransaction(new Node.Endpoint("2.2.2.2",999)); - assertEquals(node.toJsonString(objectMapper),objectMapper.writeValueAsString(node)); + node.setControl(new Node.Endpoint("1.1.1.1", 888)); + node.setTransaction(new Node.Endpoint("2.2.2.2", 999)); + assertEquals(node.toJsonString(objectMapper), objectMapper.writeValueAsString(node)); } - + @Test public void testContains() { NamingServerNode node1 = new NamingServerNode(); - node1.setControl(new Node.Endpoint("111.11.11.1",123)); - node1.setTransaction(new Node.Endpoint("111.11.11.1",124)); + node1.setControl(new Node.Endpoint("111.11.11.1", 123)); + node1.setTransaction(new Node.Endpoint("111.11.11.1", 124)); Node node2 = new Node(); - node2.setControl(new Node.Endpoint("111.11.11.1",123)); - node2.setTransaction(new Node.Endpoint("111.11.11.1",124)); + node2.setControl(new Node.Endpoint("111.11.11.1", 123)); + node2.setTransaction(new Node.Endpoint("111.11.11.1", 124)); NamingServerNode node3 = new NamingServerNode(); - node3.setControl(new Node.Endpoint("111.11.11.1",123)); - node3.setTransaction(new Node.Endpoint("111.11.11.1",124)); + node3.setControl(new Node.Endpoint("111.11.11.1", 123)); + node3.setTransaction(new Node.Endpoint("111.11.11.1", 124)); Assertions.assertFalse(node1.equals(node2)); Assertions.assertTrue(node1.equals(node3)); } + + @Test + void testGettersAndSetters() { + NamingServerNode node = new NamingServerNode(); + node.setWeight(2.5); + node.setHealthy(false); + node.setUnit("unitTest"); + node.setTerm(12345L); + + assertEquals(2.5, node.getWeight()); + assertEquals(false, node.isHealthy()); + assertEquals("unitTest", node.getUnit()); + assertEquals(12345L, node.getTerm()); + } + + @Test + void testEqualsAndHashCode() { + NamingServerNode node1 = new NamingServerNode(); + node1.setControl(new Node.Endpoint("1.1.1.1", 888)); + node1.setTransaction(new Node.Endpoint("2.2.2.2", 999)); + + NamingServerNode node2 = new NamingServerNode(); + node2.setControl(new Node.Endpoint("1.1.1.1", 888)); + node2.setTransaction(new Node.Endpoint("2.2.2.2", 999)); + + NamingServerNode node3 = new NamingServerNode(); + node3.setControl(new Node.Endpoint("3.3.3.3", 777)); + node3.setTransaction(new Node.Endpoint("4.4.4.4", 666)); + + Assertions.assertTrue(node1.equals(node2)); + Assertions.assertFalse(node1.equals(node3)); + Assertions.assertEquals(node1.hashCode(), node2.hashCode()); + Assertions.assertNotEquals(node1.hashCode(), node3.hashCode()); + } + + @Test + void testIsChanged() { + NamingServerNode currentNode = new NamingServerNode(); + currentNode.setTerm(100L); + + NamingServerNode newerNode = new NamingServerNode(); + newerNode.setTerm(101L); + + NamingServerNode olderNode = new NamingServerNode(); + olderNode.setTerm(99L); + + Assertions.assertTrue(currentNode.isChanged(newerNode)); + Assertions.assertFalse(currentNode.isChanged(olderNode)); + Assertions.assertFalse(currentNode.isChanged(null)); + } } \ No newline at end of file diff --git a/common/src/test/java/org/apache/seata/common/metadata/namingserver/UnitTest.java b/common/src/test/java/org/apache/seata/common/metadata/namingserver/UnitTest.java new file mode 100644 index 0000000000..a39b76d356 --- /dev/null +++ b/common/src/test/java/org/apache/seata/common/metadata/namingserver/UnitTest.java @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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.apache.seata.common.metadata.namingserver; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +class UnitTest { + + private Unit unit; + private NamingServerNode node1; + private NamingServerNode node2; + + @BeforeEach + void setUp() { + unit = new Unit(); + node1 = new NamingServerNode(); + node1.setTerm(1L); + node2 = new NamingServerNode(); + node2.setTerm(2L); + List<NamingServerNode> nodeList = new ArrayList<>(); + nodeList.add(node1); + unit.setNamingInstanceList(nodeList); + } + + @Test + void testGettersAndSetters() { + unit.setUnitName("TestUnit"); + Assertions.assertEquals("TestUnit", unit.getUnitName()); + + List<NamingServerNode> newList = new ArrayList<>(); + unit.setNamingInstanceList(newList); + Assertions.assertEquals(newList, unit.getNamingInstanceList()); + } + + @Test + void testRemoveInstance() { + unit.removeInstance(node1); + Assertions.assertFalse(unit.getNamingInstanceList().contains(node1)); + } + + @Test + void testAddInstance() { + // Test adding a new node + Assertions.assertTrue(unit.addInstance(node2)); + Assertions.assertTrue(unit.getNamingInstanceList().contains(node2)); + + // Test adding an existing node with a different term + node1.setTerm(3L); + Assertions.assertTrue(unit.addInstance(node1)); + Assertions.assertEquals(1, unit.getNamingInstanceList().size()); + + // Test adding an existing node without change + NamingServerNode node3 = new NamingServerNode(); + node3.setTerm(3L); + Assertions.assertFalse(unit.addInstance(node3)); + Assertions.assertEquals(1, unit.getNamingInstanceList().size()); + } +} diff --git a/common/src/test/java/org/apache/seata/common/result/PageResultTest.java b/common/src/test/java/org/apache/seata/common/result/PageResultTest.java new file mode 100644 index 0000000000..4ee65f108a --- /dev/null +++ b/common/src/test/java/org/apache/seata/common/result/PageResultTest.java @@ -0,0 +1,151 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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.apache.seata.common.result; + +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.MockitoAnnotations; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +public class PageResultTest { + @InjectMocks + private PageResult pageResult; + + @BeforeEach + void setUp() { + MockitoAnnotations.initMocks(this); + } + + @Test + void buildPageSizeDivisibleByListSize() { + List<Long> list = new ArrayList<>(); + for (long i = 0; i < 100; i++) { + list.add(i); + } + PageResult pageResult = PageResult.build(list, 1, 10); + assertEquals(10, pageResult.getPages()); + assertEquals(10, pageResult.getData().size()); + } + + @Test + void buildPageSizeNotDivisibleByListSize() { + List<Long> list = new ArrayList<>(); + for (long i = 0; i < 9; i++) { + list.add(i); + } + PageResult pageResult = PageResult.build(list, 1, 10); + assertEquals(1, pageResult.getPages()); + assertEquals(9, pageResult.getData().size()); + } + + @Test + void buildPageNumGreaterThanTotalPages() { + List<Long> list = new ArrayList<>(); + for (long i = 0; i < 5; i++) { + list.add(i); + } + PageResult pageResult = PageResult.build(list, 10, 2); + assertEquals(10, pageResult.getPageNum().intValue()); + assertEquals(3, pageResult.getPages().intValue()); + assertEquals(0, pageResult.getData().size()); + } + + @Test + void failureInvalidParams() { + PageResult pageResult = PageResult.failure("400", "error"); + assertEquals("400", pageResult.getCode()); + assertEquals("error", pageResult.getMessage()); + } + + @Test + void successNoData() { + PageResult pageResult = PageResult.success(); + assertEquals(PageResult.SUCCESS_CODE, pageResult.getCode()); + assertEquals(PageResult.SUCCESS_MSG, pageResult.getMessage()); + assertNull(pageResult.getData()); + } + + @Test + void successWithData() { + List<Long> list = new ArrayList<>(); + for (long i = 0; i < 5; i++) { + list.add(i); + } + PageResult pageResult = PageResult.success(list, 5, 1, 5); + assertEquals(PageResult.SUCCESS_CODE, pageResult.getCode()); + assertEquals(PageResult.SUCCESS_MSG, pageResult.getMessage()); + assertEquals(5, pageResult.getTotal().intValue()); + assertEquals(1, pageResult.getPageNum().intValue()); + assertEquals(5, pageResult.getPageSize().intValue()); + assertEquals(1, pageResult.getPages().intValue()); + assertEquals(list, pageResult.getData()); + } + + @Test + void checkPageNumAndPageSizeDefault() { + BaseParam param = new BaseParam(); + param.setPageNum(0); + param.setPageSize(0); + param.setTimeStart(1L); + param.setTimeEnd(2L); + PageResult.checkPage(param); + assertEquals(1, param.getPageNum()); + assertEquals(20, param.getPageSize()); + assertEquals(1L, param.getTimeStart()); + assertEquals(2L, param.getTimeEnd()); + assertEquals("BaseParam{pageNum=1, pageSize=20, timeStart=1, timeEnd=2}", param.toString()); + } + + @Test + void getTotalSetAndGet() { + pageResult.setTotal(100); + assertEquals(100, pageResult.getTotal().intValue()); + } + + @Test + void getPagesSetAndGet() { + pageResult.setPages(10); + assertEquals(10, pageResult.getPages().intValue()); + } + + @Test + void getPageNumSetAndGet() { + pageResult.setPageNum(2); + assertEquals(2, pageResult.getPageNum().intValue()); + } + + @Test + void getPageSizeSetAndGet() { + pageResult.setPageSize(30); + assertEquals(30, pageResult.getPageSize().intValue()); + } + + @Test + void getDataSetAndGet() { + List<Long> list = new ArrayList<>(); + for (long i = 0; i < 5; i++) { + list.add(i); + } + pageResult.setData(list); + assertEquals(list, pageResult.getData()); + } +} diff --git a/common/src/test/java/org/apache/seata/common/result/SingleResultTest.java b/common/src/test/java/org/apache/seata/common/result/SingleResultTest.java new file mode 100644 index 0000000000..db690aa4e9 --- /dev/null +++ b/common/src/test/java/org/apache/seata/common/result/SingleResultTest.java @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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.apache.seata.common.result; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +class SingleResultTest { + + @Test + void testConstructor() { + SingleResult<String> result = new SingleResult<>("200", "OK", "Data"); + Assertions.assertEquals("200", result.getCode()); + Assertions.assertEquals("OK", result.getMessage()); + Assertions.assertEquals("Data", result.getData()); + } + + @Test + void testFailureWithCodeAndMessage() { + SingleResult<String> result = SingleResult.failure("500", "Error"); + Assertions.assertEquals("500", result.getCode()); + Assertions.assertEquals("Error", result.getMessage()); + Assertions.assertNull(result.getData()); + } + + @Test + void testFailureWithErrorCode() { + SingleResult<String> result = SingleResult.failure(Code.LOGIN_FAILED); + Assertions.assertEquals("401", result.getCode()); + Assertions.assertEquals("Login failed", result.getMessage()); + Assertions.assertNull(result.getData()); + } + + @Test + void testSuccess() { + SingleResult<String> result = SingleResult.success("SuccessData"); + Assertions.assertEquals(SingleResult.SUCCESS_CODE, result.getCode()); + Assertions.assertEquals(SingleResult.SUCCESS_MSG, result.getMessage()); + Assertions.assertEquals("SuccessData", result.getData()); + } + + @Test + void testGettersAndSetters() { + SingleResult<String> result = new SingleResult<>("200", "OK"); + result.setData("NewData"); + Assertions.assertEquals("NewData", result.getData()); + } +} diff --git a/common/src/test/java/org/apache/seata/common/util/PageUtilTest.java b/common/src/test/java/org/apache/seata/common/util/PageUtilTest.java index 640fa03701..545e64c078 100644 --- a/common/src/test/java/org/apache/seata/common/util/PageUtilTest.java +++ b/common/src/test/java/org/apache/seata/common/util/PageUtilTest.java @@ -16,18 +16,45 @@ */ package org.apache.seata.common.util; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; import org.apache.seata.common.exception.NotSupportYetException; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.doNothing; /** * The page util test. - * */ public class PageUtilTest { + private int validPageNum; + private int validPageSize; + private String validTimeColumnName; + @InjectMocks + private PageUtil pageUtil; + + @BeforeEach + void setUp() { + validPageNum = 1; + validPageSize = 10; + validTimeColumnName = "gmt_create"; + MockitoAnnotations.initMocks(this); + + } + @Test public void testPageSql() { String sourceSql = "select * from test where a = 1"; @@ -35,8 +62,8 @@ public class PageUtilTest { String mysqlTargetSql = "select * from test where a = 1 limit 5 offset 0"; String oracleTargetSql = "select * from " + - "( select ROWNUM rn, temp.* from (select * from test where a = 1) temp )" + - " where rn between 1 and 5"; + "( select ROWNUM rn, temp.* from (select * from test where a = 1) temp )" + + " where rn between 1 and 5"; String sqlserverTargetSql = "select * from (select temp.*, ROW_NUMBER() OVER(ORDER BY gmt_create desc) AS rowId from (select * from test where a = 1) temp ) t where t.rowId between 1 and 5"; assertEquals(PageUtil.pageSql(sourceSql, "mysql", 1, 5), mysqlTargetSql); @@ -69,4 +96,94 @@ public class PageUtilTest { assertThrows(NotSupportYetException.class, () -> PageUtil.countSql(sourceSql, "xxx")); } + @Test + void checkParamValidPageParams() { + assertDoesNotThrow(() -> PageUtil.checkParam(validPageNum, validPageSize)); + } + + @Test + void checkParamPageNumBelowMin() { + int invalidPageNum = PageUtil.MIN_PAGE_NUM - 1; + assertThrows(IllegalArgumentException.class, () -> PageUtil.checkParam(invalidPageNum, validPageSize)); + } + + @Test + void checkParamPageNumAboveMax() { + int invalidPageNum = PageUtil.MAX_PAGE_NUM + 1; + assertThrows(IllegalArgumentException.class, () -> PageUtil.checkParam(invalidPageNum, validPageSize)); + } + + @Test + void checkParamPageSizeBelowMin() { + int invalidPageSize = PageUtil.MIN_PAGE_SIZE - 1; + assertThrows(IllegalArgumentException.class, () -> PageUtil.checkParam(validPageNum, invalidPageSize)); + } + + @Test + void checkParamPageSizeAboveMax() { + int invalidPageSize = PageUtil.MAX_PAGE_SIZE + 1; + assertThrows(IllegalArgumentException.class, () -> PageUtil.checkParam(validPageNum, invalidPageSize)); + } + + @Test + void setObjectWithDateParameterSetsDateCorrectly() throws SQLException { + List<Object> params = new ArrayList<>(); + params.add(new Date(System.currentTimeMillis())); + params.add(123); + + PreparedStatement preparedStatement = Mockito.mock(PreparedStatement.class); + doNothing().when(preparedStatement).setDate(anyInt(), any(java.sql.Date.class)); + + PageUtil.setObject(preparedStatement, params); + + Mockito.verify(preparedStatement).setDate(anyInt(), any(java.sql.Date.class)); + } + + @Test + void setObjectWithNonDateParameterSetsObjectCorrectly() throws SQLException { + List<Object> params = new ArrayList<>(); + params.add("testString"); + + PreparedStatement preparedStatement = Mockito.mock(PreparedStatement.class); + + PageUtil.setObject(preparedStatement, params); + + Mockito.verify(preparedStatement, Mockito.times(1)).setObject(anyInt(), any()); + } + + @Test + void setObjectEmptyListNoInteractionWithPreparedStatement() throws SQLException { + List<Object> params = new ArrayList<>(); + + PreparedStatement preparedStatement = Mockito.mock(PreparedStatement.class); + + PageUtil.setObject(preparedStatement, params); + + Mockito.verify(preparedStatement, Mockito.never()).setObject(anyInt(), any()); + } + + @Test + void setObjectNullListNoInteraction() throws SQLException { + List<Object> params = null; + PreparedStatement preparedStatement = Mockito.mock(PreparedStatement.class); + + assertThrows(NullPointerException.class, () -> PageUtil.setObject(preparedStatement, params)); + } + + @Test + public void getTimeStartSqlSupportedDBTypes() { + String[] supportedDBTypes = {"mysql", "oracle", "postgresql", "sqlserver", "dm", "oscar"}; + String expectedSQL = " and FLOOR(gmt_create/1000) >= ? "; + + for (String dbType : supportedDBTypes) { + assertEquals(expectedSQL, PageUtil.getTimeStartSql(dbType, validTimeColumnName)); + } + } + + @Test + public void getTimeStartSqlNotSupportedDBType() { + String notSupportedDBType = "xxx"; + assertThrows(IllegalArgumentException.class, () -> PageUtil.getTimeStartSql(notSupportedDBType, validTimeColumnName)); + } + } diff --git a/common/src/test/java/org/apache/seata/common/util/StringUtilsTest.java b/common/src/test/java/org/apache/seata/common/util/StringUtilsTest.java index a7a3655596..64c7a6ae81 100644 --- a/common/src/test/java/org/apache/seata/common/util/StringUtilsTest.java +++ b/common/src/test/java/org/apache/seata/common/util/StringUtilsTest.java @@ -26,14 +26,17 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.Date; import java.util.HashMap; +import java.util.Iterator; import java.util.List; import java.util.Map; - import org.apache.seata.common.Constants; import org.apache.seata.common.holder.ObjectHolder; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.opentest4j.AssertionFailedError; @@ -42,10 +45,20 @@ import static org.junit.jupiter.api.Assertions.assertNull; /** * The type String utils test. - * */ public class StringUtilsTest { + private Iterator<String> emptyIterator; + private Iterator<String> singleElementIterator; + private Iterator<String> multipleElementsIterator; + + @BeforeEach + void setUp() { + emptyIterator = Collections.emptyIterator(); + singleElementIterator = Collections.singletonList("Hello").iterator(); + multipleElementsIterator = Arrays.asList("Hello", "World", "Java").iterator(); + } + /** * Test is empty. */ @@ -107,7 +120,7 @@ public class StringUtilsTest { } @Test - public void testHump2Line(){ + public void testHump2Line() { assertThat(StringUtils.hump2Line("abc-d").equals("abcD")).isTrue(); assertThat(StringUtils.hump2Line("aBc").equals("a-bc")).isTrue(); assertThat(StringUtils.hump2Line("abc").equals("abc")).isTrue(); @@ -117,8 +130,8 @@ public class StringUtilsTest { public void testInputStream2String() throws IOException { assertNull(StringUtils.inputStream2String(null)); String data = "abc\n" - + ":\"klsdf\n" - + "2ks,x:\".,-3sd˚ø≤ø¬≥"; + + ":\"klsdf\n" + + "2ks,x:\".,-3sd˚ø≤ø¬≥"; ByteArrayInputStream inputStream = new ByteArrayInputStream(data.getBytes(Constants.DEFAULT_CHARSET)); assertThat(StringUtils.inputStream2String(inputStream)).isEqualTo(data); } @@ -127,8 +140,8 @@ public class StringUtilsTest { void inputStream2Bytes() { assertNull(StringUtils.inputStream2Bytes(null)); String data = "abc\n" - + ":\"klsdf\n" - + "2ks,x:\".,-3sd˚ø≤ø¬≥"; + + ":\"klsdf\n" + + "2ks,x:\".,-3sd˚ø≤ø¬≥"; byte[] bs = data.getBytes(Constants.DEFAULT_CHARSET); ByteArrayInputStream inputStream = new ByteArrayInputStream(data.getBytes(Constants.DEFAULT_CHARSET)); assertThat(StringUtils.inputStream2Bytes(inputStream)).isEqualTo(bs); @@ -249,7 +262,6 @@ public class StringUtilsTest { Assertions.assertEquals("{\"aaa\"->111, \"bbb\"->true, \"self\"->(this HashMap), \"list\"->[(ref HashMap), 'c']}", StringUtils.toString(map)); Assertions.assertFalse(CycleDependencyHandler.isStarting()); - //case: Object Assertions.assertEquals("CycleDependency(s=\"a\", obj=null)", StringUtils.toString(CycleDependency.A)); //case: Object, and cycle dependency @@ -300,8 +312,7 @@ public class StringUtilsTest { } @Retention(RetentionPolicy.RUNTIME) - @Target(ElementType.TYPE) - @interface TestAnnotation { + @Target(ElementType.TYPE) @interface TestAnnotation { boolean test() default false; } @@ -374,21 +385,21 @@ public class StringUtilsTest { public String toString() { toStringTriggered = true; return "(" + - "s=" + s + "," + - "obj=" + (obj != this ? String.valueOf(obj) : "(this CycleDependency)") + - ')'; + "s=" + s + "," + + "obj=" + (obj != this ? String.valueOf(obj) : "(this CycleDependency)") + + ')'; } } @Test void checkDataSize() { - assertThat(StringUtils.checkDataSize("","testdata",10,false)).isEqualTo(Boolean.TRUE); - assertThat(StringUtils.checkDataSize("1234567","testdata",17,false)).isEqualTo(Boolean.TRUE); - assertThat(StringUtils.checkDataSize("1234567","testdata",4,false)).isEqualTo(Boolean.FALSE); + assertThat(StringUtils.checkDataSize("", "testdata", 10, false)).isEqualTo(Boolean.TRUE); + assertThat(StringUtils.checkDataSize("1234567", "testdata", 17, false)).isEqualTo(Boolean.TRUE); + assertThat(StringUtils.checkDataSize("1234567", "testdata", 4, false)).isEqualTo(Boolean.FALSE); Assertions.assertThrows(IllegalArgumentException.class, () -> - StringUtils.checkDataSize("1234567","testdata",6,true) + StringUtils.checkDataSize("1234567", "testdata", 6, true) ); - assertThat( StringUtils.checkDataSize("1234567","testdata",6,false)).isEqualTo(Boolean.FALSE); + assertThat(StringUtils.checkDataSize("1234567", "testdata", 6, false)).isEqualTo(Boolean.FALSE); } @Test @@ -404,4 +415,62 @@ public class StringUtilsTest { Assertions.assertFalse(StringUtils.hasUpperCase("a")); Assertions.assertTrue(StringUtils.hasUpperCase("A")); } + + @Test + void joinNullIteratorReturnsNull() { + Assertions.assertNull(StringUtils.join(null, ",")); + } + + @Test + void joinEmptyReturnsEmptyString() { + Assertions.assertEquals("", StringUtils.join(emptyIterator, ",")); + } + + @Test + void joinSingleReturnsSingleElement() { + Assertions.assertEquals("Hello", StringUtils.join(singleElementIterator, ",")); + } + + @Test + void joinMultipleWithSeparatorReturnsSeparator() { + Assertions.assertEquals("Hello,World,Java", StringUtils.join(multipleElementsIterator, ",")); + } + + @Test + void joinMultipleSeparatorReturnsSeparator() { + Assertions.assertEquals("HelloWorldJava", StringUtils.join(multipleElementsIterator, null)); + } + + @Test + void joinMultipleAndNullReturnsJoinedString() { + Iterator<String> mixedIterator = Arrays.asList("Hello", "", "World", null, "Java").iterator(); + Assertions.assertEquals("Hello,,World,,Java", StringUtils.join(mixedIterator, ",")); + } + + @Test + void hasLengthNullCharSequenceReturnsFalse() { + String nullCharSequence = null; + String emptyCharSequence = ""; + String singleCharSequence = "a"; + String multipleCharSequence = "abc"; + Assertions.assertFalse(StringUtils.hasLength(nullCharSequence)); + Assertions.assertFalse(StringUtils.hasLength(emptyCharSequence)); + Assertions.assertTrue(StringUtils.hasLength(singleCharSequence)); + Assertions.assertTrue(StringUtils.hasLength(multipleCharSequence)); + } + + @Test + void hasTextNullCharSequenceReturnsFalse() { + String nullCharSequence = null; + String emptyCharSequence = ""; + String singleCharSequence = "a"; + String multipleCharSequence = "abc"; + String whitespaceCharSequence = " a b c "; + Assertions.assertFalse(StringUtils.hasText(nullCharSequence)); + Assertions.assertFalse(StringUtils.hasText(emptyCharSequence)); + Assertions.assertTrue(StringUtils.hasText(singleCharSequence)); + Assertions.assertTrue(StringUtils.hasText(multipleCharSequence)); + Assertions.assertFalse(StringUtils.hasText(" ")); + Assertions.assertTrue(StringUtils.hasText(whitespaceCharSequence)); + } } --------------------------------------------------------------------- To unsubscribe, e-mail: notifications-unsubscr...@seata.apache.org For additional commands, e-mail: notifications-h...@seata.apache.org