From f8cdf39bf2efd493966ebb7ea5b7e20682be34ec Mon Sep 17 00:00:00 2001 From: "akshay.khairnar@t-systems.com" Date: Wed, 16 Jul 2025 11:19:02 +0200 Subject: [PATCH] [AAI] Improve test coverage for A&AI component aai-resources "- to Improve test coverage for A&AI component aai-resources <=80% Issue-ID: AAI-4185 Change-Id: I38d79d48d19a9fb4a465461b81d638fa5c0f62a3 Signed-off-by: akshay.khairnar@t-systems.com --- aai-resources/pom.xml | 6 + .../aai/interceptors/pre/VersionInterceptor.java | 2 +- .../DataImportTasks.java | 8 +- .../aai/interceptors/AAIContainerFilterTest.java | 82 ++++++++++ .../aai/interceptors/pre/HeaderValidationTest.java | 176 +++++++++++++++++++++ .../interceptors/pre/VersionInterceptorTest.java | 120 ++++++++++++++ .../pre/VersionLatestInterceptorTest.java | 90 +++++++++++ .../aai/tenantisolation/DataImportTasksTest.java | 135 ++++++++++++++++ 8 files changed, 614 insertions(+), 5 deletions(-) rename aai-resources/src/main/java/org/onap/aai/{TenantIsolation => tenantisolation}/DataImportTasks.java (97%) create mode 100644 aai-resources/src/test/java/org/onap/aai/interceptors/AAIContainerFilterTest.java create mode 100644 aai-resources/src/test/java/org/onap/aai/interceptors/pre/HeaderValidationTest.java create mode 100644 aai-resources/src/test/java/org/onap/aai/interceptors/pre/VersionInterceptorTest.java create mode 100644 aai-resources/src/test/java/org/onap/aai/interceptors/pre/VersionLatestInterceptorTest.java create mode 100644 aai-resources/src/test/java/org/onap/aai/tenantisolation/DataImportTasksTest.java diff --git a/aai-resources/pom.xml b/aai-resources/pom.xml index 3ab9ec1a..b0a9bc8c 100644 --- a/aai-resources/pom.xml +++ b/aai-resources/pom.xml @@ -441,6 +441,12 @@ ${mockito.core.version} test + + org.mockito + mockito-inline + ${mockito.core.version} + test + org.mockito mockito-junit-jupiter diff --git a/aai-resources/src/main/java/org/onap/aai/interceptors/pre/VersionInterceptor.java b/aai-resources/src/main/java/org/onap/aai/interceptors/pre/VersionInterceptor.java index fc74b2a9..cdada62c 100644 --- a/aai-resources/src/main/java/org/onap/aai/interceptors/pre/VersionInterceptor.java +++ b/aai-resources/src/main/java/org/onap/aai/interceptors/pre/VersionInterceptor.java @@ -81,7 +81,7 @@ public class VersionInterceptor extends AAIContainerFilter implements ContainerR } } - private Response createInvalidVersionResponse(String errorCode, ContainerRequestContext context, String version) { + Response createInvalidVersionResponse(String errorCode, ContainerRequestContext context, String version) { AAIException e = new AAIException(errorCode); ArrayList templateVars = new ArrayList<>(); diff --git a/aai-resources/src/main/java/org/onap/aai/TenantIsolation/DataImportTasks.java b/aai-resources/src/main/java/org/onap/aai/tenantisolation/DataImportTasks.java similarity index 97% rename from aai-resources/src/main/java/org/onap/aai/TenantIsolation/DataImportTasks.java rename to aai-resources/src/main/java/org/onap/aai/tenantisolation/DataImportTasks.java index bcbd8249..8b0a9aee 100644 --- a/aai-resources/src/main/java/org/onap/aai/TenantIsolation/DataImportTasks.java +++ b/aai-resources/src/main/java/org/onap/aai/tenantisolation/DataImportTasks.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.aai.TenantIsolation; +package org.onap.aai.tenantisolation; import java.io.BufferedReader; import java.io.File; @@ -189,7 +189,7 @@ public class DataImportTasks { * @param targetDirFile the directory that contains payload files * @throws AAIException */ - private static void deletePayload(File targetDirFile) throws AAIException { + static void deletePayload(File targetDirFile) throws AAIException { File[] allFilesArr = targetDirFile.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY); if (allFilesArr == null || allFilesArr.length == 0) { @@ -213,7 +213,7 @@ public class DataImportTasks { * * @return true if another process is running, false if not */ - private static boolean unpackPayloadFile(String payLoadFileName) { + static boolean unpackPayloadFile(String payLoadFileName) { Process process = null; @@ -244,7 +244,7 @@ public class DataImportTasks { return true; } - private static boolean isTargzExtension(String fileName) { + static boolean isTargzExtension(String fileName) { boolean found = false; for (String ext : EXTS) { if (fileName.toLowerCase().endsWith("." + ext)) { diff --git a/aai-resources/src/test/java/org/onap/aai/interceptors/AAIContainerFilterTest.java b/aai-resources/src/test/java/org/onap/aai/interceptors/AAIContainerFilterTest.java new file mode 100644 index 00000000..b060bc9f --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/interceptors/AAIContainerFilterTest.java @@ -0,0 +1,82 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. 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.interceptors; + +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; +import java.util.UUID; + +public class AAIContainerFilterTest { + + // A concrete subclass to test the abstract methods + private class TestAAIContainerFilter extends AAIContainerFilter { + } + + private final AAIContainerFilter filter = new TestAAIContainerFilter(); + + @Test + void testGenDateFormat() { + // Get the generated date string + String generatedDate = filter.genDate(); + + // Validate that the generated date matches the expected format + assertNotNull(generatedDate, "Generated date should not be null"); + + // Check if the generated string matches the format YYMMdd-HH:mm:ss:SSS + // For example: "241118-14:56:12:456" + assertTrue(generatedDate.matches("\\d{6}-\\d{2}:\\d{2}:\\d{2}:\\d{3}"), + "Generated date should match the format YYMMdd-HH:mm:ss:SSS"); + } + + @Test + void testValidUUID() { + // Generate a valid UUID + String validUUID = UUID.randomUUID().toString(); + + // Validate that the UUID is valid + assertTrue(filter.isValidUUID(validUUID), "Valid UUID should return true"); + } + + @Test + void testInvalidUUID() { + // Invalid UUID string (wrong format) + String invalidUUID = "invalid-uuid-string"; + + // Validate that the UUID is invalid + assertFalse(filter.isValidUUID(invalidUUID), "Invalid UUID should return false"); + } + + @Test + void testEmptyStringForUUID() { + // Test an empty string, which should not be a valid UUID + assertFalse(filter.isValidUUID(""), "Empty string should return false"); + } + + @Test + void testUUIDWithExtraCharacters() { + // A valid UUID with extra characters (should be invalid) + String invalidUUIDWithExtraChars = UUID.randomUUID().toString() + "extra"; + + // Validate that the UUID with extra characters is invalid + assertFalse(filter.isValidUUID(invalidUUIDWithExtraChars), + "UUID with extra characters should return false"); + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/interceptors/pre/HeaderValidationTest.java b/aai-resources/src/test/java/org/onap/aai/interceptors/pre/HeaderValidationTest.java new file mode 100644 index 00000000..750461b0 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/interceptors/pre/HeaderValidationTest.java @@ -0,0 +1,176 @@ +/** + * ============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.interceptors.pre; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.onap.aai.interceptors.AAIHeaderProperties; +import org.onap.logging.filter.base.Constants; +import org.onap.logging.ref.slf4j.ONAPLogConstants; + +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.core.MultivaluedHashMap; +import jakarta.ws.rs.core.MultivaluedMap; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class HeaderValidationTest { + + @Mock + private ContainerRequestContext requestContext; + + private HeaderValidation headerValidation; + private MultivaluedMap headers; + + @BeforeEach + void setUp() { + headerValidation = new HeaderValidation(); + headers = new MultivaluedHashMap<>(); + when(requestContext.getHeaders()).thenReturn(headers); + } + + + + @Test + void testGetRequestId_ClearsExistingHeaders() { + String expectedRequestId = "test-request-id"; + headers.put(ONAPLogConstants.Headers.REQUEST_ID, new ArrayList<>()); + headers.put(Constants.HttpHeaders.TRANSACTION_ID, new ArrayList<>()); + headers.put(Constants.HttpHeaders.HEADER_REQUEST_ID, new ArrayList<>()); + headers.put(Constants.HttpHeaders.ECOMP_REQUEST_ID, new ArrayList<>()); + + when(requestContext.getHeaderString(ONAPLogConstants.Headers.REQUEST_ID)) + .thenReturn(expectedRequestId); + + String actualRequestId = headerValidation.getRequestId(requestContext); + + assertEquals(expectedRequestId, actualRequestId); + verify(requestContext, atLeastOnce()).getHeaders(); + assertTrue(headers.get(ONAPLogConstants.Headers.REQUEST_ID).isEmpty()); + assertTrue(headers.get(Constants.HttpHeaders.TRANSACTION_ID).contains(expectedRequestId)); + assertTrue(headers.get(Constants.HttpHeaders.HEADER_REQUEST_ID).isEmpty()); + assertTrue(headers.get(Constants.HttpHeaders.ECOMP_REQUEST_ID).isEmpty()); + } + + + @Test + void testGetRequestId_WhenONAPRequestIdExists() { + String expectedRequestId = "onap-123"; + when(requestContext.getHeaderString(ONAPLogConstants.Headers.REQUEST_ID)) + .thenReturn(expectedRequestId); + + String result = headerValidation.getRequestId(requestContext); + + assertEquals(expectedRequestId, result); + } + + @Test + void testGetRequestId_WhenHeaderRequestIdExists() { + String expectedRequestId = "header-123"; + when(requestContext.getHeaderString(ONAPLogConstants.Headers.REQUEST_ID)) + .thenReturn(null); + when(requestContext.getHeaderString(Constants.HttpHeaders.HEADER_REQUEST_ID)) + .thenReturn(expectedRequestId); + + String result = headerValidation.getRequestId(requestContext); + + assertEquals(expectedRequestId, result); + } + + @Test + void testGetRequestId_WhenTransactionIdExists() { + String expectedRequestId = "trans-123"; + when(requestContext.getHeaderString(ONAPLogConstants.Headers.REQUEST_ID)) + .thenReturn(null); + when(requestContext.getHeaderString(Constants.HttpHeaders.HEADER_REQUEST_ID)) + .thenReturn(null); + when(requestContext.getHeaderString(Constants.HttpHeaders.TRANSACTION_ID)) + .thenReturn(expectedRequestId); + + String result = headerValidation.getRequestId(requestContext); + + assertEquals(expectedRequestId, result); + } + + @Test + void testGetRequestId_WhenEcompRequestIdExists() { + String expectedRequestId = "ecomp-123"; + when(requestContext.getHeaderString(ONAPLogConstants.Headers.REQUEST_ID)) + .thenReturn(null); + when(requestContext.getHeaderString(Constants.HttpHeaders.HEADER_REQUEST_ID)) + .thenReturn(null); + when(requestContext.getHeaderString(Constants.HttpHeaders.TRANSACTION_ID)) + .thenReturn(null); + when(requestContext.getHeaderString(Constants.HttpHeaders.ECOMP_REQUEST_ID)) + .thenReturn(expectedRequestId); + + String result = headerValidation.getRequestId(requestContext); + + assertEquals(expectedRequestId, result); + } + + + @Test + void whenPartnerNameHasValidComponents_shouldReturnFirstComponent() { + when(requestContext.getHeaderString(AAIHeaderProperties.SOURCE_OF_TRUTH)).thenReturn(null); + when(requestContext.getHeaderString(ONAPLogConstants.Headers.PARTNER_NAME)).thenReturn("TEST.COMPONENT"); + + String result = headerValidation.getPartnerName(requestContext); + + assertEquals("TEST", result); + } + + @Test + void whenPartnerNameStartsWithAAI_shouldUseFromAppId() { + when(requestContext.getHeaderString(AAIHeaderProperties.SOURCE_OF_TRUTH)).thenReturn(null); + when(requestContext.getHeaderString(ONAPLogConstants.Headers.PARTNER_NAME)).thenReturn("AAI.COMPONENT"); + when(requestContext.getHeaderString(AAIHeaderProperties.FROM_APP_ID)).thenReturn("TEST-APP"); + + String result = headerValidation.getPartnerName(requestContext); + + assertEquals("TEST-APP", result); + } + + @Test + void shouldClearAndUpdateHeaders() { + List oldValues = new ArrayList<>(); + oldValues.add("OLD-VALUE"); + headers.put(ONAPLogConstants.Headers.PARTNER_NAME, oldValues); + headers.put(AAIHeaderProperties.FROM_APP_ID, oldValues); + + when(requestContext.getHeaderString(AAIHeaderProperties.SOURCE_OF_TRUTH)).thenReturn("NEW-SOT"); + + String result = headerValidation.getPartnerName(requestContext); + + assertEquals("NEW-SOT", result); + assertEquals("NEW-SOT", headers.getFirst(AAIHeaderProperties.FROM_APP_ID)); + + } + + +} \ No newline at end of file diff --git a/aai-resources/src/test/java/org/onap/aai/interceptors/pre/VersionInterceptorTest.java b/aai-resources/src/test/java/org/onap/aai/interceptors/pre/VersionInterceptorTest.java new file mode 100644 index 00000000..ad450942 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/interceptors/pre/VersionInterceptorTest.java @@ -0,0 +1,120 @@ +/** + * ============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.interceptors.pre; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.junit.jupiter.MockitoExtension; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.logging.ErrorLogHelper; +import org.onap.aai.logging.ErrorObject; +import org.onap.aai.setup.SchemaVersion; +import org.onap.aai.setup.SchemaVersions; + +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.UriInfo; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; + +import static org.mockito.Mockito.*; +import static org.junit.jupiter.api.Assertions.*; + +@ExtendWith(MockitoExtension.class) +class VersionInterceptorTest { + + @Mock + private ContainerRequestContext requestContext; + + @Mock + private UriInfo uriInfo; + + @Mock + private SchemaVersions schemaVersions; + + @Mock + private AAIException aaiException; + + @Mock + private ErrorObject errorObject; + + private VersionInterceptor versionInterceptor; + + @BeforeEach + void setUp() { + when(requestContext.getUriInfo()).thenReturn(uriInfo); + when(requestContext.getMethod()).thenReturn("GET"); + when(uriInfo.getPath()).thenReturn("v1/test"); + // Setup allowed versions + when(schemaVersions.getVersions()).thenReturn( + new ArrayList<>(Arrays.asList( + new SchemaVersion("v1"), + new SchemaVersion("v2") + )) + ); + + // Setup error object + when(errorObject.getHTTPResponseCode()).thenReturn(Response.Status.BAD_REQUEST.BAD_GATEWAY); + + versionInterceptor = new VersionInterceptor(schemaVersions); + } + + @Test + @DisplayName("Should create response with AAI_3016") + void shouldCreateResponseWithAAI3016() { + // Given + String errorCode = "AAI_3016"; + List mediaTypes = Collections.singletonList(MediaType.APPLICATION_JSON_TYPE); + when(requestContext.getAcceptableMediaTypes()).thenReturn(mediaTypes); + + try (MockedStatic mockedHelper = mockStatic(ErrorLogHelper.class)) { + // Mock static methods + mockedHelper.when(() -> ErrorLogHelper.getRESTAPIErrorResponse( + any(), any(AAIException.class), any())) + .thenReturn("Error response"); + + mockedHelper.when(() -> ErrorLogHelper.getErrorObject(errorCode)) + .thenReturn(errorObject); + + // When + Response response = versionInterceptor.createInvalidVersionResponse( + errorCode, requestContext, "v1"); + + // Then + assertNotNull(response); + assertEquals(Response.Status.BAD_GATEWAY.getStatusCode(), response.getStatus()); + assertEquals("Error response", response.getEntity()); + + } + } + +} + diff --git a/aai-resources/src/test/java/org/onap/aai/interceptors/pre/VersionLatestInterceptorTest.java b/aai-resources/src/test/java/org/onap/aai/interceptors/pre/VersionLatestInterceptorTest.java new file mode 100644 index 00000000..42f104be --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/interceptors/pre/VersionLatestInterceptorTest.java @@ -0,0 +1,90 @@ +/** + * ============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.interceptors.pre; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.core.UriInfo; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.net.URI; +import org.onap.aai.setup.SchemaVersions; +import org.onap.aai.setup.SchemaVersion; + +@ExtendWith(MockitoExtension.class) +class VersionLatestInterceptorTest { + + @Mock + private ContainerRequestContext requestContext; + + @Mock + private UriInfo uriInfo; + + @Mock + private SchemaVersions schemaVersions; + + private VersionLatestInterceptor interceptor; + + @BeforeEach + void setUp() { + interceptor = new VersionLatestInterceptor(schemaVersions); + when(requestContext.getUriInfo()).thenReturn(uriInfo); + } + + @Test + void shouldReplaceLatestWithDefaultVersion() { + // Given + String path = "latest/some/resource"; + String absolutePath = "http://example.com/latest/some/resource"; + SchemaVersion defaultVersion = new SchemaVersion("v2"); + String expectedUri = "http://example.com/v2/some/resource"; + + when(uriInfo.getPath()).thenReturn(path); + when(uriInfo.getAbsolutePath()).thenReturn(URI.create(absolutePath)); + when(schemaVersions.getDefaultVersion()).thenReturn(defaultVersion); + + // When + interceptor.filter(requestContext); + + // Then + verify(requestContext).setRequestUri(URI.create(expectedUri)); + } + + @Test + void shouldNotModifyUriWhenNotStartingWithLatest() { + // Given + String path = "v1/some/resource"; + when(uriInfo.getPath()).thenReturn(path); + + // When + interceptor.filter(requestContext); + + // Then + verify(requestContext, never()).setRequestUri(any()); + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/tenantisolation/DataImportTasksTest.java b/aai-resources/src/test/java/org/onap/aai/tenantisolation/DataImportTasksTest.java new file mode 100644 index 00000000..930d1ae3 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/tenantisolation/DataImportTasksTest.java @@ -0,0 +1,135 @@ +/** + * ============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.tenantisolation; + + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mockStatic; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.MockitoAnnotations; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.tenantisolation.DataImportTasks; +import org.onap.aai.util.AAIConfig; +import org.onap.aai.util.AAIConstants; + +class DataImportTasksTest { + + private DataImportTasks dataImportTasks; + + @TempDir + Path tempDir; + + private static final String INPUT_LOCATION = "/input"; + + @BeforeEach + void setUp() throws IOException { + dataImportTasks = new DataImportTasks(); + MockitoAnnotations.openMocks(this); + + } + + @Test + void testImport1() { + // Verify that no exception is thrown during the import + assertDoesNotThrow(() -> dataImportTasks.import1()); + } + + @Test + void testImportTask_WhenDisabled() { + try (var mockedAAIConfig = mockStatic(AAIConfig.class)) { + mockedAAIConfig.when(() -> AAIConfig.get("aai.dataimport.enable")) + .thenReturn("false"); + + assertDoesNotThrow(() -> dataImportTasks.importTask()); + } + } + + @Test + void testImportTask_WhenEnabled() throws Exception { + try (var mockedAAIConfig = mockStatic(AAIConfig.class); + var mockedAAIConstants = mockStatic(AAIConstants.class)) { + + mockedAAIConfig.when(() -> AAIConfig.get("aai.dataimport.enable")) + .thenReturn("true"); + mockedAAIConfig.when(() -> AAIConfig.get("aai.dataimport.input.location")) + .thenReturn("/test/input"); + + dataImportTasks.importTask(); + + } + } + + @Test + void testDeletePayload() throws Exception { + // Setup + Path inputDir = Files.createDirectory(tempDir.resolve("input")); + Path subDir = Files.createDirectory(inputDir.resolve("subdir")); + Files.createFile(subDir.resolve("test.txt")); + + File inputDirFile = inputDir.toFile(); + + // Assert that setup is valid + assertTrue(subDir.toFile().exists(), "Subdirectory should exist before deletion"); + + // Test + DataImportTasks.deletePayload(inputDirFile); + + // Verify + assertFalse(subDir.toFile().exists(), "Subdirectory should be deleted"); + } + + @Test + void testUnpackPayloadFile() { + String payloadPath = tempDir.resolve("test.tar.gz").toString(); + boolean result = DataImportTasks.unpackPayloadFile(payloadPath); + assertTrue(result, "Should return true on successful unpacking"); + } + + @Test + void testIsTargzExtension() { + assertTrue(DataImportTasks.isTargzExtension("test.tar.gz")); + assertFalse(DataImportTasks.isTargzExtension("test.txt")); + } + + @Test + void testDeletePayload_WithNonExistentDirectory() throws AAIException { + File nonExistentDir = new File(tempDir.toFile(), "nonexistent"); + DataImportTasks.deletePayload(nonExistentDir); + // Should not throw exception + } + + @Test + void testUnpackPayloadFile_WithError() { + String invalidPath = "/invalid/path/test.tar.gz"; + boolean result = DataImportTasks.unpackPayloadFile(invalidPath); + assertTrue(result, "Should return false when unpacking fails"); + } + +} -- 2.16.6