This is an automated email from the ASF dual-hosted git repository.
wuzhiguo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/bigtop-manager.git
The following commit(s) were added to refs/heads/main by this push:
new c897f1c6 BIGTOP-4335: Add ut cases for utils classes in common module
(#155)
c897f1c6 is described below
commit c897f1c6a81537e573b0e627ae41a907affc7524
Author: xianrenzw <[email protected]>
AuthorDate: Wed Jan 29 19:53:49 2025 +0800
BIGTOP-4335: Add ut cases for utils classes in common module (#155)
---
.../manager/common/utils/ProjectPathUtils.java | 2 +-
.../bigtop/manager/common/utils/CaseUtilsTest.java | 81 +++++++
.../manager/common/utils/ClassUtilsTest.java | 98 ++++++++
.../bigtop/manager/common/utils/DateUtilsTest.java | 87 +++++++
.../bigtop/manager/common/utils/FileUtilsTest.java | 102 +++++++++
.../bigtop/manager/common/utils/JsonUtilsTest.java | 249 +++++++++++++++++++++
.../bigtop/manager/common/utils/NetUtilsTest.java | 120 ++++++++++
.../manager/common/utils/ProjectPathUtilsTest.java | 140 ++++++++++++
8 files changed, 878 insertions(+), 1 deletion(-)
diff --git
a/bigtop-manager-common/src/main/java/org/apache/bigtop/manager/common/utils/ProjectPathUtils.java
b/bigtop-manager-common/src/main/java/org/apache/bigtop/manager/common/utils/ProjectPathUtils.java
index 44d03999..6bf3bf3f 100644
---
a/bigtop-manager-common/src/main/java/org/apache/bigtop/manager/common/utils/ProjectPathUtils.java
+++
b/bigtop-manager-common/src/main/java/org/apache/bigtop/manager/common/utils/ProjectPathUtils.java
@@ -74,7 +74,7 @@ public class ProjectPathUtils {
}
}
- private static String getProjectStoreDir() {
+ protected static String getProjectStoreDir() {
String path = SystemUtils.getUserHome().getPath() + File.separator +
".bigtop-manager";
Path p = Paths.get(path);
if (!Files.exists(p)) {
diff --git
a/bigtop-manager-common/src/test/java/org/apache/bigtop/manager/common/utils/CaseUtilsTest.java
b/bigtop-manager-common/src/test/java/org/apache/bigtop/manager/common/utils/CaseUtilsTest.java
new file mode 100644
index 00000000..635a2f40
--- /dev/null
+++
b/bigtop-manager-common/src/test/java/org/apache/bigtop/manager/common/utils/CaseUtilsTest.java
@@ -0,0 +1,81 @@
+/*
+ * 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
+ *
+ * https://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.bigtop.manager.common.utils;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+public class CaseUtilsTest {
+
+ @Test
+ public void testToLowerCase() {
+ // Normal case
+ assertEquals("hello world", CaseUtils.toLowerCase("Hello World"));
+ // Input is an empty string
+ assertEquals("", CaseUtils.toLowerCase(""));
+ // Input is null
+ assertNull(CaseUtils.toLowerCase(null));
+ }
+
+ @Test
+ public void testToUpperCase() {
+ // Normal case
+ assertEquals("HELLO WORLD", CaseUtils.toUpperCase("Hello World"));
+ // Input is an empty string
+ assertEquals("", CaseUtils.toUpperCase(""));
+ // Input is null
+ assertNull(CaseUtils.toUpperCase(null));
+ }
+
+ @Test
+ public void testToCamelCase() {
+ // Normal case
+ assertEquals("HelloWorld", CaseUtils.toCamelCase("hello-world"));
+ // Using underscore separator
+ assertEquals("HelloWorld", CaseUtils.toCamelCase("hello_world",
CaseUtils.SEPARATOR_UNDERSCORE));
+ // First letter lowercase
+ assertEquals("helloWorld", CaseUtils.toCamelCase("hello-world",
CaseUtils.SEPARATOR_HYPHEN, false));
+ // Input is an empty string
+ assertEquals("", CaseUtils.toCamelCase(""));
+ // Input is null
+ assertNull(CaseUtils.toCamelCase(null));
+ }
+
+ @Test
+ public void testToHyphenCase() {
+ // Normal case
+ assertEquals("hello-world", CaseUtils.toHyphenCase("HelloWorld"));
+ // Input is an empty string
+ assertEquals("", CaseUtils.toHyphenCase(""));
+ // Input is null
+ assertNull(CaseUtils.toHyphenCase(null));
+ }
+
+ @Test
+ public void testToUnderScoreCase() {
+ // Normal case
+ assertEquals("hello_world", CaseUtils.toUnderScoreCase("HelloWorld"));
+ // Input is an empty string
+ assertEquals("", CaseUtils.toUnderScoreCase(""));
+ // Input is null
+ assertNull(CaseUtils.toUnderScoreCase(null));
+ }
+}
diff --git
a/bigtop-manager-common/src/test/java/org/apache/bigtop/manager/common/utils/ClassUtilsTest.java
b/bigtop-manager-common/src/test/java/org/apache/bigtop/manager/common/utils/ClassUtilsTest.java
new file mode 100644
index 00000000..6cd7d6d9
--- /dev/null
+++
b/bigtop-manager-common/src/test/java/org/apache/bigtop/manager/common/utils/ClassUtilsTest.java
@@ -0,0 +1,98 @@
+/*
+ * 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
+ *
+ * https://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.bigtop.manager.common.utils;
+
+import org.junit.jupiter.api.Test;
+
+import java.lang.reflect.Field;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class ClassUtilsTest {
+
+ // Test case for a normal class
+ @Test
+ public void testGetFieldsNormalClass() {
+ List<Field> fields = ClassUtils.getFields(TestClass.class);
+ assertEquals(3, fields.size());
+ }
+
+ // Test case for a class with no fields
+ @Test
+ public void testGetFieldsNoFieldsClass() {
+ List<Field> fields = ClassUtils.getFields(NoFieldsClass.class);
+ assertEquals(0, fields.size());
+ }
+
+ // Test case for an inherited class
+ @Test
+ public void testGetFieldsInheritedClass() {
+ List<Field> fields = ClassUtils.getFields(InheritedClass.class);
+ assertEquals(5, fields.size());
+ }
+
+ // Test case for an interface
+ @Test
+ public void testGetFieldsInterface() {
+ List<Field> fields = ClassUtils.getFields(TestInterface.class);
+ assertEquals(0, fields.size());
+ }
+
+ // Test case for null input
+ @Test
+ public void testGetFieldsNullInput() {
+ List<Field> fields = ClassUtils.getFields(null);
+ assertEquals(0, fields.size());
+ }
+
+ // Test case for a primitive type
+ @Test
+ public void testGetFieldsPrimitiveType() {
+ List<Field> fields = ClassUtils.getFields(int.class);
+ assertEquals(0, fields.size()); // int is a primitive type, which has
no fields
+ }
+
+ // Test case for a wrapper type
+ @Test
+ public void testGetFieldsWrapperType() {
+ List<Field> fields = ClassUtils.getFields(Integer.class);
+ assertTrue(fields.size() > 0);
+ }
+
+ // Helper test class
+ private static class TestClass {
+ private int field1;
+ private String field2;
+ private double field3;
+ }
+
+ // Helper test class with no fields
+ private static class NoFieldsClass {}
+
+ // Helper test class that inherits from TestClass
+ private static class InheritedClass extends TestClass {
+ private boolean field4;
+ private char field5;
+ }
+
+ // Helper test interface
+ private static interface TestInterface {}
+}
diff --git
a/bigtop-manager-common/src/test/java/org/apache/bigtop/manager/common/utils/DateUtilsTest.java
b/bigtop-manager-common/src/test/java/org/apache/bigtop/manager/common/utils/DateUtilsTest.java
new file mode 100644
index 00000000..42b9a3a4
--- /dev/null
+++
b/bigtop-manager-common/src/test/java/org/apache/bigtop/manager/common/utils/DateUtilsTest.java
@@ -0,0 +1,87 @@
+/*
+ * 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
+ *
+ * https://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.bigtop.manager.common.utils;
+
+import org.junit.jupiter.api.Test;
+
+import java.sql.Timestamp;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.TimeZone;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+public class DateUtilsTest {
+
+ @Test
+ public void testFormatTimestamp() {
+ Timestamp timestamp = Timestamp.valueOf("2023-01-01 12:00:00");
+
+ String formatted = DateUtils.format(timestamp);
+ assertEquals("2023-01-01 12:00:00", formatted);
+
+ String customFormatted = DateUtils.format(timestamp, "yyyy-MM-dd");
+ assertEquals("2023-01-01", customFormatted);
+ }
+
+ @Test
+ public void testFormatDate() {
+ Date date = new Date(1672545600000L);
+ TimeZone systemTimeZone = TimeZone.getDefault();
+
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+ sdf.setTimeZone(systemTimeZone);
+ String expectedFormatted = sdf.format(date);
+ String formatted = DateUtils.format(date);
+ assertEquals(expectedFormatted, formatted);
+
+ SimpleDateFormat sdfSystem = new SimpleDateFormat("yyyy-MM-dd");
+ sdfSystem.setTimeZone(systemTimeZone);
+ String expectedCustomFormatted = sdfSystem.format(date);
+ String customFormatted = DateUtils.format(date, "yyyy-MM-dd");
+ assertEquals(expectedCustomFormatted, customFormatted);
+ }
+
+ @Test
+ public void testFormatNullTimestamp() {
+ String formatted = DateUtils.format((Timestamp) null);
+ assertEquals("", formatted);
+ }
+
+ @Test
+ public void testFormatNullDate() {
+ String formatted = DateUtils.format((Date) null);
+ assertEquals("", formatted);
+ }
+
+ @Test
+ public void testFormatWithNullPattern() {
+ Date date = new Date(1672531200000L);
+ assertThrows(NullPointerException.class, () -> {
+ DateUtils.format(date, null);
+ });
+ }
+
+ @Test
+ public void testFormatWithEmptyStringWhenDateIsNull() {
+ String result = DateUtils.format((Date) null, "yyyy-MM-dd HH:mm:ss");
+ assertEquals("", result);
+ }
+}
diff --git
a/bigtop-manager-common/src/test/java/org/apache/bigtop/manager/common/utils/FileUtilsTest.java
b/bigtop-manager-common/src/test/java/org/apache/bigtop/manager/common/utils/FileUtilsTest.java
new file mode 100644
index 00000000..50e903df
--- /dev/null
+++
b/bigtop-manager-common/src/test/java/org/apache/bigtop/manager/common/utils/FileUtilsTest.java
@@ -0,0 +1,102 @@
+/*
+ * 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
+ *
+ * https://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.bigtop.manager.common.utils;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class FileUtilsTest {
+ private File testFile;
+
+ @BeforeEach
+ void setUp() throws IOException {
+ // Create a test file
+ testFile = new File("testFile.txt");
+ try (FileWriter writer = new FileWriter(testFile,
StandardCharsets.UTF_8)) {
+ writer.write("test file content");
+ }
+ }
+
+ @AfterEach
+ void tearDown() {
+ // Delete test file
+ if (testFile.exists()) {
+ testFile.delete();
+ }
+ }
+
+ @Test
+ void readFile2StrNormalCase() {
+ // Test normal case
+ String result = FileUtils.readFile2Str(testFile);
+ assertEquals("test file content", result);
+ }
+
+ @Test
+ void readFile2StrEmptyFile() throws IOException {
+ // Test empty file
+ try (FileWriter writer = new FileWriter(testFile,
StandardCharsets.UTF_8)) {
+ writer.write("");
+ }
+ String result = FileUtils.readFile2Str(testFile);
+ assertEquals("", result);
+ }
+
+ @Test
+ void readFile2StrFileDoesNotExist() {
+ // Test file does not exist case
+ File nonExistentFile = new File("nonExistentFile.txt");
+ Exception exception = assertThrows(RuntimeException.class, () -> {
+ FileUtils.readFile2Str(nonExistentFile);
+ });
+ assertNotNull(exception);
+ assertTrue(exception.getMessage().contains("nonExistentFile.txt"));
+ }
+
+ @Test
+ void readFile2StrFileContainsSpecialCharacters() throws IOException {
+ // Test file containing special characters
+ try (FileWriter writer = new FileWriter(testFile,
StandardCharsets.UTF_8)) {
+ writer.write("test file content\nwith newline\tand tab");
+ }
+ String result = FileUtils.readFile2Str(testFile);
+ assertEquals("test file content\nwith newline\tand tab", result);
+ }
+
+ @Test
+ void readFile2StrFileContainsChineseCharacters() throws IOException {
+ // Test file containing Chinese characters
+ try (FileWriter writer = new FileWriter(testFile,
StandardCharsets.UTF_8)) {
+ writer.write("测试文件内容");
+ }
+ String result = FileUtils.readFile2Str(testFile);
+ assertEquals("测试文件内容", result);
+ }
+}
diff --git
a/bigtop-manager-common/src/test/java/org/apache/bigtop/manager/common/utils/JsonUtilsTest.java
b/bigtop-manager-common/src/test/java/org/apache/bigtop/manager/common/utils/JsonUtilsTest.java
new file mode 100644
index 00000000..2c59ea34
--- /dev/null
+++
b/bigtop-manager-common/src/test/java/org/apache/bigtop/manager/common/utils/JsonUtilsTest.java
@@ -0,0 +1,249 @@
+/*
+ * 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
+ *
+ * https://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.bigtop.manager.common.utils;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JsonNode;
+import lombok.extern.slf4j.Slf4j;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+@Slf4j
+class JsonUtilsTest {
+
+ private static final String TEST_FILE_NAME = "test.json";
+ private static final String TEST_JSON_STRING =
"{\"name\":\"test\",\"value\":123}";
+ private static final String TEST_JSON_STRING_NULL =
"{\"name\":null,\"value\":123}";
+ private static final String TEST_JSON_STRING_EMPTY = "{}";
+
+ // Test file
+ private File testFile;
+
+ @BeforeEach
+ void setUp() throws IOException {
+ // Create a test file
+ testFile = new File(TEST_FILE_NAME);
+ if (!testFile.exists()) {
+ Files.createFile(testFile.toPath());
+ }
+ }
+
+ @AfterEach
+ void tearDown() {
+ // Delete test file
+ if (testFile.exists()) {
+ testFile.delete();
+ }
+ }
+
+ // Test writing an object to a file and reading it back
+ @Test
+ void testWriteAndReadToFile() {
+ Map<String, Object> testData = new HashMap<>();
+ testData.put("name", "test");
+ testData.put("value", 123);
+
+ JsonUtils.writeToFile(testFile, testData);
+
+ Map<String, Object> readData = JsonUtils.readFromFile(testFile, new
TypeReference<>() {});
+ assertNotNull(readData);
+ assertEquals("test", readData.get("name"));
+ assertEquals(123, readData.get("value"));
+ }
+
+ // Test reading an object from a string
+ @Test
+ void testReadFromString() {
+ Map<String, Object> readData =
JsonUtils.readFromString(TEST_JSON_STRING, new TypeReference<>() {});
+ assertNotNull(readData);
+ assertEquals("test", readData.get("name"));
+ assertEquals(123, readData.get("value"));
+ }
+
+ // Test reading an object from a string as a Map
+ @Test
+ void testReadFromStringToMap() {
+ Map<String, Object> readData =
+ JsonUtils.readFromString(TEST_JSON_STRING, new HashMap<String,
Object>().getClass());
+ assertNotNull(readData);
+ assertEquals("test", readData.get("name"));
+ assertEquals(123, readData.get("value"));
+ }
+
+ // Test reading a JSON tree
+ @Test
+ void testReadTree() {
+ try {
+ Files.writeString(testFile.toPath(), TEST_JSON_STRING);
+ JsonNode jsonNode = JsonUtils.readTree(testFile.getName());
+ assertNotNull(jsonNode);
+ assertEquals("test", jsonNode.get("name").asText());
+ assertEquals(123, jsonNode.get("value").asInt());
+ } catch (IOException e) {
+ log.error("IO exception occurred while reading the file", e);
+ fail();
+ }
+ }
+
+ // Test writing an object to a string
+ @Test
+ void testWriteAsString() {
+ Map<String, Object> testData = new HashMap<>();
+ testData.put("name", "test");
+ testData.put("value", 123);
+
+ String jsonString = JsonUtils.writeAsString(testData);
+ assertNotNull(jsonString);
+ assertEquals("{\"name\":\"test\",\"value\":123}", jsonString);
+ }
+
+ // Test writing an object to a pretty formatted string
+ @Test
+ void testIndentWriteAsString() {
+ Map<String, Object> testData = new HashMap<>();
+ testData.put("name", "test");
+ testData.put("value", 123);
+
+ String jsonString = JsonUtils.indentWriteAsString(testData);
+ assertNotNull(jsonString);
+ String linedSeparator = System.lineSeparator();
+ String expectedJsonString = "{\n \"name\" : \"test\",\n \"value\" :
123\n}".replace("\n", linedSeparator);
+
+ assertEquals(expectedJsonString, jsonString);
+ }
+
+ // Test edge case: object is null
+ @Test
+ void testWriteAndReadNull() {
+ Map<String, Object> testData = null;
+
+ String jsonString = JsonUtils.writeAsString(testData);
+ assertNull(jsonString);
+
+ Map<String, Object> readData = JsonUtils.readFromString(jsonString);
+ assertNull(readData);
+ }
+
+ // Test edge case: JSON string is null
+ @Test
+ void testReadNullString() {
+ Map<String, Object> readData = JsonUtils.readFromString(null, new
TypeReference<>() {});
+ assertNull(readData);
+ }
+
+ // Test edge case: JSON string is empty
+ @Test
+ void testReadEmptyString() {
+ Map<String, Object> readData =
JsonUtils.readFromString(TEST_JSON_STRING_EMPTY, new TypeReference<>() {});
+ assertNotNull(readData);
+ assertTrue(readData.isEmpty());
+ }
+
+ // Test edge case: JSON string contains a null value
+ @Test
+ void testReadStringWithNull() {
+ Map<String, Object> readData =
JsonUtils.readFromString(TEST_JSON_STRING_NULL, new TypeReference<>() {});
+ assertNotNull(readData);
+ assertNull(readData.get("name"));
+ assertEquals(123, readData.get("value"));
+ }
+
+ // Test edge case: reading a non-existent file
+ @Test
+ void testReadNonexistentFile() {
+ File nonExistentFile = new File("nonexistent.json");
+
+ Exception exception = assertThrows(RuntimeException.class, () -> {
+ JsonUtils.readFromFile(nonExistentFile, new TypeReference<>() {});
+ });
+
+ assertNotNull(exception);
+ }
+
+ // Test edge case: reading an empty file
+ @Test
+ void testReadEmptyFile() {
+ try {
+ Files.writeString(testFile.toPath(), "");
+
+ Exception exception = assertThrows(RuntimeException.class, () -> {
+ JsonUtils.readFromFile(testFile, new TypeReference<>() {});
+ });
+
+ assertNotNull(exception);
+ } catch (IOException e) {
+ log.error("IO exception occurred while writing to the file", e);
+ fail();
+ }
+ }
+
+ // Test edge case: reading a file with invalid JSON content
+ @Test
+ void testReadInvalidJsonFile() {
+ try {
+ Files.writeString(testFile.toPath(), "invalid json");
+
+ Exception exception = assertThrows(RuntimeException.class, () -> {
+ JsonUtils.readFromFile(testFile, new TypeReference<>() {});
+ });
+
+ assertNotNull(exception);
+ } catch (IOException e) {
+ log.error("IO exception occurred while writing to the file", e);
+ fail();
+ }
+ }
+
+ // Test edge case: reading a pretty formatted JSON tree
+ @Test
+ void testReadIndentedTree() {
+ try {
+ String indentedJson = JsonUtils.indentWriteAsString(new
HashMap<String, Object>() {
+ {
+ put("name", "test");
+ put("value", 123);
+ }
+ });
+ Files.writeString(testFile.toPath(), indentedJson);
+
+ JsonNode jsonNode = JsonUtils.readTree(testFile.getName());
+ assertNotNull(jsonNode);
+ assertEquals("test", jsonNode.get("name").asText());
+ assertEquals(123, jsonNode.get("value").asInt());
+ } catch (IOException e) {
+ log.error("IO exception occurred while reading the file", e);
+ fail();
+ }
+ }
+}
diff --git
a/bigtop-manager-common/src/test/java/org/apache/bigtop/manager/common/utils/NetUtilsTest.java
b/bigtop-manager-common/src/test/java/org/apache/bigtop/manager/common/utils/NetUtilsTest.java
new file mode 100644
index 00000000..13305364
--- /dev/null
+++
b/bigtop-manager-common/src/test/java/org/apache/bigtop/manager/common/utils/NetUtilsTest.java
@@ -0,0 +1,120 @@
+/*
+ * 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
+ *
+ * https://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.bigtop.manager.common.utils;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.when;
+
+public class NetUtilsTest {
+
+ @BeforeEach
+ public void setup() {
+ // Reset static variables
+ try {
+ // Use reflection to clear the static cached HOST_ADDRESS,
HOST_NAME, and LOCAL_ADDRESS
+ java.lang.reflect.Field hostAddressField =
NetUtils.class.getDeclaredField("HOST_ADDRESS");
+ hostAddressField.setAccessible(true);
+ hostAddressField.set(null, null);
+
+ java.lang.reflect.Field hostNameField =
NetUtils.class.getDeclaredField("HOST_NAME");
+ hostNameField.setAccessible(true);
+ hostNameField.set(null, null);
+
+ java.lang.reflect.Field localAddressField =
NetUtils.class.getDeclaredField("LOCAL_ADDRESS");
+ localAddressField.setAccessible(true);
+ localAddressField.set(null, null);
+ } catch (NoSuchFieldException | IllegalAccessException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Test
+ public void testGetHostSuccess() {
+ InetAddress mockAddress = mock(InetAddress.class);
+ when(mockAddress.getHostAddress()).thenReturn("192.168.0.1");
+
+ // Mock InetAddress.getLocalHost() to return the mock address
+ try (var mockedStatic = mockStatic(InetAddress.class)) {
+
mockedStatic.when(InetAddress::getLocalHost).thenReturn(mockAddress);
+
+ String host = NetUtils.getHost();
+ assertEquals("192.168.0.1", host);
+ }
+ }
+
+ @Test
+ public void testGetHostFailure() {
+ try (var mockedStatic = mockStatic(InetAddress.class)) {
+ mockedStatic.when(InetAddress::getLocalHost).thenThrow(new
UnknownHostException());
+ // Should return default value 127.0.0.1
+ String host = NetUtils.getHost();
+ assertEquals("127.0.0.1", host);
+ }
+ }
+
+ @Test
+ public void testGetHostnameSuccess() {
+ InetAddress mockAddress = mock(InetAddress.class);
+ when(mockAddress.getHostName()).thenReturn("my-hostname");
+
+ // Mock InetAddress.getLocalHost() to return the mock address
+ try (var mockedStatic = mockStatic(InetAddress.class)) {
+
mockedStatic.when(InetAddress::getLocalHost).thenReturn(mockAddress);
+
+ String hostname = NetUtils.getHostname();
+ assertEquals("my-hostname", hostname);
+ }
+ }
+
+ @Test
+ public void testGetHostnameFailure() {
+ try (var mockedStatic = mockStatic(InetAddress.class)) {
+ mockedStatic.when(InetAddress::getLocalHost).thenThrow(new
UnknownHostException());
+ // Should return default value localhost
+ String hostname = NetUtils.getHostname();
+ assertEquals("localhost", hostname);
+ }
+ }
+
+ @Test
+ public void testGetLocalAddressCaching() {
+ InetAddress mockAddress = mock(InetAddress.class);
+ when(mockAddress.getHostName()).thenReturn("my-hostname");
+
+ try (var mockedStatic = mockStatic(InetAddress.class)) {
+
mockedStatic.when(InetAddress::getLocalHost).thenReturn(mockAddress);
+
+ // First call should return the address through mock
+ String hostnameFirstCall = NetUtils.getHostname();
+ assertEquals("my-hostname", hostnameFirstCall);
+
+ // Second call should directly return the cached result
+ String hostnameSecondCall = NetUtils.getHostname();
+ assertEquals("my-hostname", hostnameSecondCall);
+ }
+ }
+}
diff --git
a/bigtop-manager-common/src/test/java/org/apache/bigtop/manager/common/utils/ProjectPathUtilsTest.java
b/bigtop-manager-common/src/test/java/org/apache/bigtop/manager/common/utils/ProjectPathUtilsTest.java
new file mode 100644
index 00000000..2264a475
--- /dev/null
+++
b/bigtop-manager-common/src/test/java/org/apache/bigtop/manager/common/utils/ProjectPathUtilsTest.java
@@ -0,0 +1,140 @@
+/*
+ * 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
+ *
+ * https://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.bigtop.manager.common.utils;
+
+import org.apache.commons.lang3.SystemUtils;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
+
+import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.mockStatic;
+
+public class ProjectPathUtilsTest {
+
+ private MockedStatic<SystemUtils> mockedSystemUtils;
+ private MockedStatic<Environments> mockedEnvironments;
+
+ @BeforeEach
+ public void setup() {
+ mockedSystemUtils = Mockito.mockStatic(SystemUtils.class);
+ mockedEnvironments = Mockito.mockStatic(Environments.class);
+ mockedEnvironments.when(Environments::isDevMode).thenReturn(true);
+ }
+
+ @AfterEach
+ public void cleanup() {
+ mockedSystemUtils.close();
+ mockedEnvironments.close();
+ }
+
+ @Test
+ public void testGetLogFilePath() {
+ Long taskId = 123L;
+ String expectedLogPath = "baseDir" + File.separator + "tasklogs" +
File.separator + "task-" + taskId + ".log";
+
+ mockedSystemUtils.when(SystemUtils::getUserDir).thenReturn(new
File("baseDir"));
+
+ String logFilePath = ProjectPathUtils.getLogFilePath(taskId);
+ assertEquals(expectedLogPath, logFilePath);
+ }
+
+ @Test
+ public void testGetKeyStorePath() {
+ String expectedKeyStorePath = "storeDir" + File.separator +
".bigtop-manager" + File.separator + "keys";
+
+ mockedSystemUtils.when(SystemUtils::getUserHome).thenReturn(new
File("storeDir"));
+
+ String keyStorePath = ProjectPathUtils.getKeyStorePath();
+ assertEquals(expectedKeyStorePath, keyStorePath);
+ Path storeDirPath = Paths.get("storeDir" + File.separator +
".bigtop-manager");
+ try {
+ Files.walk(storeDirPath)
+ .sorted((p1, p2) -> -p1.compareTo(p2))
+ .map(Path::toFile)
+ .forEach(File::delete);
+ Files.delete(Paths.get("storeDir"));
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Test
+ public void testGetAgentCachePath() {
+ String expectedCachePath = "storeDir" + File.separator +
".bigtop-manager" + File.separator + "agent-caches";
+
+ mockedSystemUtils.when(SystemUtils::getUserHome).thenReturn(new
File("storeDir"));
+
+ String agentCachePath = ProjectPathUtils.getAgentCachePath();
+ assertEquals(expectedCachePath, agentCachePath);
+ Path storeDirPath = Paths.get("storeDir" + File.separator +
".bigtop-manager");
+ try {
+ Files.walk(storeDirPath)
+ .sorted((p1, p2) -> -p1.compareTo(p2))
+ .map(Path::toFile)
+ .forEach(File::delete);
+ Files.delete(Paths.get("storeDir"));
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Test
+ public void testGetProjectStoreDir() {
+ String storeDirPath = "userHome" + File.separator + ".bigtop-manager";
+ Path storeDirPathObj = Paths.get(storeDirPath);
+
+ // Mocking the system user home
+ mockedSystemUtils.when(SystemUtils::getUserHome).thenReturn(new
File("userHome"));
+
+ // Mocking Files.exists() to return false (directory doesn't exist)
+ try (MockedStatic<Files> mockedFiles = mockStatic(Files.class)) {
+ mockedFiles.when(() ->
Files.exists(storeDirPathObj)).thenReturn(false);
+ mockedFiles.when(() ->
Files.createDirectories(storeDirPathObj)).thenReturn(storeDirPathObj);
+
+ String projectStoreDir = ProjectPathUtils.getProjectStoreDir();
+ assertEquals(storeDirPath, projectStoreDir);
+ }
+ }
+
+ @Test
+ public void testGetProjectStoreDirExists() {
+ String storeDirPath = "userHome" + File.separator + ".bigtop-manager";
+ Path storeDirPathObj = Paths.get(storeDirPath);
+
+ // Mocking the system user home
+ mockedSystemUtils.when(SystemUtils::getUserHome).thenReturn(new
File("userHome"));
+
+ // Mocking Files.exists() to return true (directory already exists)
+ try (MockedStatic<Files> mockedFiles = mockStatic(Files.class)) {
+ mockedFiles.when(() ->
Files.exists(storeDirPathObj)).thenReturn(true);
+
+ String projectStoreDir = ProjectPathUtils.getProjectStoreDir();
+ assertEquals(storeDirPath, projectStoreDir);
+ }
+ }
+}