[AAI] Improve test coverage for A&AI component aai-traversal 43/140643/3 1.16.0
authornisha.gangore <nisha.gangore@accenture.com>
Wed, 2 Apr 2025 08:49:32 +0000 (14:19 +0530)
committernisha.gangore <nisha.gangore@accenture.com>
Mon, 7 Apr 2025 05:55:34 +0000 (11:25 +0530)
- to Improve test coverage for A&AI component aai-traversal <=80%

Issue-ID: AAI-4106
Change-Id: I585ad5be4ca881f14d39791bc4f92f183b3600fb
Signed-off-by: nisha.gangore <nisha.gangore@accenture.com>
aai-traversal/src/test/java/org/onap/aai/TraversalAppTest.java [new file with mode: 0644]
aai-traversal/src/test/java/org/onap/aai/transforms/LowerCamelToLowerHyphenConverterTest.java [new file with mode: 0644]
aai-traversal/src/test/java/org/onap/aai/transforms/MapTraverserTest.java
aai-traversal/src/test/java/org/onap/aai/util/MakeNamedQueryTest.java [new file with mode: 0644]

diff --git a/aai-traversal/src/test/java/org/onap/aai/TraversalAppTest.java b/aai-traversal/src/test/java/org/onap/aai/TraversalAppTest.java
new file mode 100644 (file)
index 0000000..496d92e
--- /dev/null
@@ -0,0 +1,121 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2025 Deutsche Telekom. All rights reserved.
+ * ================================================================================
+ * Licensed 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.aai;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.onap.aai.config.SpringContextAware;
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.nodes.NodeIngestor;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.core.env.Environment;
+import org.springframework.test.context.TestPropertySource;
+import java.lang.reflect.Method;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+@SpringBootTest(
+        classes = TraversalApp.class)
+@TestPropertySource(locations = "classpath:application-test.properties")
+public class TraversalAppTest extends AAISetup {
+
+    @Mock
+    private NodeIngestor mockNodeIngestor;
+
+    private TraversalApp app;
+
+    static Environment mockEnv = mock(Environment.class);
+
+    @BeforeEach
+    public void setUp() throws NoSuchFieldException, IllegalAccessException {
+        app = new TraversalApp();
+        when(mockEnv.getProperty("spring.application.name")).thenReturn("aai-traversal");
+        when(mockEnv.getProperty("server.port")).thenReturn("8080");
+        injectMockIntoPrivateField(app, "env", mockEnv);
+        injectMockIntoPrivateField(app, "nodeIngestor", mockNodeIngestor);
+        injectMockIntoPrivateField(app, "context", mock(SpringContextAware.class));
+        injectMockIntoPrivateField(app, "loaderFactory", mock(SpringContextAware.class));
+    }
+
+    private void injectMockIntoPrivateField(Object target, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {
+        var field = target.getClass().getDeclaredField(fieldName);
+        field.setAccessible(true);
+        field.set(target, value);
+    }
+
+    private Object invokePrivateMethodAndReturnResult(Object target, String methodName, Class<?>[] parameterTypes, Object[] args) throws Exception {
+        Method method = target.getClass().getDeclaredMethod(methodName, parameterTypes);
+        method.setAccessible(true);
+        return method.invoke(target, args);
+    }
+
+    @Test
+    public void testSchemaServiceExceptionTranslator() throws Exception {
+        Exception ex = new Exception("Test exception");
+        AAIException result = (AAIException) invokePrivateMethodAndReturnResult(app, "schemaServiceExceptionTranslator",
+                new Class<?>[]{Exception.class}, new Object[]{ex});
+        assertEquals("AAI_3025", result.getCode());
+
+        Exception nodeEx = new Exception("NodeIngestor failure");
+        AAIException nodeResult = (AAIException) invokePrivateMethodAndReturnResult(app, "schemaServiceExceptionTranslator",
+                new Class<?>[]{Exception.class}, new Object[]{nodeEx});
+        assertEquals("AAI_3026", nodeResult.getCode());
+
+        Exception edgeEx = new Exception("EdgeIngestor failure");
+        AAIException edgeResult = (AAIException) invokePrivateMethodAndReturnResult(app, "schemaServiceExceptionTranslator",
+                new Class<?>[]{Exception.class}, new Object[]{edgeEx});
+        assertEquals("AAI_3027", edgeResult.getCode());
+
+        Exception connEx = new Exception("Connection refused");
+        AAIException connResult = (AAIException) invokePrivateMethodAndReturnResult(app, "schemaServiceExceptionTranslator",
+                new Class<?>[]{Exception.class}, new Object[]{connEx});
+        assertEquals("AAI_3025", connResult.getCode());
+    }
+
+    @Test
+    public void testSetDefaultProps() {
+        System.setProperty("user.dir", "/path/to/aai-traversal");
+        System.clearProperty("BUNDLECONFIG_DIR");
+        TraversalApp.setDefaultProps();
+        assertEquals("src/main/resources", System.getProperty("BUNDLECONFIG_DIR"));
+
+        System.setProperty("user.dir", "/path/to/other");
+        System.clearProperty("BUNDLECONFIG_DIR");
+        TraversalApp.setDefaultProps();
+        assertEquals("aai-traversal/src/main/resources", System.getProperty("BUNDLECONFIG_DIR"));
+    }
+
+    @Test
+    public void testSetDefaultPropsWhenNotSet() {
+        System.setProperty("user.dir", "/path/to/other");
+        System.clearProperty("BUNDLECONFIG_DIR");
+        TraversalApp.setDefaultProps();
+        assertEquals("aai-traversal/src/main/resources", System.getProperty("BUNDLECONFIG_DIR"));
+    }
+
+    @Test
+    public void testSetDefaultPropsWithNullFileSeparator() {
+        System.clearProperty("file.separator");
+        TraversalApp.setDefaultProps();
+        assertEquals("/", System.getProperty("file.separator"));
+    }
+}
diff --git a/aai-traversal/src/test/java/org/onap/aai/transforms/LowerCamelToLowerHyphenConverterTest.java b/aai-traversal/src/test/java/org/onap/aai/transforms/LowerCamelToLowerHyphenConverterTest.java
new file mode 100644 (file)
index 0000000..8673703
--- /dev/null
@@ -0,0 +1,62 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2025 Deutsche Telekom. All rights reserved.
+ * ================================================================================
+ * Licensed 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.aai.transforms;
+
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+
+public class LowerCamelToLowerHyphenConverterTest {
+
+    private final LowerCamelToLowerHyphenConverter converter = new LowerCamelToLowerHyphenConverter();
+
+    // Test for valid input (camelCase to lower-hyphen)
+    @Test
+    public void testConvert_validInput() {
+        assertEquals("my-variable-name", converter.convert("myVariableName"));
+        assertEquals("this-is-a-test", converter.convert("thisIsATest"));
+    }
+
+    // Test for null input
+    @Test
+    public void testConvert_nullInput() {
+        assertNull(converter.convert(null));
+    }
+
+    // Test for an empty string
+    @Test
+    public void testConvert_emptyString() {
+        assertEquals("", converter.convert(""));
+    }
+
+    // Test for no camel case (lowercase input should remain unchanged)
+    @Test
+    public void testConvert_lowercaseInput() {
+        assertEquals("lowercase", converter.convert("lowercase"));
+    }
+
+    // Test for single-word input (should remain unchanged)
+    @Test
+    public void testConvert_singleWord() {
+        assertEquals("test", converter.convert("test"));
+    }
+
+}
index 97150fe..1a6c41b 100644 (file)
 package org.onap.aai.transforms;
 
 import com.bazaarvoice.jolt.JsonUtils;
-
+import org.junit.jupiter.api.Test;
 import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
-
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class MapTraverserTest {
 
@@ -33,15 +35,16 @@ public class MapTraverserTest {
     private String[] testCases = {"TestCase1.json", "TestCase2.json"};
     private MapTraverser traverser = new MapTraverser(new LowerCamelToLowerHyphenConverter());
 
-    @Test(expected = NullPointerException.class)
-    public void testIfMapIsNullThrowNullPointerException() {
+    @Test
+    void testIfMapIsNullThrowNullPointerException() {
+        // Test case where the map is null and should throw a NullPointerException
         Map<String, Object> map = null;
-        traverser.convertKeys(map);
+        assertThrows(NullPointerException.class, () -> traverser.convertKeys(map));
     }
 
     @Test
-    public void runTestCases() throws IOException {
-
+    void runTestCases() throws IOException {
+        // Run multiple test cases
         for (String testCase : testCases) {
             Map<String, Object> values = JsonUtils.filepathToMap(testResources + testCase);
 
@@ -51,4 +54,70 @@ public class MapTraverserTest {
             JoltTestUtil.runArrayOrderObliviousDiffy("failed case " + testCase, output, actual);
         }
     }
+
+    @Test
+    void testListWithNestedMaps() {
+        // Test case where list contains maps
+        Map<String, Object> input = Map.of(
+                "key1", List.of(Map.of("nestedKey", "value1"), Map.of("nestedKey", "value2")),
+                "key2", "value"
+        );
+
+        Map<String, Object> expectedOutput = Map.of(
+                "key1", List.of(Map.of("nested-key", "value1"), Map.of("nested-key", "value2")),
+                "key2", "value"
+        );
+
+        Map<String, Object> actual = traverser.convertKeys(input);
+        assertEquals(expectedOutput, actual, "Test failed for list with nested maps.");
+    }
+
+    @Test
+    void testEmptyList() {
+        // Test case for an empty list
+        Map<String, Object> input = Map.of(
+                "key1", List.of(),
+                "key2", "value"
+        );
+
+        Map<String, Object> expectedOutput = Map.of(
+                "key1", List.of(),
+                "key2", "value"
+        );
+
+        Map<String, Object> actual = traverser.convertKeys(input);
+        assertEquals(expectedOutput, actual, "Test failed for empty list.");
+    }
+
+    @Test
+    void testListWithPrimitives() {
+        // Test case for a list of primitive values
+        Map<String, Object> input = Map.of(
+                "key1", List.of("string1", "string2", "string3"),
+                "key2", "value"
+        );
+
+        Map<String, Object> expectedOutput = Map.of(
+                "key1", List.of("string1", "string2", "string3"),
+                "key2", "value"
+        );
+
+        Map<String, Object> actual = traverser.convertKeys(input);
+        assertEquals(expectedOutput, actual, "Test failed for list with primitive values.");
+    }
+
+    @Test
+    void testNullListInMap() {
+        // Test case where the list is null inside the map
+        Map<String, Object> input = new HashMap<>();
+        input.put("key1", null);  // Null list in the map
+        input.put("key2", "value");
+
+        Map<String, Object> expectedOutput = new HashMap<>();
+        expectedOutput.put("key1", null);  // key1 should remain null
+        expectedOutput.put("key2", "value");
+
+        Map<String, Object> actual = traverser.convertKeys(input);
+        assertEquals(expectedOutput, actual, "Test failed for null list in map.");
+    }
 }
diff --git a/aai-traversal/src/test/java/org/onap/aai/util/MakeNamedQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/util/MakeNamedQueryTest.java
new file mode 100644 (file)
index 0000000..8473e8f
--- /dev/null
@@ -0,0 +1,242 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2025 Deutsche Telekom. All rights reserved.
+ * ================================================================================
+ * Licensed 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.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.aai.util;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.Loader;
+import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+public class MakeNamedQueryTest {
+
+    @InjectMocks
+    private MakeNamedQuery makeNamedQuery;
+
+    @Mock
+    private Loader mockLoader;
+
+    @Mock
+    private Introspector mockIntrospector;
+
+    @Mock
+    private Introspector mockRelationshipListIntrospector;
+
+    @Mock
+    private Introspector mockNewRelationshipDatum1;
+
+    @Mock
+    private AnnotationConfigApplicationContext mockContext;
+
+    @BeforeEach
+    public void setup() {
+        MockitoAnnotations.openMocks(this);
+    }
+
+    @Test
+    public void testSetupNQElementsWithReflection() throws Exception {
+        when(mockIntrospector.getWrappedValue("named-query-elements")).thenReturn(mockIntrospector);
+        when(mockIntrospector.getValue("named-query-element")).thenReturn(new ArrayList<>());
+        when(mockLoader.introspectorFromName("named-query-element")).thenReturn(mockIntrospector);
+        when(mockIntrospector.getLoader()).thenReturn(mockLoader);
+        when(mockLoader.introspectorFromName("relationship-list")).thenReturn(mockRelationshipListIntrospector);
+        when(mockRelationshipListIntrospector.getUnderlyingObject()).thenReturn(new ArrayList<>());
+
+        Method setupNQElementsMethod = MakeNamedQuery.class.getDeclaredMethod("setupNQElements", Introspector.class, List.class);
+        setupNQElementsMethod.setAccessible(true);
+
+        List<Introspector> mockRelationships = new ArrayList<>();
+        Introspector result = (Introspector) setupNQElementsMethod.invoke(makeNamedQuery, mockIntrospector, mockRelationships);
+
+        assertNotNull(result);
+    }
+
+    @Test
+    public void testSetupNQElementsElseBlock() throws Exception {
+        when(mockIntrospector.getLoader()).thenReturn(mockLoader);
+        when(mockLoader.introspectorFromName("named-query-element")).thenReturn(mockIntrospector);
+        when(mockIntrospector.getValue("named-query-element")).thenReturn(new ArrayList<>());
+        when(mockIntrospector.getWrappedValue("named-query-elements")).thenReturn(mockIntrospector);
+        when(mockIntrospector.getLoader()).thenReturn(mockLoader);
+        when(mockLoader.introspectorFromName("relationship-list")).thenReturn(mockIntrospector);
+
+        List<Introspector> mockRelationships = new ArrayList<>();
+        invokePrivateSetupNQElements(mockIntrospector, mockRelationships);
+
+        assertNotNull(mockRelationships);
+
+        verify(mockLoader).introspectorFromName("named-query-element");
+    }
+
+    private void invokePrivateSetupNQElements(Introspector introspector, List<Introspector> relationships) {
+        try {
+            Method method = MakeNamedQuery.class.getDeclaredMethod("setupNQElements", Introspector.class, List.class);
+            method.setAccessible(true);
+            method.invoke(makeNamedQuery, introspector, relationships);
+        } catch (Exception e) {
+            e.printStackTrace();
+            fail("Exception occurred during reflection: " + e.getMessage());
+        }
+    }
+
+    @Test
+    public void testSetupNQElementsWithAAIUnknownObjectException() throws Exception {
+        when(mockIntrospector.getWrappedValue("named-query-elements")).thenReturn(null);
+        when(mockIntrospector.newIntrospectorInstanceOfProperty("named-query-elements")).thenThrow(AAIUnknownObjectException.class);
+
+        Method setupNQElementsMethod = MakeNamedQuery.class.getDeclaredMethod("setupNQElements", Introspector.class, List.class);
+        setupNQElementsMethod.setAccessible(true);
+
+        List<Introspector> mockRelationships = new ArrayList<>();
+
+        try {
+            setupNQElementsMethod.invoke(makeNamedQuery, mockIntrospector, mockRelationships);
+        } catch (Exception e) {
+            assertTrue(e.getCause() instanceof AAIUnknownObjectException);
+        }
+    }
+
+    @Test
+    public void testSetupNQElementsWithIllegalArgumentException() throws Exception {
+        when(mockIntrospector.getWrappedValue("named-query-elements")).thenReturn(null);
+        when(mockIntrospector.newIntrospectorInstanceOfProperty("named-query-elements")).thenThrow(IllegalArgumentException.class);
+
+        Method setupNQElementsMethod = MakeNamedQuery.class.getDeclaredMethod("setupNQElements", Introspector.class, List.class);
+        setupNQElementsMethod.setAccessible(true);
+
+        List<Introspector> mockRelationships = new ArrayList<>();
+
+        try {
+            setupNQElementsMethod.invoke(makeNamedQuery, mockIntrospector, mockRelationships);
+        } catch (Exception e) {
+            assertTrue(e.getCause() instanceof IllegalArgumentException);
+        }
+    }
+
+    @Test
+    public void testMakeWidgetRelationshipWithReflection() throws Exception {
+        String modelInvariantId = "dummyModelInvariantId";
+        String modelVersionId = "dummyModelVersionId";
+
+        when(mockLoader.introspectorFromName("relationship")).thenReturn(mockIntrospector);
+        when(mockIntrospector.getValue("relationship-data")).thenReturn(new ArrayList<>());
+        when(mockLoader.introspectorFromName("named-query-element")).thenReturn(mockIntrospector);
+        when(mockIntrospector.getLoader()).thenReturn(mockLoader);
+        when(mockLoader.introspectorFromName("relationship-list")).thenReturn(mockRelationshipListIntrospector);
+        when(mockRelationshipListIntrospector.getUnderlyingObject()).thenReturn(new ArrayList<>());
+        when(mockLoader.introspectorFromName("relationship-data")).thenReturn(mockNewRelationshipDatum1);
+
+        doNothing().when(mockNewRelationshipDatum1).setValue("relationship-key", "model.model-invariant-id");
+        doNothing().when(mockNewRelationshipDatum1).setValue("relationship-value", modelInvariantId);
+
+        Method makeWidgetRelationshipMethod = MakeNamedQuery.class.getDeclaredMethod(
+                "makeWidgetRelationship", Loader.class, String.class, String.class);
+
+        makeWidgetRelationshipMethod.setAccessible(true);
+
+        Introspector result = (Introspector) makeWidgetRelationshipMethod.invoke(null, mockLoader, modelInvariantId, modelVersionId);
+
+        assertNotNull(result);
+    }
+
+    @Test
+    public void testMakeWidgetRelationshipWithAAIUnknownObjectException() throws Exception {
+        String modelInvariantId = "dummyModelInvariantId";
+        String modelVersionId = "dummyModelVersionId";
+
+        when(mockLoader.introspectorFromName("relationship")).thenThrow(AAIUnknownObjectException.class);
+
+        Method makeWidgetRelationshipMethod = MakeNamedQuery.class.getDeclaredMethod(
+                "makeWidgetRelationship", Loader.class, String.class, String.class);
+
+        makeWidgetRelationshipMethod.setAccessible(true);
+
+        try {
+            makeWidgetRelationshipMethod.invoke(null, mockLoader, modelInvariantId, modelVersionId);
+        } catch (Exception e) {
+            assertTrue(e.getCause() instanceof AAIUnknownObjectException);
+        }
+    }
+
+    @Test
+    public void testMakeWidgetRelationshipWithIllegalArgumentException() throws Exception {
+        String modelInvariantId = "dummyModelInvariantId";
+        String modelVersionId = "dummyModelVersionId";
+
+        when(mockLoader.introspectorFromName("relationship")).thenThrow(IllegalArgumentException.class);
+
+        Method makeWidgetRelationshipMethod = MakeNamedQuery.class.getDeclaredMethod(
+                "makeWidgetRelationship", Loader.class, String.class, String.class);
+
+        makeWidgetRelationshipMethod.setAccessible(true);
+
+        try {
+            makeWidgetRelationshipMethod.invoke(null, mockLoader, modelInvariantId, modelVersionId);
+        } catch (Exception e) {
+            assertTrue(e.getCause() instanceof IllegalArgumentException);
+        }
+    }
+
+    @Test
+    public void testLoadNQElementWithAAIUnknownObjectException() throws Exception {
+        when(mockIntrospector.getLoader()).thenReturn(mockLoader);
+        when(mockLoader.introspectorFromName("named-query-element")).thenThrow(AAIUnknownObjectException.class);
+
+        Method loadNQElementMethod = MakeNamedQuery.class.getDeclaredMethod("loadNQElement", Introspector.class, List.class);
+
+        loadNQElementMethod.setAccessible(true);
+
+        List<Introspector> mockRelationships = new ArrayList<>();
+
+        try {
+            loadNQElementMethod.invoke(makeNamedQuery, mockIntrospector, mockRelationships);
+        } catch (Exception e) {
+            assertTrue(e.getCause() instanceof AAIUnknownObjectException);
+        }
+    }
+
+    @Test
+    public void testLoadNQElementWithIllegalArgumentException() throws Exception {
+        when(mockIntrospector.getLoader()).thenReturn(mockLoader);
+        when(mockLoader.introspectorFromName("named-query-element")).thenThrow(IllegalArgumentException.class);
+
+        Method loadNQElementMethod = MakeNamedQuery.class.getDeclaredMethod("loadNQElement", Introspector.class, List.class);
+
+        loadNQElementMethod.setAccessible(true);
+
+        List<Introspector> mockRelationships = new ArrayList<>();
+
+        try {
+            loadNQElementMethod.invoke(makeNamedQuery, mockIntrospector, mockRelationships);
+        } catch (Exception e) {
+            assertTrue(e.getCause() instanceof IllegalArgumentException);
+        }
+    }
+}