diff options
Diffstat (limited to 'participant/participant-impl/participant-impl-policy/src/test/java')
7 files changed, 1133 insertions, 0 deletions
diff --git a/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/controlloop/participant/policy/main/handler/TestPolicyHandler.java b/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/controlloop/participant/policy/main/handler/TestPolicyHandler.java new file mode 100644 index 000000000..abc3e71b8 --- /dev/null +++ b/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/controlloop/participant/policy/main/handler/TestPolicyHandler.java @@ -0,0 +1,134 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 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.clamp.controlloop.participant.policy.main.handler; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.clamp.controlloop.common.ControlLoopConstants; +import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopOrderedState; +import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantControlLoopStateChange; +import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantControlLoopUpdate; +import org.onap.policy.clamp.controlloop.participant.intermediary.comm.ControlLoopStateChangeListener; +import org.onap.policy.clamp.controlloop.participant.intermediary.comm.ControlLoopUpdateListener; +import org.onap.policy.clamp.controlloop.participant.policy.main.parameters.CommonTestData; +import org.onap.policy.clamp.controlloop.participant.policy.main.startstop.Main; +import org.onap.policy.clamp.controlloop.participant.policy.main.startstop.ParticipantPolicyActivator; +import org.onap.policy.clamp.controlloop.participant.policy.main.utils.TestListenerUtils; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.utils.services.Registry; + +public class TestPolicyHandler { + + private static ControlLoopUpdateListener clUpdateListener; + private ControlLoopStateChangeListener clStateChangeListener; + private static ParticipantControlLoopUpdate participantControlLoopUpdateMsg; + private ParticipantControlLoopStateChange participantControlLoopStateChangeMsg; + private static final String PARTICIPANTS_ENDPOINT = "participants"; + private static final String ELEMENTS_ENDPOINT = "elements"; + private static final CommInfrastructure INFRA = CommInfrastructure.NOOP; + private static final String TOPIC = "my-topic"; + private static final Object lockit = new Object(); + static CommonTestData commonTestData = new CommonTestData(); + + /** + * Setup before class, instantiate Main. + * + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + Registry.newRegistry(); + final String[] configParameters = {"-c", "src/test/resources/parameters/TestParameters.json"}; + Main main = new Main(configParameters); + assertTrue(main.isRunning()); + TestListenerUtils.initParticipantHandler(); + + clUpdateListener = new ControlLoopUpdateListener( + PolicyHandler.getInstance() + .getPolicyProvider() + .getIntermediaryApi() + .getParticipantHandler()); + participantControlLoopUpdateMsg = + TestListenerUtils.createControlLoopUpdateMsg(); + participantControlLoopUpdateMsg.getControlLoop().setOrderedState(ControlLoopOrderedState.PASSIVE); + } + + @Test + public void testUpdatePolicyTypes() throws Exception { + // Verify that the ToscaServicetemplate has policy_types + assertNotNull(participantControlLoopUpdateMsg.getControlLoopDefinition().getPolicyTypes()); + + synchronized (lockit) { + clUpdateListener.onTopicEvent(INFRA, TOPIC, null, participantControlLoopUpdateMsg); + } + // Verify the result of GET participants with what is stored + assertEquals("org.onap.PM_Policy", + TestListenerUtils.getParticipantHandler().getParticipantId().getName()); + } + + @Test + public void testUpdatePolicies() throws Exception { + // Add policies to the toscaServiceTemplate + TestListenerUtils.addPoliciesToToscaServiceTemplate(participantControlLoopUpdateMsg.getControlLoopDefinition()); + + // Verify that the ToscaServicetemplate has policies + assertNotNull(participantControlLoopUpdateMsg.getControlLoopDefinition() + .getToscaTopologyTemplate().getPolicies()); + + synchronized (lockit) { + clUpdateListener.onTopicEvent(INFRA, TOPIC, null, participantControlLoopUpdateMsg); + } + // Verify the result of GET participants with what is stored + assertEquals("org.onap.PM_Policy", + TestListenerUtils.getParticipantHandler().getParticipantId().getName()); + } + + @Test + public void testDeletePoliciesAndPolicyTypes() throws Exception { + // Add policies to the toscaServiceTemplate + TestListenerUtils.addPoliciesToToscaServiceTemplate(participantControlLoopUpdateMsg.getControlLoopDefinition()); + + // Verify that the ToscaServicetemplate has policies + assertNotNull(participantControlLoopUpdateMsg.getControlLoopDefinition() + .getToscaTopologyTemplate().getPolicies()); + + synchronized (lockit) { + clUpdateListener.onTopicEvent(INFRA, TOPIC, null, participantControlLoopUpdateMsg); + } + // Verify the result of GET participants with what is stored + assertEquals("org.onap.PM_Policy", + TestListenerUtils.getParticipantHandler().getParticipantId().getName()); + + clStateChangeListener = new ControlLoopStateChangeListener(TestListenerUtils.getParticipantHandler()); + participantControlLoopStateChangeMsg = + TestListenerUtils.createControlLoopStateChangeMsg(ControlLoopOrderedState.UNINITIALISED); + participantControlLoopStateChangeMsg.setOrderedState(ControlLoopOrderedState.UNINITIALISED); + clStateChangeListener.onTopicEvent(INFRA, TOPIC, null, participantControlLoopStateChangeMsg); + + // Verify the result of GET participants with what is stored + assertEquals("org.onap.PM_Policy", + TestListenerUtils.getParticipantHandler().getParticipantId().getName()); + } +} diff --git a/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/controlloop/participant/policy/main/parameters/CommonTestData.java b/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/controlloop/participant/policy/main/parameters/CommonTestData.java new file mode 100644 index 000000000..e3d7e3aa5 --- /dev/null +++ b/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/controlloop/participant/policy/main/parameters/CommonTestData.java @@ -0,0 +1,221 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 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.clamp.controlloop.participant.policy.main.parameters; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import javax.ws.rs.core.Response; +import org.onap.policy.clamp.controlloop.common.exception.ControlLoopRuntimeException; +import org.onap.policy.common.endpoints.parameters.TopicParameters; +import org.onap.policy.common.parameters.ParameterGroup; +import org.onap.policy.common.utils.coder.Coder; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.common.utils.coder.StandardCoder; +import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; + +/** + * Class to hold/create all parameters for test cases. + */ +public class CommonTestData { + public static final String PARTICIPANT_GROUP_NAME = "ControlLoopParticipantGroup"; + public static final String DESCRIPTION = "Participant description"; + public static final long TIME_INTERVAL = 2000; + public static final List<TopicParameters> TOPIC_PARAMS = Arrays.asList(getTopicParams()); + + public static final Coder coder = new StandardCoder(); + + /** + * Converts the contents of a map to a parameter class. + * + * @param source property map + * @param clazz class of object to be created from the map + * @return a new object represented by the map + */ + public <T extends ParameterGroup> T toObject(final Map<String, Object> source, final Class<T> clazz) { + try { + return coder.convert(source, clazz); + } catch (final CoderException e) { + throw new RuntimeException("cannot create " + clazz.getName() + " from map", e); + } + } + + /** + * Returns a property map for a ParticipantPolicyParameters map for test cases. + * + * @param name name of the parameters + * + * @return a property map suitable for constructing an object + */ + public Map<String, Object> getParticipantPolicyParametersMap(final String name) { + final Map<String, Object> map = new TreeMap<>(); + + map.put("name", name); + map.put("intermediaryParameters", getIntermediaryParametersMap(false)); + map.put("databaseProviderParameters", getDatabaseProviderParametersMap(false)); + return map; + } + + /** + * Returns a property map for a databaseProviderParameters map for test cases. + * + * @param isEmpty boolean value to represent that object created should be empty or not + * @return a property map suitable for constructing an object + */ + public Map<String, Object> getDatabaseProviderParametersMap(final boolean isEmpty) { + final Map<String, Object> map = new TreeMap<>(); + if (!isEmpty) { + map.put("name", "PolicyProviderParameterGroup"); + map.put("implementation", "org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl"); + map.put("databaseDriver", "org.h2.Driver"); + map.put("databaseUrl", "jdbc:h2:mem:testdb"); + map.put("databaseUser", "policy"); + map.put("databasePassword", "P01icY"); + map.put("persistenceUnit", "ToscaConceptTest"); + } + + return map; + } + + /** + * Returns a property map for a intermediaryParameters map for test cases. + * + * @param isEmpty boolean value to represent that object created should be empty or not + * @return a property map suitable for constructing an object + */ + public Map<String, Object> getIntermediaryParametersMap(final boolean isEmpty) { + final Map<String, Object> map = new TreeMap<>(); + if (!isEmpty) { + map.put("name", "Participant parameters"); + map.put("reportingTimeInterval", TIME_INTERVAL); + map.put("description", DESCRIPTION); + map.put("participantId", getParticipantId()); + map.put("participantType", getParticipantId()); + map.put("clampControlLoopTopics", getTopicParametersMap(false)); + } + + return map; + } + + /** + * Returns a property map for a TopicParameters map for test cases. + * + * @param isEmpty boolean value to represent that object created should be empty or not + * @return a property map suitable for constructing an object + */ + public Map<String, Object> getTopicParametersMap(final boolean isEmpty) { + final Map<String, Object> map = new TreeMap<>(); + if (!isEmpty) { + map.put("topicSources", TOPIC_PARAMS); + map.put("topicSinks", TOPIC_PARAMS); + } + return map; + } + + /** + * Returns topic parameters for test cases. + * + * @return topic parameters + */ + public static TopicParameters getTopicParams() { + final TopicParameters topicParams = new TopicParameters(); + topicParams.setTopic("POLICY-CLRUNTIME-PARTICIPANT"); + topicParams.setTopicCommInfrastructure("dmaap"); + topicParams.setServers(Arrays.asList("localhost")); + return topicParams; + } + + /** + * Returns participantId for test cases. + * + * @return participant Id + */ + public static ToscaConceptIdentifier getParticipantId() { + final ToscaConceptIdentifier participantId = new ToscaConceptIdentifier("org.onap.PM_Policy", "0.0.0"); + return participantId; + } + + /** + * Gets the standard participant parameters. + * + * @param port port to be inserted into the parameters + * @return the standard participant parameters + */ + public ParticipantPolicyParameters getParticipantPolicyParameters(int port) { + try { + return coder.decode(getParticipantPolicyParametersAsString(port), ParticipantPolicyParameters.class); + + } catch (CoderException e) { + throw new ControlLoopRuntimeException(Response.Status.NOT_ACCEPTABLE, + "cannot read participant parameters", e); + } + } + + /** + * Gets the standard participant parameters, as a String. + * + * @param port port to be inserted into the parameters + * @return the standard participant parameters + */ + public static String getParticipantPolicyParametersAsString(int port) { + + try { + File file = new File(getParamFile()); + String json = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); + + json = json.replace("${port}", String.valueOf(port)); + json = json.replace("${dbName}", "jdbc:h2:mem:testdb"); + + return json; + + } catch (IOException e) { + throw new ControlLoopRuntimeException(Response.Status.NOT_ACCEPTABLE, + "cannot read participant parameters", e); + + } + } + + /** + * Gets the full path to the parameter file, which may vary depending on whether or + * not this is an end-to-end test. + * + * @return the parameter file name + */ + private static String getParamFile() { + String paramFile = "src/test/resources/parameters/TestParametersStd.json"; + return paramFile; + } + + /** + * Nulls out a field within a JSON string. + * @param json JSON string + * @param field field to be nulled out + * @return a new JSON string with the field nulled out + */ + public String nullifyField(String json, String field) { + return json.replace(field + "\"", field + "\":null, \"" + field + "Xxx\""); + } +} diff --git a/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/controlloop/participant/policy/main/parameters/TestParticipantPolicyParameterHandler.java b/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/controlloop/participant/policy/main/parameters/TestParticipantPolicyParameterHandler.java new file mode 100644 index 000000000..dd62dbfc4 --- /dev/null +++ b/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/controlloop/participant/policy/main/parameters/TestParticipantPolicyParameterHandler.java @@ -0,0 +1,98 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 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.clamp.controlloop.participant.policy.main.parameters; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.FileNotFoundException; +import org.apache.commons.io.DirectoryWalker.CancelException; +import org.junit.Test; +import org.onap.policy.clamp.controlloop.common.exception.ControlLoopException; +import org.onap.policy.clamp.controlloop.participant.policy.main.startstop.ParticipantPolicyCommandLineArguments; +import org.onap.policy.common.utils.coder.CoderException; + +public class TestParticipantPolicyParameterHandler { + + @Test + public void testParameterHandlerNoParameterFile() throws ControlLoopException { + final String[] emptyArgumentString = { "-c", "src/test/resources/parameters/NoParametersFile.json" }; + + final ParticipantPolicyCommandLineArguments emptyArguments = new ParticipantPolicyCommandLineArguments(); + emptyArguments.parse(emptyArgumentString); + + assertThatThrownBy(() -> new ParticipantPolicyParameterHandler().getParameters(emptyArguments)) + .hasCauseInstanceOf(CoderException.class) + .hasRootCauseInstanceOf(FileNotFoundException.class); + } + + @Test + public void testParameterHandlerInvalidParameters() throws ControlLoopException { + final String[] invalidArgumentString = { "-c", "src/test/resources/parameters/InvalidParameters.json" }; + + final ParticipantPolicyCommandLineArguments invalidArguments = + new ParticipantPolicyCommandLineArguments(); + invalidArguments.parse(invalidArgumentString); + + assertThatThrownBy(() -> new ParticipantPolicyParameterHandler().getParameters(invalidArguments)) + .hasMessageStartingWith("error reading parameters from") + .hasCauseInstanceOf(CoderException.class); + } + + @Test + public void testParticipantPolicyParameters() throws ControlLoopException { + final String[] participantConfigParameters = { "-c", "src/test/resources/parameters/TestParameters.json" }; + + final ParticipantPolicyCommandLineArguments arguments = new ParticipantPolicyCommandLineArguments(); + arguments.parse(participantConfigParameters); + + final ParticipantPolicyParameters parGroup = new ParticipantPolicyParameterHandler() + .getParameters(arguments); + assertTrue(arguments.checkSetConfigurationFilePath()); + assertEquals(CommonTestData.PARTICIPANT_GROUP_NAME, parGroup.getName()); + } + + @Test + public void testParticipantVersion() throws ControlLoopException { + final String[] participantConfigParameters = { "-v" }; + final ParticipantPolicyCommandLineArguments arguments = new ParticipantPolicyCommandLineArguments(); + final String version = arguments.parse(participantConfigParameters); + assertThat(arguments.parse(participantConfigParameters)).startsWith( + "ONAP Tosca defined control loop Participant"); + } + + @Test + public void testParticipantHelp() throws ControlLoopException { + final String[] participantConfigParameters = { "-h" }; + final ParticipantPolicyCommandLineArguments arguments = new ParticipantPolicyCommandLineArguments(); + assertThat(arguments.parse(participantConfigParameters)).startsWith("usage:"); + } + + @Test + public void testParticipantInvalidOption() throws ControlLoopException { + final String[] participantConfigParameters = { "-d" }; + final ParticipantPolicyCommandLineArguments arguments = new ParticipantPolicyCommandLineArguments(); + assertThatThrownBy(() -> arguments.parse(participantConfigParameters)) + .hasMessageStartingWith("invalid command line arguments specified"); + } +} diff --git a/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/controlloop/participant/policy/main/parameters/TestParticipantPolicyParameters.java b/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/controlloop/participant/policy/main/parameters/TestParticipantPolicyParameters.java new file mode 100644 index 000000000..5ffe5101d --- /dev/null +++ b/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/controlloop/participant/policy/main/parameters/TestParticipantPolicyParameters.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 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.clamp.controlloop.participant.policy.main.parameters; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; + +import java.util.Map; +import org.junit.Test; +import org.onap.policy.common.parameters.ValidationResult; + +public class TestParticipantPolicyParameters { + CommonTestData commonTestData = new CommonTestData(); + + @Test + public void testParticipantPolicyParameters_Named() { + final ParticipantPolicyParameters participantParameters = new ParticipantPolicyParameters("my-name"); + assertEquals("my-name", participantParameters.getName()); + } + + @Test + public void testParticipantPolicyParameters() { + final ParticipantPolicyParameters participantParameters = commonTestData.toObject( + commonTestData.getParticipantPolicyParametersMap(CommonTestData.PARTICIPANT_GROUP_NAME), + ParticipantPolicyParameters.class); + assertThat(participantParameters.validate().isValid()).isTrue(); + } + + @Test + public void testParticipantPolicyParameters_NullName() { + final ParticipantPolicyParameters participantParameters = commonTestData + .toObject(commonTestData.getParticipantPolicyParametersMap(null), + ParticipantPolicyParameters.class); + final ValidationResult validationResult = participantParameters.validate(); + assertFalse(validationResult.isValid()); + assertEquals(null, participantParameters.getName()); + assertThat(validationResult.getResult()).contains("is null"); + } + + @Test + public void testParticipantPolicyParameters_EmptyName() { + final ParticipantPolicyParameters participantParameters = commonTestData + .toObject(commonTestData.getParticipantPolicyParametersMap(""), + ParticipantPolicyParameters.class); + final ValidationResult validationResult = participantParameters.validate(); + assertFalse(validationResult.isValid()); + assertEquals("", participantParameters.getName()); + assertThat(validationResult.getResult()).contains( + "item \"name\" value \"\" INVALID, " + "is blank"); + } + + @Test + public void testParticipantPolicyParameters_SetName() { + final ParticipantPolicyParameters participantParameters = commonTestData.toObject( + commonTestData.getParticipantPolicyParametersMap(CommonTestData.PARTICIPANT_GROUP_NAME), + ParticipantPolicyParameters.class); + participantParameters.setName("ParticipantNewGroup"); + assertThat(participantParameters.validate().isValid()).isTrue(); + assertEquals("ParticipantNewGroup", participantParameters.getName()); + } + + @Test + public void testParticipantPolicyParameters_EmptyParticipantIntermediaryParameters() { + final Map<String, Object> map = + commonTestData.getParticipantPolicyParametersMap(CommonTestData.PARTICIPANT_GROUP_NAME); + map.replace("intermediaryParameters", commonTestData.getIntermediaryParametersMap(true)); + final ParticipantPolicyParameters participantParameters = + commonTestData.toObject(map, ParticipantPolicyParameters.class); + final ValidationResult validationResult = participantParameters.validate(); + assertNull(validationResult.getResult()); + } + + @Test + public void testParticipantPolicyParametersp_EmptyTopicParameters() { + final Map<String, Object> map = + commonTestData.getParticipantPolicyParametersMap(CommonTestData.PARTICIPANT_GROUP_NAME); + final Map<String, Object> intermediaryParametersMap = commonTestData.getIntermediaryParametersMap(false); + intermediaryParametersMap.put("clampControlLoopTopics", commonTestData.getTopicParametersMap(true)); + map.replace("intermediaryParameters", intermediaryParametersMap); + + final ParticipantPolicyParameters participantParameters = + commonTestData.toObject(map, ParticipantPolicyParameters.class); + final ValidationResult validationResult = participantParameters.validate(); + assertNull(validationResult.getResult()); + } +} diff --git a/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/controlloop/participant/policy/main/startstop/TestMain.java b/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/controlloop/participant/policy/main/startstop/TestMain.java new file mode 100644 index 000000000..f77b678c0 --- /dev/null +++ b/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/controlloop/participant/policy/main/startstop/TestMain.java @@ -0,0 +1,143 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 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.clamp.controlloop.participant.policy.main.startstop; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.clamp.controlloop.common.ControlLoopConstants; +import org.onap.policy.clamp.controlloop.common.exception.ControlLoopRuntimeException; +import org.onap.policy.common.utils.resources.MessageConstants; +import org.onap.policy.common.utils.services.Registry; + +public class TestMain { + + /** + * Set up. + */ + @BeforeClass + public static void setUp() { + Registry.newRegistry(); + } + + /** + * Shuts "main" down. + * + * @throws Exception if an error occurs + */ + @AfterClass + public static void tearDown() throws Exception { + // shut down activator + final ParticipantPolicyActivator activator = + Registry.getOrDefault(ControlLoopConstants.REG_CLRUNTIME_ACTIVATOR, + ParticipantPolicyActivator.class, null); + if (activator != null && activator.isAlive()) { + activator.shutdown(); + } + } + + @Test + public void testMain_Help() { + final String[] configParameters = {"-h"}; + Main main = new Main(configParameters); + assertFalse(main.isRunning()); + } + + @Test + public void testMain_Version() { + final String[] configParameters = {"-v"}; + Main main = new Main(configParameters); + assertFalse(main.isRunning()); + } + + @Test + public void testMain_Valid() { + final String[] configParameters = {"-c", "src/test/resources/parameters/TestParameters.json"}; + Main main = new Main(configParameters); + assertTrue(main.isRunning()); + + assertThatCode(() -> main.shutdown()).doesNotThrowAnyException(); + + assertFalse(main.isRunning()); + } + + @Test + public void testMain_NoParameter() { + assertThatConfigParameterThrownException(new String[] {}); + } + + @Test + public void testMain_FilePathNotDefined() { + assertThatConfigParameterThrownException(new String[] {"-c"}); + } + + @Test + public void testMain_TooManyCommand() { + assertThatConfigParameterThrownException(new String[] {"-h", "d"}); + } + + @Test + public void testMain_WrongParameter() { + assertThatConfigParameterThrownException(new String[] {"-d"}); + } + + private void assertThatConfigParameterThrownException(final String[] configParameters) { + assertThatThrownBy(() -> Main.main(configParameters)).isInstanceOf(ControlLoopRuntimeException.class) + .hasMessage(String.format(MessageConstants.START_FAILURE_MSG, MessageConstants.POLICY_CLAMP)); + } + + @Test + public void testParticipant_NoFileWithThisName() { + assertThatConfigFileThrownException("src/test/resources/parameters/NoFileWithThisName.json"); + } + + @Test + public void testParticipant_NotValidFile() { + assertThatConfigFileThrownException("src/test/resources/parameters"); + } + + @Test + public void testParticipant_NoParameters() { + assertThatConfigFileThrownException("src/test/resources/parameters/NoParameters.json"); + } + + @Test + public void testParticipant_InvalidParameters() { + assertThatConfigFileThrownException("src/test/resources/parameters/InvalidParameters.json"); + } + + @Test + public void testParticipant_WrongJsonFormat() { + assertThatConfigFileThrownException("src/test/resources/parameters/Unreadable.json"); + } + + private void assertThatConfigFileThrownException(final String configFilePath) { + final String[] configParameters = new String[] {"-c", configFilePath}; + assertThatThrownBy(() -> new Main(configParameters)).isInstanceOf(ControlLoopRuntimeException.class) + .hasMessage(String.format(MessageConstants.START_FAILURE_MSG, MessageConstants.POLICY_CLAMP)); + } +} diff --git a/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/controlloop/participant/policy/main/startstop/TestParticipantPolicyActivator.java b/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/controlloop/participant/policy/main/startstop/TestParticipantPolicyActivator.java new file mode 100644 index 000000000..afb0f6cb4 --- /dev/null +++ b/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/controlloop/participant/policy/main/startstop/TestParticipantPolicyActivator.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 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.clamp.controlloop.participant.policy.main.startstop; + +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.clamp.controlloop.participant.policy.main.parameters.CommonTestData; +import org.onap.policy.clamp.controlloop.participant.policy.main.parameters.ParticipantPolicyParameterHandler; +import org.onap.policy.clamp.controlloop.participant.policy.main.parameters.ParticipantPolicyParameters; +import org.onap.policy.common.utils.services.Registry; + +public class TestParticipantPolicyActivator { + + private static ParticipantPolicyActivator activator; + + /** + * Initializes an activator. + * + * @throws Exception if an error occurs + */ + @BeforeClass + public static void setUp() throws Exception { + Registry.newRegistry(); + final String[] participantConfigParameters = { "-c", "src/test/resources/parameters/TestParameters.json"}; + final ParticipantPolicyCommandLineArguments arguments = + new ParticipantPolicyCommandLineArguments(participantConfigParameters); + final ParticipantPolicyParameters parGroup = + new ParticipantPolicyParameterHandler().getParameters(arguments); + activator = new ParticipantPolicyActivator(parGroup); + } + + /** + * Method for cleanup after each test. + * + * @throws Exception if an error occurs + */ + @AfterClass + public static void teardown() throws Exception { + // shut down activator + if (activator != null && activator.isAlive()) { + activator.shutdown(); + } + } + + @Test + public void testParticipantActivator() { + activator.start(); + assertTrue(activator.isAlive()); + assertTrue(activator.getParameters().isValid()); + assertEquals(CommonTestData.PARTICIPANT_GROUP_NAME, activator.getParameters().getName()); + + // repeat - should throw an exception + assertThatIllegalStateException().isThrownBy(() -> activator.start()); + assertTrue(activator.isAlive()); + assertTrue(activator.getParameters().isValid()); + + activator.shutdown(); + assertFalse(activator.isAlive()); + + // repeat - should throw an exception + assertThatIllegalStateException().isThrownBy(() -> activator.shutdown()); + assertFalse(activator.isAlive()); + } +} diff --git a/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/controlloop/participant/policy/main/utils/TestListenerUtils.java b/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/controlloop/participant/policy/main/utils/TestListenerUtils.java new file mode 100644 index 000000000..4f3d6d62c --- /dev/null +++ b/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/controlloop/participant/policy/main/utils/TestListenerUtils.java @@ -0,0 +1,343 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 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.clamp.controlloop.participant.policy.main.utils; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.FileNotFoundException; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import lombok.Getter; +import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoop; +import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopElement; +import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopOrderedState; +import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopState; +import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ParticipantState; +import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantControlLoopStateChange; +import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantControlLoopUpdate; +import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantHealthCheck; +import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantStateChange; +import org.onap.policy.clamp.controlloop.participant.intermediary.handler.ParticipantHandler; +import org.onap.policy.clamp.controlloop.participant.policy.main.handler.PolicyProvider; +import org.onap.policy.clamp.controlloop.participant.policy.main.parameters.CommonTestData; +import org.onap.policy.clamp.controlloop.participant.policy.main.parameters.ParticipantPolicyParameters; +import org.onap.policy.common.utils.coder.Coder; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.common.utils.coder.StandardCoder; +import org.onap.policy.common.utils.coder.YamlJsonTranslator; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; +import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate; +import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class TestListenerUtils { + + private static final YamlJsonTranslator yamlTranslator = new YamlJsonTranslator(); + private static final Coder CODER = new StandardCoder(); + static CommonTestData commonTestData = new CommonTestData(); + private static final Logger LOGGER = LoggerFactory.getLogger(TestListenerUtils.class); + + @Getter + private static ParticipantHandler participantHandler; + + private TestListenerUtils() {} + + /** + * Method to initialize participantHandler. + */ + public static void initParticipantHandler() { + + final ParticipantPolicyParameters participantParameters = commonTestData.toObject( + commonTestData.getParticipantPolicyParametersMap(CommonTestData.PARTICIPANT_GROUP_NAME), + ParticipantPolicyParameters.class); + + PolicyProvider policyProvider = + new PolicyProvider(participantParameters.getIntermediaryParameters()); + + participantHandler = policyProvider.getIntermediaryApi().getParticipantHandler(); + } + + /** + * Method to create a controlLoop from a yaml file. + * + * @return ControlLoop controlloop + */ + public static ControlLoop createControlLoop() { + ControlLoop controlLoop = new ControlLoop(); + Map<UUID, ControlLoopElement> elements = new LinkedHashMap<>(); + ToscaServiceTemplate toscaServiceTemplate = testControlLoopRead(); + Map<String, ToscaNodeTemplate> nodeTemplatesMap = + toscaServiceTemplate.getToscaTopologyTemplate().getNodeTemplates(); + for (Map.Entry<String, ToscaNodeTemplate> toscaInputEntry : nodeTemplatesMap.entrySet()) { + ControlLoopElement clElement = new ControlLoopElement(); + clElement.setId(UUID.randomUUID()); + + ToscaConceptIdentifier clElementParticipantId = new ToscaConceptIdentifier(); + clElementParticipantId.setName(toscaInputEntry.getKey()); + clElementParticipantId.setVersion(toscaInputEntry.getValue().getVersion()); + clElement.setParticipantId(clElementParticipantId); + + clElement.setDefinition(clElementParticipantId); + clElement.setState(ControlLoopState.UNINITIALISED); + clElement.setDescription(toscaInputEntry.getValue().getDescription()); + clElement.setOrderedState(ControlLoopOrderedState.UNINITIALISED); + elements.put(clElement.getId(), clElement); + } + controlLoop.setElements(elements); + controlLoop.setName("PMSHInstance0"); + controlLoop.setVersion("1.0.0"); + + ToscaConceptIdentifier definition = new ToscaConceptIdentifier(); + definition.setName("PMSHInstance0"); + definition.setVersion("1.0.0"); + controlLoop.setDefinition(definition); + + return controlLoop; + } + + /** + * Method to create ParticipantStateChange message from the arguments passed. + * + * @param participantState participant State + * + * @return ParticipantStateChange message + */ + public static ParticipantStateChange createParticipantStateChangeMsg(final ParticipantState participantState) { + final ParticipantStateChange participantStateChangeMsg = new ParticipantStateChange(); + ToscaConceptIdentifier participantId = new ToscaConceptIdentifier(); + participantId.setName("org.onap.PM_Policy"); + participantId.setVersion("0.0.0"); + + participantStateChangeMsg.setParticipantId(participantId); + participantStateChangeMsg.setTimestamp(Instant.now()); + participantStateChangeMsg.setState(participantState); + + return participantStateChangeMsg; + } + + /** + * Method to create ControlLoopStateChange message from the arguments passed. + * + * @param controlLoopOrderedState controlLoopOrderedState + * + * @return ParticipantControlLoopStateChange message + */ + public static ParticipantControlLoopStateChange createControlLoopStateChangeMsg( + final ControlLoopOrderedState controlLoopOrderedState) { + final ParticipantControlLoopStateChange participantClStateChangeMsg = new ParticipantControlLoopStateChange(); + + ToscaConceptIdentifier controlLoopId = new ToscaConceptIdentifier(); + controlLoopId.setName("PMSHInstance0"); + controlLoopId.setVersion("1.0.0"); + + ToscaConceptIdentifier participantId = new ToscaConceptIdentifier(); + participantId.setName("org.onap.PM_Policy"); + participantId.setVersion("0.0.0"); + + participantClStateChangeMsg.setControlLoopId(controlLoopId); + participantClStateChangeMsg.setParticipantId(participantId); + participantClStateChangeMsg.setTimestamp(Instant.now()); + participantClStateChangeMsg.setOrderedState(controlLoopOrderedState); + + return participantClStateChangeMsg; + } + + /** + * Method to create ControlLoopUpdateMsg. + * + * @return ParticipantControlLoopUpdate message + */ + public static ParticipantControlLoopUpdate createControlLoopUpdateMsg() { + final ParticipantControlLoopUpdate clUpdateMsg = new ParticipantControlLoopUpdate(); + ToscaConceptIdentifier controlLoopId = new ToscaConceptIdentifier(); + controlLoopId.setName("PMSHInstance0"); + controlLoopId.setVersion("1.0.0"); + + ToscaConceptIdentifier participantId = new ToscaConceptIdentifier(); + participantId.setName("org.onap.PM_Policy"); + participantId.setVersion("0.0.0"); + + clUpdateMsg.setControlLoopId(controlLoopId); + clUpdateMsg.setParticipantId(participantId); + + ControlLoop controlLoop = new ControlLoop(); + Map<UUID, ControlLoopElement> elements = new LinkedHashMap<>(); + ToscaServiceTemplate toscaServiceTemplate = testControlLoopRead(); + Map<String, ToscaNodeTemplate> nodeTemplatesMap = + toscaServiceTemplate.getToscaTopologyTemplate().getNodeTemplates(); + for (Map.Entry<String, ToscaNodeTemplate> toscaInputEntry : nodeTemplatesMap.entrySet()) { + ControlLoopElement clElement = new ControlLoopElement(); + clElement.setId(UUID.randomUUID()); + + ToscaConceptIdentifier clElementParticipantId = new ToscaConceptIdentifier(); + clElementParticipantId.setName(toscaInputEntry.getKey()); + clElementParticipantId.setVersion(toscaInputEntry.getValue().getVersion()); + clElement.setParticipantId(clElementParticipantId); + + clElement.setDefinition(clElementParticipantId); + clElement.setState(ControlLoopState.UNINITIALISED); + clElement.setDescription(toscaInputEntry.getValue().getDescription()); + clElement.setOrderedState(ControlLoopOrderedState.UNINITIALISED); + elements.put(clElement.getId(), clElement); + } + controlLoop.setElements(elements); + controlLoop.setName("PMSHInstance0"); + controlLoop.setVersion("1.0.0"); + controlLoop.setDefinition(controlLoopId); + clUpdateMsg.setControlLoop(controlLoop); + clUpdateMsg.setControlLoopDefinition(toscaServiceTemplate); + + return clUpdateMsg; + } + + /** + * Method to create ParticipantHealthCheck message. + * + * @return ParticipantHealthCheck message + */ + public static ParticipantHealthCheck createParticipantHealthCheckMsg() { + ToscaConceptIdentifier participantId = new ToscaConceptIdentifier(); + participantId.setName("org.onap.PM_Policy"); + participantId.setVersion("0.0.0"); + + ToscaConceptIdentifier controlLoopId = new ToscaConceptIdentifier(); + controlLoopId.setName("PMSHInstance0"); + controlLoopId.setVersion("1.0.0"); + + final ParticipantHealthCheck participantHealthCheckMsg = new ParticipantHealthCheck(); + participantHealthCheckMsg.setParticipantId(participantId); + participantHealthCheckMsg.setControlLoopId(controlLoopId); + participantHealthCheckMsg.setTimestamp(Instant.now()); + participantHealthCheckMsg.setState(ParticipantState.PASSIVE); + + return participantHealthCheckMsg; + } + + /** + * Method to create ParticipantControlLoopUpdate using the arguments passed. + * + * @param jsonFilePath the path of the controlloop content + * + * @return ParticipantControlLoopUpdate message + * @throws CoderException exception while reading the file to object + */ + public static ParticipantControlLoopUpdate createParticipantClUpdateMsgFromJson(String jsonFilePath) + throws CoderException { + ParticipantControlLoopUpdate participantControlLoopUpdateMsg = + CODER.decode(new File(jsonFilePath), ParticipantControlLoopUpdate.class); + return participantControlLoopUpdateMsg; + } + + private static ToscaServiceTemplate testControlLoopRead() { + Set<String> controlLoopDirectoryContents = + ResourceUtils.getDirectoryContents("src/test/resources/utils/servicetemplates"); + + boolean atLeastOneControlLoopTested = false; + ToscaServiceTemplate toscaServiceTemplate = null; + + for (String controlLoopFilePath : controlLoopDirectoryContents) { + if (!controlLoopFilePath.endsWith(".yaml")) { + continue; + } + atLeastOneControlLoopTested = true; + toscaServiceTemplate = testControlLoopYamlSerialization(controlLoopFilePath); + } + + // Add policy_types to the toscaServiceTemplate + addPolicyTypesToToscaServiceTemplate(toscaServiceTemplate); + + assertTrue(atLeastOneControlLoopTested); + return toscaServiceTemplate; + } + + private static void addPolicyTypesToToscaServiceTemplate( + ToscaServiceTemplate toscaServiceTemplate) { + Set<String> policyTypeDirectoryContents = ResourceUtils.getDirectoryContents("policytypes"); + + for (String policyTypeFilePath : policyTypeDirectoryContents) { + String policyTypeString = ResourceUtils.getResourceAsString(policyTypeFilePath); + + ToscaServiceTemplate foundPolicyTypeSt = + yamlTranslator.fromYaml(policyTypeString, ToscaServiceTemplate.class); + + toscaServiceTemplate.setDerivedFrom(foundPolicyTypeSt.getDerivedFrom()); + toscaServiceTemplate.setDescription(foundPolicyTypeSt.getDescription()); + toscaServiceTemplate.setMetadata(foundPolicyTypeSt.getMetadata()); + toscaServiceTemplate.setName(foundPolicyTypeSt.getName()); + toscaServiceTemplate.setToscaDefinitionsVersion(foundPolicyTypeSt.getToscaDefinitionsVersion()); + toscaServiceTemplate.setVersion(foundPolicyTypeSt.getVersion()); + + if (foundPolicyTypeSt.getDataTypes() != null) { + if (toscaServiceTemplate.getDataTypes() == null) { + toscaServiceTemplate.setDataTypes(foundPolicyTypeSt.getDataTypes()); + } else { + toscaServiceTemplate.getDataTypes().putAll(foundPolicyTypeSt.getDataTypes()); + } + } + + if (toscaServiceTemplate.getPolicyTypes() == null) { + toscaServiceTemplate.setPolicyTypes(foundPolicyTypeSt.getPolicyTypes()); + } else { + toscaServiceTemplate.getPolicyTypes().putAll(foundPolicyTypeSt.getPolicyTypes()); + } + } + } + + /** + * Method to add polcies to the toscaServiceTemplate. + * + * @param toscaServiceTemplate to add policies + */ + public static void addPoliciesToToscaServiceTemplate(ToscaServiceTemplate toscaServiceTemplate) { + Set<String> policiesDirectoryContents = ResourceUtils.getDirectoryContents("policies"); + + for (String policiesFilePath : policiesDirectoryContents) { + String policiesString = ResourceUtils.getResourceAsString(policiesFilePath); + + ToscaServiceTemplate foundPoliciesSt = + yamlTranslator.fromYaml(policiesString, ToscaServiceTemplate.class); + toscaServiceTemplate.getToscaTopologyTemplate().setPolicies( + foundPoliciesSt.getToscaTopologyTemplate().getPolicies()); + } + } + + private static ToscaServiceTemplate testControlLoopYamlSerialization(String controlLoopFilePath) { + try { + String controlLoopString = ResourceUtils.getResourceAsString(controlLoopFilePath); + if (controlLoopString == null) { + throw new FileNotFoundException(controlLoopFilePath); + } + + ToscaServiceTemplate serviceTemplate = yamlTranslator.fromYaml( + controlLoopString, ToscaServiceTemplate.class); + return serviceTemplate; + } catch (FileNotFoundException e) { + LOGGER.error("cannot find YAML file", controlLoopFilePath); + throw new IllegalArgumentException(e); + } + } +} |