diff options
27 files changed, 791 insertions, 238 deletions
diff --git a/auth/cli-codegen/src/test/java/org/onap/policy/apex/auth/clicodegen/CodeGeneratorCliEditorTest.java b/auth/cli-codegen/src/test/java/org/onap/policy/apex/auth/clicodegen/CodeGeneratorCliEditorTest.java index 1b44f66e7..54e50b5ab 100644 --- a/auth/cli-codegen/src/test/java/org/onap/policy/apex/auth/clicodegen/CodeGeneratorCliEditorTest.java +++ b/auth/cli-codegen/src/test/java/org/onap/policy/apex/auth/clicodegen/CodeGeneratorCliEditorTest.java @@ -25,6 +25,7 @@ package org.onap.policy.apex.auth.clicodegen; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.File; import java.io.FileInputStream; @@ -81,6 +82,20 @@ class CodeGeneratorCliEditorTest { assertEquals(0, generateCli(codeGen, apexPolicyModel)); } + @Test + void testTaskDefFields() { + CodeGeneratorCliEditor editor = new CodeGeneratorCliEditor(); + var st = editor.createTaskDefinitionInfields("InFieldTask", "1.0.0", "field1", "schema", "1.0.1"); + assertNotNull(st); + + var st2 = editor.createTaskDefinitionOutfields("OutFieldTask", "1.0.0", "field2", "schema", "1.0.1"); + assertNotNull(st2); + + var st3 = editor.createPolicyStateDefFinalizerLogic("dummy", "1.0.0", "dummyState", + "logicName", "flavor", "logic"); + assertNotNull(st3); + } + /** * Generate the CLI from the model. * diff --git a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/CommandLineCommandTest.java b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/CommandLineCommandTest.java index 5028abd31..ad606153a 100644 --- a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/CommandLineCommandTest.java +++ b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/CommandLineCommandTest.java @@ -24,10 +24,14 @@ package org.onap.policy.apex.auth.clieditor; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; +import java.util.Properties; +import java.util.SortedMap; +import java.util.TreeMap; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -136,4 +140,38 @@ class CommandLineCommandTest { otherCommand.getKeywordlist().add("TestKeyword"); assertNotEquals(commandLineCommand, otherCommand); } + + @Test + void testExecuteInvalidCommand() { + var handler = new ApexModelHandler(new Properties()); + var command = new CommandLineCommand(); + command.setApiMethod("java.invalid"); // invalid class + assertThrows(CommandLineException.class, () -> handler.executeCommand(command, null, null)); + + command.setApiMethod("org.onap.policy.apex.model.modelapi.ApexModel.invalid"); //invalid method + assertThrows(CommandLineException.class, () -> handler.executeCommand(command, null, null)); + + command.setApiMethod("org.onap.policy.apex.model.modelapi.ApexModel.saveToFile"); + SortedMap<String, CommandLineArgumentValue> map = new TreeMap<>(); + map.put("key", new CommandLineArgumentValue(null)); + assertThrows(CommandLineException.class, () -> handler.executeCommand(command, map, null)); + } + + @Test + void testCommandLineArgument() { + var argument = new CommandLineArgument(); + assertThat(argument).isEqualByComparingTo(argument); + var otherArgument = new CommandLineArgument("otherArgument"); + assertThat(argument).isLessThan(otherArgument); + + } + + @Test + void testKeyWordNodeCommands() { + var kn = new KeywordNode("test"); + var cmd = new CommandLineCommand(); + List<String> keywordList = List.of("key1", "key2"); + kn.processKeywords(keywordList, cmd); + assertNotNull(kn.getCommands()); + } } diff --git a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/CommandLineEditorOptionsTest.java b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/CommandLineEditorOptionsTest.java index dfdb4c2a3..eb31d15fb 100644 --- a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/CommandLineEditorOptionsTest.java +++ b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/CommandLineEditorOptionsTest.java @@ -257,8 +257,8 @@ class CommandLineEditorOptionsTest { assertEquals(3336, tempModelFileOutCharCount); assertTrue(tempLogFileIn.delete()); - assertTrue(tempModelFileIn.delete()); assertTrue(tempLogFileOut.delete()); assertTrue(tempModelFileOut.delete()); + tempModelFileIn.delete(); } } diff --git a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/CommandLineEditorScriptingTest.java b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/CommandLineEditorScriptingTest.java index 395f4c6bf..2e98fcf45 100644 --- a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/CommandLineEditorScriptingTest.java +++ b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/CommandLineEditorScriptingTest.java @@ -72,8 +72,8 @@ class CommandLineEditorScriptingTest { */ @AfterEach public void removeGeneratedFiles() { - assertTrue(tempModelFile.delete()); assertTrue(tempLogFile.delete()); + tempModelFile.delete(); } /** diff --git a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/CommandLineParametersTest.java b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/CommandLineParametersTest.java new file mode 100644 index 000000000..b979d73df --- /dev/null +++ b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/CommandLineParametersTest.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2024 Nordix Foundation. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.auth.clieditor; + +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.io.IOException; +import org.junit.jupiter.api.Test; + + +class CommandLineParametersTest { + + @Test + void testMetadataFile() { + var clParameters = new CommandLineParameters(); + assertNotNull(clParameters.getMetadataLocation()); + assertFalse(clParameters.checkSetMetadataFileName()); + clParameters.setMetadataFileName("testFile"); + assertEquals("file: \"testFile\"", clParameters.getMetadataLocation()); + assertTrue(clParameters.checkSetMetadataFileName()); + } + + @Test + void testApexPropertiesFile() throws IOException { + var clParameters = new CommandLineParameters(); + assertNotNull(clParameters.getApexPropertiesLocation()); + assertNotNull(clParameters.getApexPropertiesStream()); + assertFalse(clParameters.checkSetApexPropertiesFileName()); + clParameters.setApexPropertiesFileName("testApexPropertiesFile"); + assertTrue(clParameters.checkSetApexPropertiesFileName()); + } + + @Test + void testInputModelFile() { + var clParameters = new CommandLineParameters(); + assertFalse(clParameters.checkSetInputModelFileName()); + assertFalse(clParameters.checkSetLogFileName()); + clParameters.validate(); + } +} diff --git a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/ContextAlbumsTest.java b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/ContextAlbumsTest.java index 6984b6701..e9ac89ae0 100644 --- a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/ContextAlbumsTest.java +++ b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/ContextAlbumsTest.java @@ -23,7 +23,6 @@ package org.onap.policy.apex.auth.clieditor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.IOException; @@ -62,7 +61,7 @@ class ContextAlbumsTest { */ @AfterEach void removeGeneratedModels() { - assertTrue(tempModelFile.delete()); + tempModelFile.delete(); } /** diff --git a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/FileMacroTest.java b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/FileMacroTest.java index 443727236..aecc3a066 100644 --- a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/FileMacroTest.java +++ b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/FileMacroTest.java @@ -22,7 +22,6 @@ package org.onap.policy.apex.auth.clieditor; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.IOException; @@ -67,7 +66,7 @@ class FileMacroTest { */ @AfterEach void removeGeneratedModels() { - assertTrue(tempModelFile.delete()); + tempModelFile.delete(); } /** @@ -97,7 +96,7 @@ class FileMacroTest { writtenModel.getKeyInformation().getKeyInfoMap().clear(); compareModel.getKeyInformation().getKeyInfoMap().clear(); - assertEquals(writtenModel, compareModel); + assertEquals(normalizeNewlines(writtenModel.toString()), normalizeNewlines(compareModel.toString())); // The output event is in this file final File outputLogFile = new File(tempLogFile.getCanonicalPath()); @@ -114,4 +113,8 @@ class FileMacroTest { // Check what we got is what we expected to get assertEquals(outputLogCompareString, outputLogString); } + + private String normalizeNewlines(String input) { + return input.replace("\r\n", "\n"); + } } diff --git a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/LogicBlockTest.java b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/LogicBlockTest.java index 982d5195e..111215b26 100644 --- a/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/LogicBlockTest.java +++ b/auth/cli-editor/src/test/java/org/onap/policy/apex/auth/clieditor/LogicBlockTest.java @@ -22,7 +22,6 @@ package org.onap.policy.apex.auth.clieditor; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.IOException; @@ -67,8 +66,8 @@ class LogicBlockTest { */ @AfterEach void removeTempFiles() { - assertTrue(tempLogicModelFile.delete()); - assertTrue(tempAvroModelFile.delete()); + tempLogicModelFile.delete(); + tempAvroModelFile.delete(); } /** diff --git a/context/context-management/src/test/java/org/onap/policy/apex/context/impl/ContextAlbumImplTest.java b/context/context-management/src/test/java/org/onap/policy/apex/context/impl/ContextAlbumImplTest.java index 216e3686a..5b1f3ee7f 100644 --- a/context/context-management/src/test/java/org/onap/policy/apex/context/impl/ContextAlbumImplTest.java +++ b/context/context-management/src/test/java/org/onap/policy/apex/context/impl/ContextAlbumImplTest.java @@ -21,6 +21,7 @@ package org.onap.policy.apex.context.impl; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -40,6 +41,8 @@ import org.onap.policy.apex.context.impl.distribution.jvmlocal.JvmLocalDistribut import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; import org.onap.policy.apex.context.parameters.ContextParameterConstants; import org.onap.policy.apex.context.parameters.ContextParameters; +import org.onap.policy.apex.context.parameters.DistributorParameters; +import org.onap.policy.apex.context.parameters.PersistorParameters; import org.onap.policy.apex.context.parameters.SchemaParameters; import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; import org.onap.policy.apex.model.basicmodel.concepts.AxConcept; @@ -65,6 +68,7 @@ class ContextAlbumImplTest { contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); + contextParameters.getPersistorParameters().setFlushPeriod(30000); ParameterService.register(contextParameters); ParameterService.register(contextParameters.getDistributorParameters()); @@ -295,11 +299,53 @@ class ContextAlbumImplTest { assertThatThrownBy(album::flush).hasMessage("map flush failed, supplied map is null"); AxContextAlbums albums = new AxContextAlbums(); ModelService.registerModel(AxContextAlbums.class, albums); + + assertThatThrownBy(() -> { + distributor.createContextAlbum(new AxContextAlbums().getKey()); + }).hasMessage("context album NULL:0.0.0 does not exist"); + albums.getAlbumsMap().put(axContextAlbum.getKey(), axContextAlbum); distributor.createContextAlbum(album.getKey()); + axContextAlbum.setItemSchema(new AxArtifactKey()); + albums.getAlbumsMap().put(axContextAlbum.getKey(), axContextAlbum); + assertThatThrownBy(() -> { + distributor.createContextAlbum(album.getKey()); + }).hasMessageContaining("context album definition for TestContextAlbum:0.0.1 is invalid"); + + axContextAlbum.setItemSchema(new AxArtifactKey("invalid", "0.0.1")); + albums.getAlbumsMap().put(axContextAlbum.getKey(), axContextAlbum); + assertThatThrownBy(() -> { + distributor.createContextAlbum(album.getKey()); + }).hasMessage("schema \"invalid:0.0.1\" for context album TestContextAlbum:0.0.1 does not exist"); + album.flush(); ModelService.clear(); } + + @Test + void testParametersToString() { + assertThat(ParameterService.get(ContextParameterConstants.MAIN_GROUP_NAME).toString()) + .isInstanceOf(String.class); + assertThat(ParameterService.get(ContextParameterConstants.SCHEMA_GROUP_NAME).toString()) + .isInstanceOf(String.class); + } + + @Test + void testParameterSetter() { + var parameters = new PersistorParameters(); + parameters.setFlushPeriod(0); + parameters.setPluginClass("TestPlugin.class"); + assertEquals(300000, parameters.getFlushPeriod()); + + var distributorParameters = new DistributorParameters(); + distributorParameters.setName("test"); + distributorParameters.setPluginClass("TestPlugin.class"); + assertEquals("test", distributorParameters.getName()); + + var contextParameters = new ContextParameters(); + contextParameters.setDistributorParameters(distributorParameters); + assertEquals("test", contextParameters.getDistributorParameters().getName()); + } } diff --git a/context/context-management/src/test/java/org/onap/policy/apex/context/impl/LockManagerTest.java b/context/context-management/src/test/java/org/onap/policy/apex/context/impl/LockManagerTest.java new file mode 100644 index 000000000..2aac635a1 --- /dev/null +++ b/context/context-management/src/test/java/org/onap/policy/apex/context/impl/LockManagerTest.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2024 Nordix Foundation. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.context.impl; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; +import org.onap.policy.apex.context.ContextException; +import org.onap.policy.apex.context.impl.distribution.jvmlocal.JvmLocalDistributor; +import org.onap.policy.apex.context.impl.locking.LockManagerFactory; +import org.onap.policy.apex.context.impl.locking.jvmlocal.JvmLocalLockManager; +import org.onap.policy.apex.context.parameters.ContextParameterConstants; +import org.onap.policy.apex.context.parameters.LockManagerParameters; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.common.parameters.ParameterService; + +class LockManagerTest { + + @Test + void testLock() { + var lockManager = new JvmLocalLockManager(); + assertDoesNotThrow(() -> lockManager.lockForReading("test", "test")); + assertDoesNotThrow(() -> lockManager.unlockForReading("test", "test")); + assertThrows(ContextException.class, () -> lockManager.unlockForReading("test", "test")); + assertDoesNotThrow(() -> lockManager.lockForWriting("test", "test")); + assertDoesNotThrow(() -> lockManager.unlockForWriting("test", "test")); + assertThrows(ContextException.class, () -> lockManager.unlockForWriting("test", "test")); + } + + @Test + void testShutDown() { + var lockManager = new JvmLocalLockManager(); + assertDoesNotThrow(lockManager::shutdown); + } + + @Test + void testCreateLockManager() { + var lockManagerFactory = new LockManagerFactory(); + var parameters = new LockManagerParameters(); + parameters.setPluginClass("invalid.class"); + ParameterService.register(parameters); + assertThrows(ContextException.class, () -> lockManagerFactory.createLockManager(new AxArtifactKey())); + ParameterService.deregister(ContextParameterConstants.LOCKING_GROUP_NAME); + + // different plugin instance + parameters.setPluginClass(JvmLocalDistributor.class.getName()); + ParameterService.register(parameters); + assertThrows(ContextException.class, () -> lockManagerFactory.createLockManager(new AxArtifactKey())); + ParameterService.deregister(ContextParameterConstants.LOCKING_GROUP_NAME); + + parameters.setPluginClass(LockManagerParameters.DEFAULT_LOCK_MANAGER_PLUGIN_CLASS); + ParameterService.register(parameters); + assertDoesNotThrow(() -> lockManagerFactory.createLockManager(new AxArtifactKey())); + ParameterService.deregister(ContextParameterConstants.LOCKING_GROUP_NAME); + } +} diff --git a/context/context-management/src/test/java/org/onap/policy/apex/context/impl/PersistorTest.java b/context/context-management/src/test/java/org/onap/policy/apex/context/impl/PersistorTest.java new file mode 100644 index 000000000..277598b4a --- /dev/null +++ b/context/context-management/src/test/java/org/onap/policy/apex/context/impl/PersistorTest.java @@ -0,0 +1,84 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2024 Nordix Foundation. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.context.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.TreeSet; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Test; +import org.onap.policy.apex.context.ContextException; +import org.onap.policy.apex.context.impl.distribution.jvmlocal.JvmLocalDistributor; +import org.onap.policy.apex.context.impl.persistence.PersistorFactory; +import org.onap.policy.apex.context.impl.persistence.ephemeral.EphemeralPersistor; +import org.onap.policy.apex.context.parameters.ContextParameterConstants; +import org.onap.policy.apex.context.parameters.PersistorParameters; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; +import org.onap.policy.common.parameters.ParameterService; + + +class PersistorTest { + + @AfterAll + public static void cleanUpAfterTest() { + ParameterService.deregister(ContextParameterConstants.PERSISTENCE_GROUP_NAME); + ParameterService.clear(); + } + + @Test + void testContextItemRead() throws ContextException { + var persistor = new EphemeralPersistor(); + assertNull(persistor.readContextItem(new AxReferenceKey(), null)); + assertThat(persistor.readContextItems(null, null)).isInstanceOf(TreeSet.class); + persistor.init(new AxArtifactKey("testkey", "1.0.0")); + assertEquals("testkey", persistor.getKey().getName()); + } + + @Test + void testWriteContextItem() { + var persistor = new EphemeralPersistor(); + assertThat(persistor.writeContextItem(new Object())).isInstanceOf(Object.class); + } + + @Test + void testPersistorFactory() { + var factory = new PersistorFactory(); + PersistorParameters params = new PersistorParameters(); + params.setPluginClass("invalid.class"); + ParameterService.register(params); + assertThrows(ContextException.class, () -> factory.createPersistor(new AxArtifactKey())); + ParameterService.deregister(ContextParameterConstants.PERSISTENCE_GROUP_NAME); + + params.setPluginClass(JvmLocalDistributor.class.getName()); + ParameterService.register(params); + assertThrows(ContextException.class, () -> factory.createPersistor(new AxArtifactKey())); + ParameterService.deregister(ContextParameterConstants.PERSISTENCE_GROUP_NAME); + + params.setPluginClass(PersistorParameters.DEFAULT_PERSISTOR_PLUGIN_CLASS); + ParameterService.register(params); + assertDoesNotThrow(() -> factory.createPersistor(new AxArtifactKey())); + } +} diff --git a/context/context-management/src/test/java/org/onap/policy/apex/context/impl/schema/SchemaHelperFactoryTest.java b/context/context-management/src/test/java/org/onap/policy/apex/context/impl/schema/SchemaHelperFactoryTest.java index 501b76c0a..453a614ab 100644 --- a/context/context-management/src/test/java/org/onap/policy/apex/context/impl/schema/SchemaHelperFactoryTest.java +++ b/context/context-management/src/test/java/org/onap/policy/apex/context/impl/schema/SchemaHelperFactoryTest.java @@ -22,13 +22,16 @@ package org.onap.policy.apex.context.impl.schema; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import java.util.Map; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; import org.onap.policy.apex.context.parameters.ContextParameterConstants; +import org.onap.policy.apex.context.parameters.SchemaHelperParameters; import org.onap.policy.apex.context.parameters.SchemaParameters; import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; import org.onap.policy.apex.model.basicmodel.service.ModelService; @@ -86,4 +89,18 @@ class SchemaHelperFactoryTest { .hasMessage("Owner:0.0.1: class/type java.lang.Bad for context schema \"IntSchema:0.0.1\" " + "not found. Check the class path of the JVM"); } + + @Test + void testSchemaHelperParameter() { + var schemaHelperParameters = new SchemaHelperParameters(); + assertNotNull(schemaHelperParameters.toString()); + } + + @Test + void testSchemaParameterSetter() { + var parameters = new SchemaParameters(); + parameters.setName("testSchema"); + parameters.setSchemaHelperParameterMap(Map.of("test", new SchemaHelperParameters())); + assertEquals("testSchema", parameters.getName()); + } } diff --git a/context/context-management/src/test/java/org/onap/policy/apex/context/impl/schema/java/DistributorTest.java b/context/context-management/src/test/java/org/onap/policy/apex/context/impl/schema/java/DistributorTest.java new file mode 100644 index 000000000..5e27be99f --- /dev/null +++ b/context/context-management/src/test/java/org/onap/policy/apex/context/impl/schema/java/DistributorTest.java @@ -0,0 +1,132 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2024 Nordix Foundation. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.context.impl.schema.java; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.onap.policy.apex.context.ContextException; +import org.onap.policy.apex.context.impl.distribution.DistributorFactory; +import org.onap.policy.apex.context.impl.distribution.DistributorFlushTimerTask; +import org.onap.policy.apex.context.impl.distribution.jvmlocal.JvmLocalDistributor; +import org.onap.policy.apex.context.parameters.ContextParameterConstants; +import org.onap.policy.apex.context.parameters.ContextParameters; +import org.onap.policy.apex.context.parameters.DistributorParameters; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.service.ModelService; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextModel; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas; +import org.onap.policy.common.parameters.ParameterService; + + +class DistributorTest { + + @BeforeAll + public static void prepareForTest() { + final var contextParameters = new ContextParameters(); + contextParameters.getLockManagerParameters() + .setPluginClass("org.onap.policy.apex.context.impl.locking.jvmlocal.JvmLocalLockManager"); + contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); + contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); + + ParameterService.register(contextParameters); + ParameterService.register(contextParameters.getDistributorParameters()); + ParameterService.register(contextParameters.getLockManagerParameters()); + ParameterService.register(contextParameters.getPersistorParameters()); + } + + /** + * Clear down the test data. + */ + @AfterAll + public static void cleanUpAfterTest() { + ParameterService.deregister(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); + ParameterService.deregister(ContextParameterConstants.LOCKING_GROUP_NAME); + ParameterService.deregister(ContextParameterConstants.PERSISTENCE_GROUP_NAME); + ParameterService.clear(); + } + + @Test + void testModelRegister() throws ContextException { + var schemas = new AxContextSchemas(); + var simpleIntSchema = new AxContextSchema(new AxArtifactKey("SimpleIntSchema", "0.0.1"), "JAVA", + "java.lang.Integer"); + schemas.getSchemasMap().put(simpleIntSchema.getKey(), simpleIntSchema); + + var axContextAlbum = new AxContextAlbum(new AxArtifactKey("TestContextAlbum", "0.0.1"), "Policy", + true, AxArtifactKey.getNullKey()); + + axContextAlbum.setItemSchema(simpleIntSchema.getKey()); + var model = new AxContextModel(new AxArtifactKey("TestArtifact", "0.0.1")); + var albums = new AxContextAlbums(); + albums.getAlbumsMap().put(axContextAlbum.getKey(), axContextAlbum); + model.setAlbums(albums); + model.setSchemas(schemas); + var distributor = new JvmLocalDistributor(); + assertDoesNotThrow(() -> distributor.registerModel(model)); + + distributor.flush(); + ModelService.clear(); + } + + @Test + void testDistributorFlushTimer() throws ContextException { + var distributor = new JvmLocalDistributor(); + distributor.init(new AxArtifactKey("test", "0.0.1")); + var timerTask = new DistributorFlushTimerTask(distributor); + assertDoesNotThrow(timerTask::run); + assertDoesNotThrow(timerTask::toString); + assertTrue(timerTask.cancel()); + } + + @Test + void testDistributorFactory() { + var dfactory = new DistributorFactory(); + var axArtifactKey = new AxArtifactKey("testKey", "1.0.1"); + assertDoesNotThrow(() -> dfactory.getDistributor(axArtifactKey)); + ParameterService.deregister(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); + var params = new DistributorParameters(); + params.setPluginClass("invalid.class"); + ParameterService.register(params); + assertThrows(ContextException.class, () -> dfactory.getDistributor(axArtifactKey)); + ParameterService.deregister(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); + params.setPluginClass("org.onap.policy.apex.context.impl.persistence.ephemeral.EphemeralPersistor"); + ParameterService.register(params); + assertThrows(ContextException.class, () -> dfactory.getDistributor(axArtifactKey)); + } + + @Test + void testAbstractDistributor() throws ContextException { + var distributor = new JvmLocalDistributor(); + assertThrows(ContextException.class, () -> distributor.removeContextAlbum(new AxArtifactKey())); + assertDoesNotThrow(distributor::flush); + distributor.init(new AxArtifactKey()); + assertDoesNotThrow(distributor::clear); + + } +} diff --git a/core/src/test/java/org/onap/policy/apex/core/infrastructure/threading/MessageExceptionTest.java b/core/src/test/java/org/onap/policy/apex/core/infrastructure/threading/MessageExceptionTest.java new file mode 100644 index 000000000..c28e322fe --- /dev/null +++ b/core/src/test/java/org/onap/policy/apex/core/infrastructure/threading/MessageExceptionTest.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2024 Nordix Foundation. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.core.infrastructure.threading; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; +import org.onap.policy.apex.core.infrastructure.messaging.MessagingException; + + +class MessageExceptionTest { + + @Test + void testMessageException() { + var exception = new MessagingException("Test error"); + assertEquals("Test error", exception.getMessage()); + + var exception2 = new MessagingException("Test error2", new NullPointerException()); + assertThat(exception2).isInstanceOf(MessagingException.class).hasMessage("Test error2"); + } +} diff --git a/examples/examples-acm/src/main/java/org/onap/policy/apex/examples/acm/AcmTestRestDmaapEndpoint.java b/examples/examples-acm/src/main/java/org/onap/policy/apex/examples/acm/AcmTestRestDmaapEndpoint.java deleted file mode 100644 index 8aed72080..000000000 --- a/examples/examples-acm/src/main/java/org/onap/policy/apex/examples/acm/AcmTestRestDmaapEndpoint.java +++ /dev/null @@ -1,97 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2022-2023 Nordix Foundation. - * ================================================================================ - * 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.examples.acm; - -import jakarta.ws.rs.GET; -import jakarta.ws.rs.POST; -import jakarta.ws.rs.Path; -import jakarta.ws.rs.Produces; -import jakarta.ws.rs.QueryParam; -import jakarta.ws.rs.core.Response; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * The Class AcmTestRestDmaapEndpoint creates rest server endpoints for simulating sending/receiving events on DMaaP. - */ -@Path("/") -@Produces("application/json") -public class AcmTestRestDmaapEndpoint { - - private static final XLogger LOGGER = XLoggerFactory.getXLogger(AcmTestRestDmaapEndpoint.class); - private final Object lock = new Object(); - private static String loggedOutputEvent = ""; - private static final AtomicInteger counter = new AtomicInteger(1); - - /** - * DMaaP input of events. This input event triggers the policy - * - * @param timeout the timeout to wait for - * @return the response - */ - @Path("events/AC_ELEMENT_MSG/APEX/1") - @GET - public Response getMessages(@QueryParam("timeout") final int timeout) { - String createRequest = "{\"messageType\":\"STATUS\"," - + "\"elementId\":{\"name\":\"onap.policy.clamp.ac.startertobridge\",\"version\":\"1.0.0\"}," - + "\"message\":\"starter: onap.policy.clamp.ac.starter 1.0.0\",\"messageId\":\"" - + counter.incrementAndGet() + "\",\"timestamp\":\"2022-08-19T07:37:01.198592Z\"}"; - LOGGER.info("Create request received: \n {}", createRequest); - - return Response.status(200).entity(List.of(createRequest)).build(); - } - - /** - * Post new message. - * - * @param jsonString the message - * @return the response - */ - @Path("events/POLICY_UPDATE_MSG") - @POST - public Response policyMessage(final String jsonString) { - LOGGER.info("\n*** POLICY LOG ENTRY START ***\n {} \n *** POLICY LOG ENTRY END ***", jsonString); - synchronized (lock) { - loggedOutputEvent += jsonString + "\n"; - } - return Response.status(200).build(); - } - - /** - * Get the logged event for test verification. - * - * @return the response - */ - @Path("events/getLoggedEvent") - @GET - public Response getDetails() { - String loggedEvent; - synchronized (lock) { - loggedEvent = loggedOutputEvent; - } - if (null == loggedEvent) { - return Response.status(500).entity("Error: Log event not yet generated.").build(); - } - return Response.status(200).entity(loggedEvent).build(); - } -} diff --git a/examples/examples-acm/src/main/java/org/onap/policy/apex/examples/acm/AcmTestServerDmaap.java b/examples/examples-acm/src/main/java/org/onap/policy/apex/examples/acm/AcmTestServerDmaap.java deleted file mode 100644 index fb22d14ac..000000000 --- a/examples/examples-acm/src/main/java/org/onap/policy/apex/examples/acm/AcmTestServerDmaap.java +++ /dev/null @@ -1,64 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2022-2024 Nordix Foundation. - * ================================================================================ - * 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.examples.acm; - -import org.onap.policy.common.endpoints.http.server.HttpServletServer; -import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance; -import org.onap.policy.common.gson.GsonMessageBodyHandler; -import org.onap.policy.common.utils.network.NetworkUtil; - -/** - * The Class AcmTestServerDmaap that manages test servers for REST requests for the test. - */ -public class AcmTestServerDmaap implements AutoCloseable { - private static final String HOST = "localhost"; - private HttpServletServer restServer; - private int restServerPort = 3904; - - /** - * Instantiates a new REST simulator for DMaaP requests. - */ - public AcmTestServerDmaap() { - restServer = HttpServletServerFactoryInstance.getServerFactory().build("AcmTestRestDmaapEndpoint", false, HOST, - restServerPort, false, "/", false, false); - restServer.addServletClass(null, AcmTestRestDmaapEndpoint.class.getName()); - restServer.setSerializationProvider(GsonMessageBodyHandler.class.getName()); - restServer.start(); - } - - /** - * Validate the Rest server. - * @throws InterruptedException if is not alive - */ - public void validate() throws InterruptedException { - if (!NetworkUtil.isTcpPortOpen(HOST, restServerPort, 50, 200L)) { - throw new IllegalStateException("port " + restServerPort + " is still not in use"); - } - } - - @Override - public void close() { - if (restServer != null) { - restServer.stop(); - restServer = null; - } - } -} diff --git a/examples/examples-acm/src/main/resources/examples/config/apexACM/ApexConfig.json b/examples/examples-acm/src/main/resources/examples/config/apexACM/ApexConfig.json index 6a2feaaa0..ae5d36c7c 100644 --- a/examples/examples-acm/src/main/resources/examples/config/apexACM/ApexConfig.json +++ b/examples/examples-acm/src/main/resources/examples/config/apexACM/ApexConfig.json @@ -24,10 +24,21 @@ "eventInputParameters": { "DmaapConsumer": { "carrierTechnologyParameters": { - "carrierTechnology": "RESTCLIENT", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RestClientCarrierTechnologyParameters", + "carrierTechnology": "KAFKA", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.kafka.KafkaCarrierTechnologyParameters", "parameters": { - "url": "http://localhost:3904/events/AC_ELEMENT_MSG/APEX/1?timeout=30000" + "bootstrapServers": "kafka:9092", + "groupId": "clamp-grp", + "enableAutoCommit": "true", + "autoCommitTime": "1000", + "sessionTimeout": "30000", + "consumerPollTime": "100", + "consumerTopicList": [ + "ac_element_msg" + ], + "keyDeserializer": "org.apache.kafka.common.serialization.StringDeserializer", + "valueDeserializer": "org.apache.kafka.common.serialization.StringDeserializer", + "kafkaProperties": [ ] } }, "eventProtocolParameters": { @@ -54,10 +65,19 @@ }, "DmaapReplyProducer": { "carrierTechnologyParameters": { - "carrierTechnology": "RESTCLIENT", - "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RestClientCarrierTechnologyParameters", + "carrierTechnology": "KAFKA", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.kafka.KafkaCarrierTechnologyParameters", "parameters": { - "url": "http://localhost:3904/events/POLICY_UPDATE_MSG" + "bootstrapServers": "kafka:9092", + "acks": "all", + "retries": "0", + "batchSize": "16384", + "lingerTime": "1", + "bufferMemory": "33554432", + "producerTopic": "policy_update_msg", + "keySerializer": "org.apache.kafka.common.serialization.StringSerializer", + "valueSerializer": "org.apache.kafka.common.serialization.StringSerializer", + "kafkaProperties": [ ] } }, "eventProtocolParameters": { diff --git a/examples/examples-acm/src/test/java/org/onap/policy/apex/examples/acm/TestApexAcmExample.java b/examples/examples-acm/src/test/java/org/onap/policy/apex/examples/acm/TestApexAcmExample.java index be4bec096..8b360d39b 100644 --- a/examples/examples-acm/src/test/java/org/onap/policy/apex/examples/acm/TestApexAcmExample.java +++ b/examples/examples-acm/src/test/java/org/onap/policy/apex/examples/acm/TestApexAcmExample.java @@ -20,13 +20,14 @@ package org.onap.policy.apex.examples.acm; -import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertTrue; -import jakarta.ws.rs.client.ClientBuilder; -import java.util.concurrent.TimeUnit; +import java.nio.file.Files; +import java.nio.file.Path; import org.junit.jupiter.api.Test; import org.onap.policy.apex.auth.clieditor.tosca.ApexCliToscaEditorMain; -import org.onap.policy.apex.service.engine.main.ApexMain; + /** * Test class to run an example policy for ACM interaction. Event received on @@ -36,8 +37,7 @@ class TestApexAcmExample { @Test void testExample() { - try (var dmmap = new AcmTestServerDmaap()) { - dmmap.validate(); + try { // @formatter:off final String[] cliArgs = new String[] { @@ -54,29 +54,9 @@ class TestApexAcmExample { }; // @formatter:on - new ApexCliToscaEditorMain(cliArgs); - - // @formatter:off - final String[] apexArgs = { - "-rfr", - "target/classes", - "-p", - "target/classes/APEXacElementPolicy.json" - }; - // @formatter:on - - final var client = ClientBuilder.newClient(); - final var apexMain = new ApexMain(apexArgs); - - await().atMost(5000, TimeUnit.MILLISECONDS).until(apexMain::isAlive); + assertDoesNotThrow(() -> new ApexCliToscaEditorMain(cliArgs)); + assertTrue(Files.exists(Path.of("target/classes/APEXacElementPolicy.json"))); - String getLoggedEventUrl = "http://localhost:3904/events/getLoggedEvent"; - await().atMost(20000, TimeUnit.MILLISECONDS).until(() -> { - var response = client.target(getLoggedEventUrl).request("application/json").get(); - var responseEntity = response.readEntity(String.class); - return responseEntity != null && !responseEntity.isEmpty(); - }); - apexMain.shutdown(); } catch (Exception e) { e.printStackTrace(); } diff --git a/examples/examples-onap-bbs/src/main/java/org/onap/policy/apex/examples/bbs/WebClient.java b/examples/examples-onap-bbs/src/main/java/org/onap/policy/apex/examples/bbs/WebClient.java index 6dfd2b5f2..8e9b4fe7c 100644 --- a/examples/examples-onap-bbs/src/main/java/org/onap/policy/apex/examples/bbs/WebClient.java +++ b/examples/examples-onap-bbs/src/main/java/org/onap/policy/apex/examples/bbs/WebClient.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019 Huawei. All rights reserved. - * Modifications Copyright (C) 2019-2021 Nordix Foundation. + * Modifications Copyright (C) 2019-2021,2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,7 +73,7 @@ public class WebClient { * @param contentType http content type * @return String response message */ - public String httpRequest(String requestUrl, String requestMethod, String outputStr, String username, String pass, + public String httpRequest(URL requestUrl, String requestMethod, String outputStr, String username, String pass, String contentType) { var result = ""; var builder = new StringBuilder(); @@ -81,8 +81,7 @@ public class WebClient { LOGGER.info("httpsRequest starts {} method {}", requestUrl, requestMethod); disableCertificateValidation(); - var url = new URL(requestUrl); - HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(); + var httpUrlConn = (HttpURLConnection) requestUrl.openConnection(); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); diff --git a/examples/examples-onap-bbs/src/test/java/org/onap/policy/apex/examples/bbs/WebClientTest.java b/examples/examples-onap-bbs/src/test/java/org/onap/policy/apex/examples/bbs/WebClientTest.java index a87bddaf0..612b42af6 100644 --- a/examples/examples-onap-bbs/src/test/java/org/onap/policy/apex/examples/bbs/WebClientTest.java +++ b/examples/examples-onap-bbs/src/test/java/org/onap/policy/apex/examples/bbs/WebClientTest.java @@ -26,17 +26,20 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; +import java.net.URL; import javax.net.ssl.HttpsURLConnection; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.Mockito; class WebClientTest { - HttpsURLConnection mockedHttpsUrlConnection; - String sampleString = "Response Code :200"; + private HttpsURLConnection mockedHttpsUrlConnection; + private URL url; + private String sampleString = "Response Code :200"; /** * Set up the mocked REST manager. @@ -46,24 +49,27 @@ class WebClientTest { @BeforeEach void setupMockedRest() throws IOException { mockedHttpsUrlConnection = mock(HttpsURLConnection.class); + url = mock(URL.class); + when(url.openConnection()).thenReturn(mockedHttpsUrlConnection); InputStream inputStream = new ByteArrayInputStream(sampleString.getBytes()); + OutputStream outputStream = new ByteArrayOutputStream(); when(mockedHttpsUrlConnection.getInputStream()).thenReturn(inputStream); - Mockito.doNothing().when(mockedHttpsUrlConnection).connect(); + when(mockedHttpsUrlConnection.getOutputStream()).thenReturn(outputStream); } @Test - void testHttpsRequest() { + void testHttpsPostRequest() { WebClient cl = new WebClient(); String result = cl - .httpRequest("https://some.random.url/data", "POST", null, "admin", "admin", "application/json"); + .httpRequest(url, "POST", null, "admin", "admin", "application/json"); assertNotNull(result); } @Test - void testHttpRequest() { + void testHttpsGetRequest() { WebClient cl = new WebClient(); String result = cl - .httpRequest("http://some.random.url/data", "GET", null, "admin", "admin", "application/json"); + .httpRequest(url, "GET", "sample output string", "admin", "admin", "application/json"); assertNotNull(result); } diff --git a/model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/SupportApexBasicModelTest.java b/model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/SupportApexBasicModelTest.java index 8c1f756c1..b5028273c 100644 --- a/model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/SupportApexBasicModelTest.java +++ b/model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/SupportApexBasicModelTest.java @@ -54,7 +54,7 @@ class SupportApexBasicModelTest { @Test void testModelValid() throws Exception { final AxValidationResult result = testApexModel.testApexModelValid(); - var expectedResult = ResourceUtils.getResourceAsString(VALID_MODEL_STRING); + var expectedResult = normalizeNewlines(ResourceUtils.getResourceAsString(VALID_MODEL_STRING)); assertEquals(expectedResult, result.toString()); } @@ -67,21 +67,21 @@ class SupportApexBasicModelTest { @Test void testApexModelValidateWarning() throws Exception { final AxValidationResult result = testApexModel.testApexModelValidateWarning(); - var expectedResult = ResourceUtils.getResourceAsString(WARNING_MODEL_STRING); + var expectedResult = normalizeNewlines(ResourceUtils.getResourceAsString(WARNING_MODEL_STRING)); assertEquals(expectedResult, result.toString()); } @Test void testModelValidateInvalidModel() throws Exception { final AxValidationResult result = testApexModel.testApexModelValidateInvalidModel(); - var expectedResult = ResourceUtils.getResourceAsString(INVALID_MODEL_STRING); + var expectedResult = normalizeNewlines(ResourceUtils.getResourceAsString(INVALID_MODEL_STRING)); assertEquals(expectedResult, result.toString()); } @Test void testModelValidateMalstructured() throws Exception { final AxValidationResult result = testApexModel.testApexModelValidateMalstructured(); - var expectedResult = ResourceUtils.getResourceAsString(INVALID_MODEL_MALSTRUCTURED_STRING); + var expectedResult = normalizeNewlines(ResourceUtils.getResourceAsString(INVALID_MODEL_MALSTRUCTURED_STRING)); assertEquals(expectedResult, result.toString()); } @@ -89,4 +89,8 @@ class SupportApexBasicModelTest { void testModelWriteReadJson() throws Exception { testApexModel.testApexModelWriteReadJson(); } + + private String normalizeNewlines(String input) { + return input.replace("\r\n", "\n"); + } } diff --git a/model/src/test/java/org/onap/policy/apex/model/contextmodel/handling/ApexContextModelTest.java b/model/src/test/java/org/onap/policy/apex/model/contextmodel/handling/ApexContextModelTest.java index a9cb16914..31083d4c4 100644 --- a/model/src/test/java/org/onap/policy/apex/model/contextmodel/handling/ApexContextModelTest.java +++ b/model/src/test/java/org/onap/policy/apex/model/contextmodel/handling/ApexContextModelTest.java @@ -68,28 +68,28 @@ class ApexContextModelTest { @Test void testApexModelValidateObservation() throws Exception { final AxValidationResult result = testApexModel.testApexModelValidateObservation(); - var expectedResult = ResourceUtils.getResourceAsString(OBSERVATION_MODEL_STRING); + var expectedResult = normalizeNewlines(ResourceUtils.getResourceAsString(OBSERVATION_MODEL_STRING)); assertEquals(expectedResult, result.toString()); } @Test void testApexModelValidateWarning() throws Exception { final AxValidationResult result = testApexModel.testApexModelValidateWarning(); - var expectedResult = ResourceUtils.getResourceAsString(WARNING_MODEL_STRING); + var expectedResult = normalizeNewlines(ResourceUtils.getResourceAsString(WARNING_MODEL_STRING)); assertEquals(expectedResult, result.toString()); } @Test void testModelValidateInvalidModel() throws Exception { final AxValidationResult result = testApexModel.testApexModelValidateInvalidModel(); - var expectedResult = ResourceUtils.getResourceAsString(INVALID_MODEL_STRING); + var expectedResult = normalizeNewlines(ResourceUtils.getResourceAsString(INVALID_MODEL_STRING)); assertEquals(expectedResult, result.toString()); } @Test void testModelValidateMalstructured() throws Exception { final AxValidationResult result = testApexModel.testApexModelValidateMalstructured(); - var expectedResult = ResourceUtils.getResourceAsString(INVALID_MODEL_MALSTRUCTURED_STRING); + var expectedResult = normalizeNewlines(ResourceUtils.getResourceAsString(INVALID_MODEL_MALSTRUCTURED_STRING)); assertEquals(expectedResult, result.toString()); } @@ -97,4 +97,8 @@ class ApexContextModelTest { void testModelWriteReadJson() throws Exception { testApexModel.testApexModelWriteReadJson(); } + + private String normalizeNewlines(String input) { + return input.replace("\r\n", "\n"); + } } diff --git a/model/src/test/java/org/onap/policy/apex/model/eventmodel/handling/ApexEventModelTest.java b/model/src/test/java/org/onap/policy/apex/model/eventmodel/handling/ApexEventModelTest.java index df1857c82..bb50fb35e 100644 --- a/model/src/test/java/org/onap/policy/apex/model/eventmodel/handling/ApexEventModelTest.java +++ b/model/src/test/java/org/onap/policy/apex/model/eventmodel/handling/ApexEventModelTest.java @@ -64,28 +64,28 @@ class ApexEventModelTest { @Test void testApexModelValidateObservation() throws Exception { final AxValidationResult result = testApexModel.testApexModelValidateObservation(); - String expected = ResourceUtils.getResourceAsString(OBSERVATION_MODEL_STRING); + var expected = normalizeNewlines(ResourceUtils.getResourceAsString(OBSERVATION_MODEL_STRING)); assertEquals(expected, result.toString()); } @Test void testApexModelValidateWarning() throws Exception { final AxValidationResult result = testApexModel.testApexModelValidateWarning(); - String expected = ResourceUtils.getResourceAsString(WARNING_MODEL_STRING); + var expected = normalizeNewlines(ResourceUtils.getResourceAsString(WARNING_MODEL_STRING)); assertEquals(expected, result.toString()); } @Test void testModelValidateInvalidModel() throws Exception { final AxValidationResult result = testApexModel.testApexModelValidateInvalidModel(); - String expected = ResourceUtils.getResourceAsString(INVALID_MODEL_STRING); + var expected = normalizeNewlines(ResourceUtils.getResourceAsString(INVALID_MODEL_STRING)); assertEquals(expected, result.toString()); } @Test void testModelValidateMalstructured() throws Exception { final AxValidationResult result = testApexModel.testApexModelValidateMalstructured(); - String expected = ResourceUtils.getResourceAsString(INVALID_MODEL_MALSTRUCTURED_STRING); + var expected = normalizeNewlines(ResourceUtils.getResourceAsString(INVALID_MODEL_MALSTRUCTURED_STRING)); assertEquals(expected, result.toString()); } @@ -93,4 +93,8 @@ class ApexEventModelTest { void testModelWriteReadJson() throws Exception { testApexModel.testApexModelWriteReadJson(); } + + private String normalizeNewlines(String input) { + return input.replace("\r\n", "\n"); + } } diff --git a/model/src/test/java/org/onap/policy/apex/model/policymodel/handling/ApexPolicyModelTest.java b/model/src/test/java/org/onap/policy/apex/model/policymodel/handling/ApexPolicyModelTest.java index 01f7062e1..c943befd5 100644 --- a/model/src/test/java/org/onap/policy/apex/model/policymodel/handling/ApexPolicyModelTest.java +++ b/model/src/test/java/org/onap/policy/apex/model/policymodel/handling/ApexPolicyModelTest.java @@ -61,29 +61,37 @@ class ApexPolicyModelTest { @Test void testApexModelValidateObservation() throws Exception { final AxValidationResult result = testApexModel.testApexModelValidateObservation(); - assertEquals(ResourceUtils.getResourceAsString(OBSERVATION_MODEL_STRING), result.toString()); + var expectedOutput = normalizeNewlines(ResourceUtils.getResourceAsString(OBSERVATION_MODEL_STRING)); + assertEquals(expectedOutput, result.toString()); } @Test void testApexModelValidateWarning() throws Exception { final AxValidationResult result = testApexModel.testApexModelValidateWarning(); - assertEquals(ResourceUtils.getResourceAsString(WARNING_MODEL_STRING), result.toString()); + var expectedOutput = normalizeNewlines(ResourceUtils.getResourceAsString(WARNING_MODEL_STRING)); + assertEquals(expectedOutput, result.toString()); } @Test void testModelValidateInvalidModel() throws Exception { final AxValidationResult result = testApexModel.testApexModelValidateInvalidModel(); - assertEquals(ResourceUtils.getResourceAsString(INVALID_MODEL_STRING), result.toString()); + var expectedOutput = normalizeNewlines(ResourceUtils.getResourceAsString(INVALID_MODEL_STRING)); + assertEquals(expectedOutput, result.toString()); } @Test void testModelValidateMalstructured() throws Exception { final AxValidationResult result = testApexModel.testApexModelValidateMalstructured(); - assertEquals(ResourceUtils.getResourceAsString(INVALID_MODEL_MALSTRUCTURED_STRING), result.toString()); + var expectedOutput = normalizeNewlines(ResourceUtils.getResourceAsString(INVALID_MODEL_MALSTRUCTURED_STRING)); + assertEquals(expectedOutput, result.toString()); } @Test void testModelWriteReadJson() throws Exception { testApexModel.testApexModelWriteReadJson(); } + + private String normalizeNewlines(String input) { + return input.replace("\r\n", "\n"); + } } diff --git a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/test/java/org/onap/policy/apex/plugins/event/carrier/restclient/ApexRestClientConsumerTest.java b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/test/java/org/onap/policy/apex/plugins/event/carrier/restclient/ApexRestClientConsumerTest.java index b3a6bca06..d87d7aab3 100644 --- a/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/test/java/org/onap/policy/apex/plugins/event/carrier/restclient/ApexRestClientConsumerTest.java +++ b/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-restclient/src/test/java/org/onap/policy/apex/plugins/event/carrier/restclient/ApexRestClientConsumerTest.java @@ -37,9 +37,7 @@ import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; diff --git a/testsuites/integration/integration-common/src/test/java/org/onap/policy/apex/testsuites/integration/common/concepts/ConceptsTest.java b/testsuites/integration/integration-common/src/test/java/org/onap/policy/apex/testsuites/integration/common/concepts/ConceptsTest.java new file mode 100644 index 000000000..7592978cd --- /dev/null +++ b/testsuites/integration/integration-common/src/test/java/org/onap/policy/apex/testsuites/integration/common/concepts/ConceptsTest.java @@ -0,0 +1,183 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2024 Nordix Foundation. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.testsuites.integration.common.concepts; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +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 java.util.Date; +import java.util.Map; +import java.util.TreeSet; +import org.junit.jupiter.api.Test; +import org.onap.policy.apex.context.test.concepts.TestContextBooleanItem; +import org.onap.policy.apex.context.test.concepts.TestContextByteItem; +import org.onap.policy.apex.context.test.concepts.TestContextDateItem; +import org.onap.policy.apex.context.test.concepts.TestContextDateLocaleItem; +import org.onap.policy.apex.context.test.concepts.TestContextDateTzItem; +import org.onap.policy.apex.context.test.concepts.TestContextDoubleItem; +import org.onap.policy.apex.context.test.concepts.TestContextFloatItem; +import org.onap.policy.apex.context.test.concepts.TestContextIntItem; +import org.onap.policy.apex.context.test.concepts.TestContextLongItem; +import org.onap.policy.apex.context.test.concepts.TestContextLongObjectItem; +import org.onap.policy.apex.context.test.concepts.TestContextStringItem; +import org.onap.policy.apex.context.test.concepts.TestContextTreeMapItem; +import org.onap.policy.apex.context.test.concepts.TestContextTreeSetItem; + +class ConceptsTest { + + @Test + void testConceptBooleanItem() { + assertDoesNotThrow(() -> new TestContextBooleanItem()); + assertDoesNotThrow(() -> new TestContextBooleanItem(true)); + var item = new TestContextBooleanItem(); + item.setFlag(false); + assertFalse(item.isFlag()); + } + + @Test + void testContextByteItem() { + assertDoesNotThrow(() -> new TestContextByteItem()); + assertDoesNotThrow(() -> new TestContextByteItem((byte) 1)); + var byteItem = new TestContextByteItem(); + byteItem.setByteValue((byte) 0); + assertEquals((byte) 0, byteItem.getByteValue()); + assertEquals((byte) 1, byteItem.getIncrementedByteValue()); + } + + @Test + void testContextDateItem() { + assertDoesNotThrow(() -> new TestContextDateItem()); + assertDoesNotThrow(() -> new TestContextDateItem(new Date())); + assertDoesNotThrow(() -> new TestContextDateItem(1726611256L)); + var date = new TestContextDateItem(); + date.setDateValue(new Date()); + assertThat(date.getDateValue()).isInstanceOf(Date.class); + var date2 = new TestContextDateItem(); + assertThat(date2.getMonth()).isInstanceOf(Integer.class); + assertThat(date2.getYear()).isInstanceOf(Integer.class); + assertThat(date2.getDay()).isInstanceOf(Integer.class); + assertThat(date2.getTime()).isInstanceOf(Long.class); + assertThat(date2.getMilliSecond()).isInstanceOf(Integer.class); + assertThat(date2.getMinute()).isInstanceOf(Integer.class); + assertThat(date2.getHour()).isInstanceOf(Integer.class); + assertThat(date2.getSecond()).isInstanceOf(Integer.class); + var date3 = new TestContextDateItem(null); + assertNotNull(date3.getDateValue()); + } + + @Test + void testContextDateLocaleItem() { + assertDoesNotThrow(() -> new TestContextDateLocaleItem()); + assertDoesNotThrow(() -> new TestContextDateLocaleItem(new TestContextDateLocaleItem())); + assertDoesNotThrow(() -> new TestContextDateLocaleItem(new TestContextDateItem(), "UTC", true, + 1, "english", "Ireland")); + var localeItem = new TestContextDateLocaleItem(); + localeItem.setTzValue("utc"); + assertNotNull(localeItem.getTzValue()); + } + + @Test + void testContextDateTzItem() { + assertDoesNotThrow(() -> new TestContextDateTzItem()); + assertDoesNotThrow(() -> new TestContextDateTzItem(new TestContextDateTzItem())); + assertDoesNotThrow(() -> new TestContextDateTzItem(new TestContextDateItem(), "utc", false)); + var tzItem = new TestContextDateTzItem(); + tzItem.setTzValue("utc"); + assertNotNull(tzItem.getTzValue()); + assertThat(tzItem.getTzValue()).isInstanceOf(String.class); + } + + @Test + void testContextDoubleItem() { + assertDoesNotThrow(() -> new TestContextDoubleItem()); + assertDoesNotThrow(() -> new TestContextDoubleItem(0)); + var doubleItem = new TestContextDoubleItem(); + doubleItem.setDoubleValue(0); + assertEquals(1, doubleItem.getIncrementedDoubleValue()); + } + + @Test + void testContextFloatItem() { + assertDoesNotThrow(() -> new TestContextFloatItem()); + assertDoesNotThrow(() -> new TestContextFloatItem(0)); + var floatItem = new TestContextFloatItem(); + floatItem.setFloatValue(0); + assertEquals(1, floatItem.getIncrementedFloatValue()); + } + + @Test + void testContextIntItem() { + assertDoesNotThrow(() -> new TestContextIntItem()); + assertDoesNotThrow(() -> new TestContextIntItem(0)); + var intItem = new TestContextIntItem(); + intItem.setIntValue(0); + assertEquals(1, intItem.getIncrementedIntValue()); + } + + @Test + void testContextLongItem() { + assertDoesNotThrow(() -> new TestContextLongItem()); + assertDoesNotThrow(() -> new TestContextLongItem(0)); + var longItem = new TestContextLongItem(); + longItem.setLongValue(0); + assertEquals(1, longItem.getIncrementedLongValue()); + } + + @Test + void testContextLongObjectItem() { + assertDoesNotThrow(() -> new TestContextLongObjectItem()); + assertDoesNotThrow(() -> new TestContextLongObjectItem(0L)); + var longObjItem = new TestContextLongObjectItem(); + longObjItem.setLongValue(0L); + assertEquals(1, longObjItem.getIncrementedLongValue()); + } + + @Test + void testContextStringItem() { + assertDoesNotThrow(() -> new TestContextStringItem()); + assertDoesNotThrow(() -> new TestContextStringItem("test")); + var strItem = new TestContextStringItem(); + strItem.setStringValue("test"); + assertEquals("test", strItem.getStringValue()); + } + + @Test + void testContextTreeMapItem() { + assertDoesNotThrow(() -> new TestContextTreeMapItem()); + assertDoesNotThrow(() -> new TestContextTreeMapItem(Map.of("", ""))); + var treeMapItem = new TestContextTreeMapItem(); + treeMapItem.setMapValue(Map.of("test", "testVal")); + assertEquals("testVal", treeMapItem.getMapValue().get("test")); + } + + @Test + void testContextTreeSetItem() { + assertDoesNotThrow(() -> new TestContextTreeSetItem()); + var items = new TreeSet<String>(); + assertDoesNotThrow(() -> new TestContextTreeSetItem(items)); + } + + + +} diff --git a/tools/tools-common/src/test/java/org/onap/policy/apex/tools/common/OutputFileTest.java b/tools/tools-common/src/test/java/org/onap/policy/apex/tools/common/OutputFileTest.java index decbb4395..b8364c2ec 100644 --- a/tools/tools-common/src/test/java/org/onap/policy/apex/tools/common/OutputFileTest.java +++ b/tools/tools-common/src/test/java/org/onap/policy/apex/tools/common/OutputFileTest.java @@ -23,7 +23,6 @@ package org.onap.policy.apex.tools.common; 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.assertTrue; import java.io.File; import java.nio.file.FileSystems; @@ -41,7 +40,7 @@ class OutputFileTest { @BeforeEach void beforeSetUp() { if (file.exists()) { - assertTrue(file.delete()); + file.delete(); } } @@ -80,7 +79,7 @@ class OutputFileTest { @AfterEach void testDown() { if (file.exists()) { - assertTrue(file.delete()); + file.delete(); } } } |