From 1e13cc1f9e41a782b0ba6e52d1e187b7b8bd1e9b Mon Sep 17 00:00:00 2001 From: "akshay.khairnar@t-systems.com" Date: Mon, 11 Aug 2025 09:39:28 +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: I5048b826c112914e7752d0343ace456b39af1eb0 Signed-off-by: akshay.khairnar@t-systems.com --- .../src/main/java/org/onap/aai/ResourcesApp.java | 352 ++++++++++----------- .../test/java/org/onap/aai/ResourcesAppTest.java | 198 ++++++++++++ .../org/onap/aai/rest/util/LogFormatToolsTest.java | 124 ++++++-- .../org/onap/aai/util/PositiveNumValidator.java | 61 ++++ 4 files changed, 524 insertions(+), 211 deletions(-) create mode 100644 aai-resources/src/test/java/org/onap/aai/ResourcesAppTest.java create mode 100644 aai-resources/src/test/java/org/onap/aai/util/PositiveNumValidator.java diff --git a/aai-resources/src/main/java/org/onap/aai/ResourcesApp.java b/aai-resources/src/main/java/org/onap/aai/ResourcesApp.java index 44dc48b2..3f092485 100644 --- a/aai-resources/src/main/java/org/onap/aai/ResourcesApp.java +++ b/aai-resources/src/main/java/org/onap/aai/ResourcesApp.java @@ -1,176 +1,176 @@ -/* - * ============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; - -import jakarta.annotation.PostConstruct; -import jakarta.annotation.PreDestroy; - -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.onap.aai.aailog.logs.AaiDebugLog; -import org.onap.aai.config.SpringContextAware; -import org.onap.aai.dbmap.AAIGraph; -import org.onap.aai.exceptions.AAIException; -import org.onap.aai.logging.ErrorLogHelper; -import org.onap.aai.nodes.NodeIngestor; -import org.onap.aai.util.AAIConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration; -import org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration; -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; -import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration; -import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.core.env.Environment; -import org.springframework.core.env.Profiles; - -@EnableConfigurationProperties -@SpringBootApplication( - exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, - HibernateJpaAutoConfiguration.class, CassandraDataAutoConfiguration.class, CassandraAutoConfiguration.class}) -public class ResourcesApp { - - private static final Logger logger = LoggerFactory.getLogger(ResourcesApp.class.getName()); - - private static final String APP_NAME = "aai-resources"; - private static AaiDebugLog debugLog = new AaiDebugLog(); - static { - debugLog.setupMDC(); - } - - @Autowired - private Environment env; - - @Autowired - private NodeIngestor nodeIngestor; - - @Autowired - private SpringContextAware context; - - @Autowired - private SpringContextAware loaderFactory; - - @PostConstruct - private void init() throws AAIException { - System.setProperty("org.onap.aai.serverStarted", "false"); - setDefaultProps(); - logger.info("AAI Server initialization started..."); - - // Setting this property to allow for encoded slash (/) in the path parameter - // This is only needed for tomcat keeping this as temporary - System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true"); - - logger.info("Starting AAIGraph connections and the NodeInjestor"); - - // if (env.acceptsProfiles(Profiles.TWO_WAY_SSL) && env.acceptsProfiles(Profiles.ONE_WAY_SSL)) { - if (env.acceptsProfiles(Profiles.of(ResourcesProfiles.TWO_WAY_SSL, ResourcesProfiles.ONE_WAY_SSL))) { - logger.warn("You have seriously misconfigured your application"); - } - - } - - @PreDestroy - public void cleanup() { - logger.info("Shutting down both realtime and cached connections"); - AAIGraph.getInstance().graphShutdown(); - } - - public static void main(String[] args) throws AAIException { - - setDefaultProps(); - - Environment env = null; - AAIConfig.init(); - try { - SpringApplication app = new SpringApplication(ResourcesApp.class); - app.setLogStartupInfo(false); - app.setRegisterShutdownHook(true); - env = app.run(args).getEnvironment(); - } catch (Exception ex) { - AAIException aai = null; - if (ex.getCause() instanceof AAIException) { - aai = (AAIException) ex.getCause(); - } else { - aai = schemaServiceExceptionTranslator(ex); - } - logger.error("Problems starting the ResourcesApp due to {}", aai.getMessage()); - ErrorLogHelper.logException(aai); - throw aai; - } - - logger.info("Application '{}' is running on {}!", env.getProperty("spring.application.name"), - env.getProperty("server.port")); - - // The main reason this was moved from the constructor is due - // to the SchemaGenerator needs the bean and during the constructor - // the Spring Context is not yet initialized - - AAIConfig.init(); - AAIGraph.getInstance(); - - logger.info("Resources MicroService Started"); - logger.debug("Resources MicroService Started"); - - } - - public static void setDefaultProps() { - - if (System.getProperty("file.separator") == null) { - System.setProperty("file.separator", "/"); - } - - String currentDirectory = System.getProperty("user.dir"); - System.setProperty("aai.service.name", ResourcesApp.class.getSimpleName()); - - if (System.getProperty("AJSC_HOME") == null) { - System.setProperty("AJSC_HOME", "."); - } - - if (currentDirectory.contains(APP_NAME)) { - if (System.getProperty("BUNDLECONFIG_DIR") == null) { - System.setProperty("BUNDLECONFIG_DIR", "src/main/resources"); - } - } else { - if (System.getProperty("BUNDLECONFIG_DIR") == null) { - System.setProperty("BUNDLECONFIG_DIR", "aai-resources/src/main/resources"); - } - } - } - - public static AAIException schemaServiceExceptionTranslator(Exception ex) { - AAIException aai = null; - String message = ExceptionUtils.getRootCause(ex).getMessage(); - if (message.contains("NodeIngestor")) { - aai = new AAIException("AAI_3026", "Error reading OXM from SchemaService - Investigate"); - } else if (message.contains("EdgeIngestor")) { - aai = new AAIException("AAI_3027", "Error reading EdgeRules from SchemaService - Investigate"); - } else if (message.contains("Connection refused")) { - aai = new AAIException("AAI_3025", "Error connecting to SchemaService - Investigate"); - } else { - aai = new AAIException("AAI_3025", "Unable to determine what the error is, please check external.log"); - } - - return aai; - } -} +/* + * ============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; + +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; + +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.onap.aai.aailog.logs.AaiDebugLog; +import org.onap.aai.config.SpringContextAware; +import org.onap.aai.dbmap.AAIGraph; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.logging.ErrorLogHelper; +import org.onap.aai.nodes.NodeIngestor; +import org.onap.aai.util.AAIConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration; +import org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration; +import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.core.env.Environment; +import org.springframework.core.env.Profiles; + +@EnableConfigurationProperties +@SpringBootApplication( + exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, + HibernateJpaAutoConfiguration.class, CassandraDataAutoConfiguration.class, CassandraAutoConfiguration.class}) +public class ResourcesApp { + + private static final Logger logger = LoggerFactory.getLogger(ResourcesApp.class.getName()); + + private static final String APP_NAME = "aai-resources"; + private static AaiDebugLog debugLog = new AaiDebugLog(); + static { + debugLog.setupMDC(); + } + + @Autowired + private Environment env; + + @Autowired + private NodeIngestor nodeIngestor; + + @Autowired + private SpringContextAware context; + + @Autowired + private SpringContextAware loaderFactory; + + @PostConstruct + void init() throws AAIException { + System.setProperty("org.onap.aai.serverStarted", "false"); + setDefaultProps(); + logger.info("AAI Server initialization started..."); + + // Setting this property to allow for encoded slash (/) in the path parameter + // This is only needed for tomcat keeping this as temporary + System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true"); + + logger.info("Starting AAIGraph connections and the NodeInjestor"); + + // if (env.acceptsProfiles(Profiles.TWO_WAY_SSL) && env.acceptsProfiles(Profiles.ONE_WAY_SSL)) { + if (env.acceptsProfiles(Profiles.of(ResourcesProfiles.TWO_WAY_SSL, ResourcesProfiles.ONE_WAY_SSL))) { + logger.warn("You have seriously misconfigured your application"); + } + + } + + @PreDestroy + public void cleanup() { + logger.info("Shutting down both realtime and cached connections"); + AAIGraph.getInstance().graphShutdown(); + } + + public static void main(String[] args) throws AAIException { + + setDefaultProps(); + + Environment env = null; + AAIConfig.init(); + try { + SpringApplication app = new SpringApplication(ResourcesApp.class); + app.setLogStartupInfo(false); + app.setRegisterShutdownHook(true); + env = app.run(args).getEnvironment(); + } catch (Exception ex) { + AAIException aai = null; + if (ex.getCause() instanceof AAIException) { + aai = (AAIException) ex.getCause(); + } else { + aai = schemaServiceExceptionTranslator(ex); + } + logger.error("Problems starting the ResourcesApp due to {}", aai.getMessage()); + ErrorLogHelper.logException(aai); + throw aai; + } + + logger.info("Application '{}' is running on {}!", env.getProperty("spring.application.name"), + env.getProperty("server.port")); + + // The main reason this was moved from the constructor is due + // to the SchemaGenerator needs the bean and during the constructor + // the Spring Context is not yet initialized + + AAIConfig.init(); + AAIGraph.getInstance(); + + logger.info("Resources MicroService Started"); + logger.debug("Resources MicroService Started"); + + } + + public static void setDefaultProps() { + + if (System.getProperty("file.separator") == null) { + System.setProperty("file.separator", "/"); + } + + String currentDirectory = System.getProperty("user.dir"); + System.setProperty("aai.service.name", ResourcesApp.class.getSimpleName()); + + if (System.getProperty("AJSC_HOME") == null) { + System.setProperty("AJSC_HOME", "."); + } + + if (currentDirectory.contains(APP_NAME)) { + if (System.getProperty("BUNDLECONFIG_DIR") == null) { + System.setProperty("BUNDLECONFIG_DIR", "src/main/resources"); + } + } else { + if (System.getProperty("BUNDLECONFIG_DIR") == null) { + System.setProperty("BUNDLECONFIG_DIR", "aai-resources/src/main/resources"); + } + } + } + + public static AAIException schemaServiceExceptionTranslator(Exception ex) { + AAIException aai = null; + String message = ExceptionUtils.getRootCause(ex).getMessage(); + if (message.contains("NodeIngestor")) { + aai = new AAIException("AAI_3026", "Error reading OXM from SchemaService - Investigate"); + } else if (message.contains("EdgeIngestor")) { + aai = new AAIException("AAI_3027", "Error reading EdgeRules from SchemaService - Investigate"); + } else if (message.contains("Connection refused")) { + aai = new AAIException("AAI_3025", "Error connecting to SchemaService - Investigate"); + } else { + aai = new AAIException("AAI_3025", "Unable to determine what the error is, please check external.log"); + } + + return aai; + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/ResourcesAppTest.java b/aai-resources/src/test/java/org/onap/aai/ResourcesAppTest.java new file mode 100644 index 00000000..38bf8e58 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/ResourcesAppTest.java @@ -0,0 +1,198 @@ +/** + * ============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 static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +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.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.junit.jupiter.MockitoExtension; +import org.onap.aai.config.SpringContextAware; +import org.onap.aai.dbmap.AAIGraph; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.nodes.NodeIngestor; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.Environment; +import org.springframework.core.env.Profiles; + +@ExtendWith(MockitoExtension.class) +class ResourcesAppTest { + + private ResourcesApp resourcesApp; + + @Mock + private Environment environment; + + @Mock + private NodeIngestor nodeIngestor; + + @Mock + private SpringContextAware context; + + @Mock + private SpringContextAware loaderFactory; + + @InjectMocks + private ResourcesApp resourceApp; + + @MockBean + private ConfigurableApplicationContext applicationContext; + + + @Mock + private Environment env; + + @BeforeEach + void setUp() { + resourcesApp = new ResourcesApp(); + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "src/main/resources"); + } + + @Test + void testSetDefaultProps() { + // Clear any existing system properties + System.clearProperty("file.separator"); + System.clearProperty("AJSC_HOME"); + System.clearProperty("BUNDLECONFIG_DIR"); + + ResourcesApp.setDefaultProps(); + + assertEquals("/", System.getProperty("file.separator")); + assertEquals(".", System.getProperty("AJSC_HOME")); + assertNotNull(System.getProperty("BUNDLECONFIG_DIR")); + assertEquals("ResourcesApp", System.getProperty("aai.service.name")); + } + + @Test + void init_ShouldSetupPropertiesAndConfiguration() throws AAIException { + when(env.acceptsProfiles(any(Profiles.class))).thenReturn(false); + + resourceApp.init(); + + assertAll( + () -> assertEquals("false", System.getProperty("org.onap.aai.serverStarted")), + () -> assertEquals("true", System.getProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH")) + ); + } + + @Test + void testBundleConfigDirWithAppName() { + System.clearProperty("BUNDLECONFIG_DIR"); + String originalUserDir = System.getProperty("user.dir"); + + System.setProperty("user.dir", originalUserDir + "/aai-resources"); + ResourcesApp.setDefaultProps(); + assertEquals("src/main/resources", System.getProperty("BUNDLECONFIG_DIR")); + + System.setProperty("user.dir", originalUserDir); + } + + @Test + void testBundleConfigDirWithoutAppName() { + // Clear and set specific properties for this test + System.clearProperty("BUNDLECONFIG_DIR"); + String originalUserDir = System.getProperty("user.dir"); + + System.setProperty("user.dir", "/different/path"); + ResourcesApp.setDefaultProps(); + assertEquals("aai-resources/src/main/resources", System.getProperty("BUNDLECONFIG_DIR")); + + System.setProperty("user.dir", originalUserDir); + } + + @Test + void testCleanup() { + try (MockedStatic aaiGraphMock = mockStatic(AAIGraph.class)) { + AAIGraph mockGraph = mock(AAIGraph.class); + aaiGraphMock.when(AAIGraph::getInstance).thenReturn(mockGraph); + + resourcesApp.cleanup(); + verify(mockGraph).graphShutdown(); + } + } + + @Test + @DisplayName("Should return AAI_3026 exception when NodeIngestor error occurs") + void testNodeIngestorError() { + Exception cause = new RuntimeException("Failed to process NodeIngestor data"); + Exception originalException = new Exception("Wrapper", cause); + + AAIException result = ResourcesApp.schemaServiceExceptionTranslator(originalException); + + assertNotNull(result); + assertEquals("AAI_3026", result.getCode()); + } + + @Test + @DisplayName("Should return AAI_3027 exception when EdgeIngestor error occurs") + void testEdgeIngestorError() { + Exception cause = new RuntimeException("EdgeIngestor failed to process"); + Exception originalException = new Exception("Wrapper", cause); + + AAIException result = ResourcesApp.schemaServiceExceptionTranslator(originalException); + + assertNotNull(result); + assertEquals("AAI_3027", result.getCode()); + } + + @Test + @DisplayName("Should return AAI_3025 exception when connection refused") + void testConnectionRefusedError() { + Exception cause = new RuntimeException("Connection refused"); + Exception originalException = new Exception("Wrapper", cause); + + AAIException result = ResourcesApp.schemaServiceExceptionTranslator(originalException); + + assertNotNull(result); + assertEquals("AAI_3025", result.getCode()); + } + + @Test + @DisplayName("Should return default AAI_3025 exception for unknown errors") + void testUnknownError() { + Exception cause = new RuntimeException("Some unexpected error"); + Exception originalException = new Exception("Wrapper", cause); + + AAIException result = ResourcesApp.schemaServiceExceptionTranslator(originalException); + + assertNotNull(result); + assertEquals("AAI_3025", result.getCode()); + } +} + + + + + + diff --git a/aai-resources/src/test/java/org/onap/aai/rest/util/LogFormatToolsTest.java b/aai-resources/src/test/java/org/onap/aai/rest/util/LogFormatToolsTest.java index 3958f46e..6f1a05fa 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/util/LogFormatToolsTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/util/LogFormatToolsTest.java @@ -1,35 +1,89 @@ -/** - * ============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.rest.util; - -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import org.junit.jupiter.api.Test; - -public class LogFormatToolsTest { - - @Test - public void testLogFormatTools() { - - String dateTime = LogFormatTools.getCurrentDateTime(); - assertNotNull(dateTime); - } -} +/** + * ============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.rest.util; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; + +import org.junit.jupiter.api.Test; + +public class LogFormatToolsTest { + + private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; + private static final DateTimeFormatter DTF = DateTimeFormatter.ofPattern(DATE_FORMAT).withZone(ZoneOffset.UTC); + + @Test + void getCurrentDateTime_ShouldReturnCorrectFormat() { + String result = LogFormatTools.getCurrentDateTime(); + + assertTrue(isValidDateFormat(result), "DateTime string should match the expected format"); + } + + @Test + void getCurrentDateTime_ShouldReturnCurrentTime() { + ZonedDateTime beforeTest = ZonedDateTime.now(); + + String result = LogFormatTools.getCurrentDateTime(); + ZonedDateTime parsedResult = ZonedDateTime.parse(result, DTF); + ZonedDateTime afterTest = ZonedDateTime.now(); + + assertTrue(parsedResult.isBefore(afterTest) || parsedResult.equals(afterTest), + "Returned datetime should not be after test end"); + } + + @Test + void getCurrentDateTime_ShouldReturnUTCTime() { + String result = LogFormatTools.getCurrentDateTime(); + ZonedDateTime parsedResult = ZonedDateTime.parse(result, DTF); + + assertEquals(ZoneOffset.UTC, parsedResult.getOffset(), + "DateTime should be in UTC timezone"); + } + + private boolean isValidDateFormat(String dateStr) { + ZonedDateTime.parse(dateStr, DTF); + return true; + } + + @Test + void testLogFormatToolsInstantiation() { + LogFormatTools logFormatTools = new LogFormatTools(); + + assertNotNull(logFormatTools, "Should be able to create LogFormatTools instance"); + assertTrue(logFormatTools instanceof LogFormatTools, + "Created object should be instance of LogFormatTools"); + } + + @Test + void testLogFormatToolsClass() { + Class clazz = LogFormatTools.class; + + assertFalse(clazz.isInterface(), "LogFormatTools should be a class, not an interface"); + assertFalse(clazz.isEnum(), "LogFormatTools should be a class, not an enum"); + assertFalse(clazz.isAnnotation(), "LogFormatTools should be a class, not an annotation"); + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/util/PositiveNumValidator.java b/aai-resources/src/test/java/org/onap/aai/util/PositiveNumValidator.java new file mode 100644 index 00000000..8e616931 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/util/PositiveNumValidator.java @@ -0,0 +1,61 @@ +/** + * ============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.Test; + +import com.beust.jcommander.ParameterException; + +import org.junit.jupiter.api.DisplayName; +import static org.junit.jupiter.api.Assertions.*; + +class PositiveNumValidatorTest { + + private final PositiveNumValidator validator = new PositiveNumValidator(); + + @Test + @DisplayName("Should accept zero as valid input") + void validateZero() { + assertDoesNotThrow(() -> validator.validate("testParam", "0")); + } + + @Test + @DisplayName("Should accept positive number as valid input") + void validatePositiveNumber() { + assertDoesNotThrow(() -> validator.validate("testParam", "42")); + } + + @Test + @DisplayName("Should throw ParameterException for negative number") + void validateNegativeNumber() { + ParameterException exception = assertThrows(ParameterException.class, + () -> validator.validate("testParam", "-1")); + + assertEquals("Parameter testParam should be >= 0", exception.getMessage()); + } + + @Test + @DisplayName("Should throw NumberFormatException for non-numeric input") + void validateNonNumericInput() { + assertThrows(NumberFormatException.class, + () -> validator.validate("testParam", "abc")); + } +} + -- 2.16.6