diff options
author | liamfallon <liam.fallon@est.tech> | 2021-05-26 11:02:07 +0100 |
---|---|---|
committer | liamfallon <liam.fallon@est.tech> | 2021-05-26 11:02:11 +0100 |
commit | 20c7487f77d0728d270b2bed34c2c798d17cc12d (patch) | |
tree | bb20d003255fab584ac64968967fbc6e1f205232 /participant/participant-impl/participant-impl-dcae/src/test/java | |
parent | f83411a86e2277adae69e780e8511913d61a0f17 (diff) |
Transfer tosca-poc onto master
This is the third if three commits, this commit makes the content of
the master branch the same as the tosca-poc branch.
This commit adds the "src" files for TOSCA control loops to the modules
in master.
Difference between this commit and the current master:
------------------------------------------------------
diff -qr clamp clamp-master |diff_filter.sh
Only in clamp/common: src
Only in clamp/models: src
Files clamp/participant/participant-impl/participant-impl-dcae/pom.xml and clamp-master/participant/participant-impl/participant-impl-dcae/pom.xml differ
Only in clamp/participant/participant-impl/participant-impl-dcae: src
Only in clamp/participant/participant-impl/participant-impl-policy: src
Only in clamp/participant/participant-impl/participant-impl-simulator: src
Files clamp/participant/participant-impl/pom.xml and clamp-master/participant/participant-impl/pom.xml differ
Only in clamp/participant/participant-intermediary: src
Files clamp/participant/pom.xml and clamp-master/participant/pom.xml differ
Files clamp/pom.xml and clamp-master/pom.xml differ
Files clamp/runtime/pom.xml and clamp-master/runtime/pom.xml differ
Only in clamp: runtime-controlloop
Difference between this commit and the current tosca-poc branch:
----------------------------------------------------------------
diff -qr clamp clamp-tp |diff_filter.sh
Files clamp/INFO.yaml and clamp-tp/INFO.yaml differ
Only in clamp/releases: 6.0.1-container.yaml
Only in clamp/releases: 6.0.1.yaml
Only in clamp/releases: 6.0.2-container.yaml
Only in clamp/releases: 6.0.2.yaml
Only in clamp/releases: 6.1.0-container.yaml
Only in clamp/releases: 6.1.0.yaml
Only in clamp/releases: 6.1.1-container.yaml
Only in clamp/releases: 6.1.1.yaml
Files clamp/runtime/src/main/resources/META-INF/resources/swagger.html and clamp-tp/runtime/src/main/resources/META-INF/resources/swagger.html differ
Issue-ID: POLICY-3215
Change-Id: Ica1aa3fe5d6110df2396ea856703102e800fa770
Signed-off-by: liamfallon <liam.fallon@est.tech>
Diffstat (limited to 'participant/participant-impl/participant-impl-dcae/src/test/java')
7 files changed, 1114 insertions, 0 deletions
diff --git a/participant/participant-impl/participant-impl-dcae/src/test/java/org/onap/policy/clamp/controlloop/participant/dcae/httpclient/ClampHttpClientTest.java b/participant/participant-impl/participant-impl-dcae/src/test/java/org/onap/policy/clamp/controlloop/participant/dcae/httpclient/ClampHttpClientTest.java new file mode 100644 index 000000000..040b33f5e --- /dev/null +++ b/participant/participant-impl/participant-impl-dcae/src/test/java/org/onap/policy/clamp/controlloop/participant/dcae/httpclient/ClampHttpClientTest.java @@ -0,0 +1,128 @@ +/*- + * ============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.dcae.httpclient; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.junit.Assert.assertTrue; +import static org.mockserver.model.HttpRequest.request; +import static org.mockserver.model.HttpResponse.response; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockserver.integration.ClientAndServer; +import org.onap.policy.clamp.controlloop.participant.dcae.main.parameters.CommonTestData; +import org.onap.policy.clamp.controlloop.participant.dcae.main.parameters.ParticipantDcaeParameters; +import org.onap.policy.clamp.controlloop.participant.dcae.model.Loop; +import org.onap.policy.common.utils.coder.Coder; +import org.onap.policy.common.utils.coder.StandardCoder; + +/** + * Class to perform unit test of {@link ClampHttpClient}. + * + */ +public class ClampHttpClientTest { + + private static final String LOOP = "pmsh_loop"; + private static final String BLUEPRINT_DEPLOYED = "BLUEPRINT_DEPLOYED"; + + private static ClientAndServer mockServer; + private static ParticipantDcaeParameters parameters; + public static final Coder CODER = new StandardCoder(); + + /** + * Set up. + */ + @BeforeClass + public static void setUp() { + CommonTestData commonTestData = new CommonTestData(); + + parameters = commonTestData.toObject( + commonTestData.getParticipantParameterGroupMap(CommonTestData.PARTICIPANT_GROUP_NAME), + ParticipantDcaeParameters.class); + + mockServer = ClientAndServer.startClientAndServer(parameters.getClampClientParameters().getPort()); + + mockServer.when(request().withMethod("GET").withPath("/restservices/clds/v2/loop/getstatus/" + LOOP)) + .respond(response().withBody(CommonTestData.createJsonStatus(BLUEPRINT_DEPLOYED)).withStatusCode(200)); + + mockServer.when(request().withMethod("PUT").withPath("/restservices/clds/v2/loop/deploy/" + LOOP)) + .respond(response().withStatusCode(202)); + + mockServer.when(request().withMethod("PUT").withPath("/restservices/clds/v2/loop/undeploy/" + LOOP)) + .respond(response().withStatusCode(202)); + } + + @AfterClass + public static void stopServer() { + mockServer.stop(); + mockServer = null; + } + + @Test + public void test_getstatus() throws Exception { + try (ClampHttpClient client = new ClampHttpClient(parameters.getClampClientParameters())) { + + Loop status = client.getstatus(LOOP); + + String json = CommonTestData.createJsonStatus(BLUEPRINT_DEPLOYED); + Loop loop = CODER.convert(json, Loop.class); + + assertThat(ClampHttpClient.getStatusCode(status)).isEqualTo(ClampHttpClient.getStatusCode(loop)); + + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void test_deploy() throws Exception { + try (ClampHttpClient client = new ClampHttpClient(parameters.getClampClientParameters())) { + + assertTrue(client.deploy(LOOP)); + + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void test_undeploy() throws Exception { + try (ClampHttpClient client = new ClampHttpClient(parameters.getClampClientParameters())) { + + assertTrue(client.undeploy(LOOP)); + + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void test_getStatusCodeNull() { + assertThat(ClampHttpClient.getStatusCode(null)).isEqualTo(ClampHttpClient.STATUS_NOT_FOUND); + } + + @Test + public void test_getStatusEmptyMap() { + assertThat(ClampHttpClient.getStatusCode(new Loop())).isEqualTo(ClampHttpClient.STATUS_NOT_FOUND); + } +} diff --git a/participant/participant-impl/participant-impl-dcae/src/test/java/org/onap/policy/clamp/controlloop/participant/dcae/main/parameters/CommonTestData.java b/participant/participant-impl/participant-impl-dcae/src/test/java/org/onap/policy/clamp/controlloop/participant/dcae/main/parameters/CommonTestData.java new file mode 100644 index 000000000..bcfaf8bb9 --- /dev/null +++ b/participant/participant-impl/participant-impl-dcae/src/test/java/org/onap/policy/clamp/controlloop/participant/dcae/main/parameters/CommonTestData.java @@ -0,0 +1,294 @@ +/*- + * ============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.dcae.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()); + private static final String REST_CLIENT_PASSWORD = "password"; + private static final String REST_CLIENT_USER = "admin"; + private static final int REST_CLAMP_PORT = 8443; + private static final int REST_CONSUL_PORT = 31321; + private static final String REST_CLAMP_HOST = "localhost"; + private static final String REST_CONSUL_HOST = "consul"; + private static final boolean REST_CLAMP_HTTPS = false; + private static final boolean REST_CONSUL_HTTPS = false; + private static final boolean REST_CLIENT_AAF = false; + + 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 ApexStarterParameterGroup map for test cases. + * + * @param name name of the parameters + * + * @return a property map suitable for constructing an object + */ + public Map<String, Object> getParticipantParameterGroupMap(final String name) { + final Map<String, Object> map = new TreeMap<>(); + + map.put("name", name); + map.put("clampClientParameters", getClampClientParametersMap(false)); + map.put("consulClientParameters", getConsulClientParametersMap(false)); + map.put("intermediaryParameters", getIntermediaryParametersMap(false)); + map.put("databaseProviderParameters", getDatabaseProviderParametersMap(false)); + return map; + } + + /** + * Returns a property map for a RestServerParameters 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> getClampClientParametersMap(final boolean isEmpty) { + final Map<String, Object> map = new TreeMap<>(); + map.put("https", REST_CLAMP_HTTPS); + map.put("aaf", REST_CLIENT_AAF); + + if (!isEmpty) { + map.put("host", REST_CLAMP_HOST); + map.put("port", REST_CLAMP_PORT); + map.put("userName", REST_CLIENT_USER); + map.put("password", REST_CLIENT_PASSWORD); + } + + return map; + } + + /** + * Returns a property map for a RestServerParameters 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> getConsulClientParametersMap(final boolean isEmpty) { + final Map<String, Object> map = new TreeMap<>(); + map.put("https", REST_CONSUL_HTTPS); + map.put("aaf", REST_CLIENT_AAF); + + if (!isEmpty) { + map.put("host", REST_CONSUL_HOST); + map.put("port", REST_CONSUL_PORT); + map.put("userName", REST_CLIENT_USER); + map.put("password", REST_CLIENT_PASSWORD); + } + + 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(); + participantId.setName("CDSParticipant0"); + participantId.setVersion("1.0.0"); + return participantId; + } + + /** + * Gets the standard participant parameters. + * + * @param port port to be inserted into the parameters + * @return the standard participant parameters + */ + public ParticipantDcaeParameters getParticipantParameterGroup(int port) { + try { + return coder.decode(getParticipantParameterGroupAsString(port), ParticipantDcaeParameters.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 getParticipantParameterGroupAsString(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() { + return "src/test/resources/parameters/TestParametersStd.json"; + } + + /** + * 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\""); + } + + /** + * create Json response from getstatus call. + * + * @param status the status of Partecipant + * @return the JSON + */ + public static String createJsonStatus(String status) { + try { + File file = new File("src/test/resources/rest/status.json"); + String json = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); + return json.replace("${status}", status); + + } catch (IOException e) { + throw new ControlLoopRuntimeException(Response.Status.NOT_ACCEPTABLE, "cannot read json file", e); + } + } +} diff --git a/participant/participant-impl/participant-impl-dcae/src/test/java/org/onap/policy/clamp/controlloop/participant/dcae/main/parameters/TestParticipantDcaeParameterHandler.java b/participant/participant-impl/participant-impl-dcae/src/test/java/org/onap/policy/clamp/controlloop/participant/dcae/main/parameters/TestParticipantDcaeParameterHandler.java new file mode 100644 index 000000000..058a3dae4 --- /dev/null +++ b/participant/participant-impl/participant-impl-dcae/src/test/java/org/onap/policy/clamp/controlloop/participant/dcae/main/parameters/TestParticipantDcaeParameterHandler.java @@ -0,0 +1,102 @@ +/*- + * ============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.dcae.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.junit.Test; +import org.onap.policy.clamp.controlloop.common.exception.ControlLoopException; +import org.onap.policy.clamp.controlloop.participant.dcae.main.parameters.ParticipantDcaeParameterHandler; +import org.onap.policy.clamp.controlloop.participant.dcae.main.parameters.ParticipantDcaeParameters; +import org.onap.policy.clamp.controlloop.participant.dcae.main.startstop.ParticipantDcaeCommandLineArguments; +import org.onap.policy.common.utils.coder.CoderException; + +/** + * Class to perform unit test of {@link ParticipantParameterHandler}. + * + */ +public class TestParticipantDcaeParameterHandler { + + @Test + public void testParameterHandlerNoParameterFile() throws ControlLoopException { + final String[] emptyArgumentString = { "-c", "src/test/resources/parameters/NoParametersFile.json" }; + + final ParticipantDcaeCommandLineArguments emptyArguments = new ParticipantDcaeCommandLineArguments(); + emptyArguments.parse(emptyArgumentString); + + assertThatThrownBy(() -> new ParticipantDcaeParameterHandler().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 ParticipantDcaeCommandLineArguments invalidArguments = + new ParticipantDcaeCommandLineArguments(); + invalidArguments.parse(invalidArgumentString); + + assertThatThrownBy(() -> new ParticipantDcaeParameterHandler().getParameters(invalidArguments)) + .hasMessageStartingWith("error reading parameters from") + .hasCauseInstanceOf(CoderException.class); + } + + @Test + public void testParticipantParameterGroup() throws ControlLoopException { + final String[] participantConfigParameters = { "-c", "src/test/resources/parameters/TestParameters.json" }; + + final ParticipantDcaeCommandLineArguments arguments = new ParticipantDcaeCommandLineArguments(); + arguments.parse(participantConfigParameters); + + final ParticipantDcaeParameters parGroup = new ParticipantDcaeParameterHandler() + .getParameters(arguments); + assertTrue(arguments.checkSetConfigurationFilePath()); + assertEquals(CommonTestData.PARTICIPANT_GROUP_NAME, parGroup.getName()); + } + + @Test + public void testParticipantVersion() throws ControlLoopException { + final String[] participantConfigParameters = { "-v" }; + final ParticipantDcaeCommandLineArguments arguments = new ParticipantDcaeCommandLineArguments(); + assertThat(arguments.parse(participantConfigParameters)).startsWith( + "ONAP Tosca defined control loop Participant"); + } + + @Test + public void testParticipantHelp() throws ControlLoopException { + final String[] participantConfigParameters = { "-h" }; + final ParticipantDcaeCommandLineArguments arguments = new ParticipantDcaeCommandLineArguments(); + assertThat(arguments.parse(participantConfigParameters)).startsWith("usage:"); + } + + @Test + public void testParticipantInvalidOption() throws ControlLoopException { + final String[] participantConfigParameters = { "-d" }; + final ParticipantDcaeCommandLineArguments arguments = new ParticipantDcaeCommandLineArguments(); + assertThatThrownBy(() -> arguments.parse(participantConfigParameters)) + .hasMessageStartingWith("invalid command line arguments specified"); + } +} diff --git a/participant/participant-impl/participant-impl-dcae/src/test/java/org/onap/policy/clamp/controlloop/participant/dcae/main/parameters/TestParticipantDcaeParameters.java b/participant/participant-impl/participant-impl-dcae/src/test/java/org/onap/policy/clamp/controlloop/participant/dcae/main/parameters/TestParticipantDcaeParameters.java new file mode 100644 index 000000000..edb429322 --- /dev/null +++ b/participant/participant-impl/participant-impl-dcae/src/test/java/org/onap/policy/clamp/controlloop/participant/dcae/main/parameters/TestParticipantDcaeParameters.java @@ -0,0 +1,90 @@ +/*- + * ============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.dcae.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 static org.junit.Assert.assertTrue; + +import java.util.Map; +import org.junit.Test; +import org.onap.policy.clamp.controlloop.participant.intermediary.parameters.ParticipantIntermediaryParameters; +import org.onap.policy.common.endpoints.parameters.TopicParameterGroup; +import org.onap.policy.common.parameters.ValidationResult; + +/** + * Class to perform unit test of {@link ParticipantParameterGroup}. + * + */ +public class TestParticipantDcaeParameters { + CommonTestData commonTestData = new CommonTestData(); + + @Test + public void testParticipantParameterGroup_Named() { + final ParticipantDcaeParameters participantParameters = new ParticipantDcaeParameters("my-name"); + assertEquals("my-name", participantParameters.getName()); + } + + @Test + public void testParticipantParameterGroup() { + final ParticipantDcaeParameters participantParameters = commonTestData.toObject( + commonTestData.getParticipantParameterGroupMap(CommonTestData.PARTICIPANT_GROUP_NAME), + ParticipantDcaeParameters.class); + final ParticipantIntermediaryParameters participantIntermediaryParameters = participantParameters + .getIntermediaryParameters(); + final TopicParameterGroup topicParameterGroup = participantParameters.getIntermediaryParameters() + .getClampControlLoopTopics(); + final ValidationResult validationResult = participantParameters.validate(); + assertTrue(validationResult.isValid()); + assertEquals(CommonTestData.PARTICIPANT_GROUP_NAME, participantParameters.getName()); + assertEquals(CommonTestData.TIME_INTERVAL, participantIntermediaryParameters.getReportingTimeInterval()); + assertEquals(CommonTestData.DESCRIPTION, participantIntermediaryParameters.getDescription()); + assertEquals(CommonTestData.TOPIC_PARAMS, topicParameterGroup.getTopicSinks()); + assertEquals(CommonTestData.TOPIC_PARAMS, topicParameterGroup.getTopicSources()); + } + + @Test + public void testParticipantParameterGroup_EmptyParticipantIntermediaryParameters() { + final Map<String, Object> map = + commonTestData.getParticipantParameterGroupMap(CommonTestData.PARTICIPANT_GROUP_NAME); + map.replace("intermediaryParameters", commonTestData.getIntermediaryParametersMap(true)); + final ParticipantDcaeParameters participantParameters = + commonTestData.toObject(map, ParticipantDcaeParameters.class); + final ValidationResult validationResult = participantParameters.validate(); + assertNull(validationResult.getResult()); + } + + @Test + public void testParticipantParameterGroup_EmptyTopicParameters() { + final Map<String, Object> map = + commonTestData.getParticipantParameterGroupMap(CommonTestData.PARTICIPANT_GROUP_NAME); + final Map<String, Object> intermediaryParametersMap = commonTestData.getIntermediaryParametersMap(false); + intermediaryParametersMap.put("clampControlLoopTopics", commonTestData.getTopicParametersMap(true)); + map.replace("intermediaryParameters", intermediaryParametersMap); + + final ParticipantDcaeParameters participantParameters = + commonTestData.toObject(map, ParticipantDcaeParameters.class); + final ValidationResult validationResult = participantParameters.validate(); + assertNull(validationResult.getResult()); + } +} diff --git a/participant/participant-impl/participant-impl-dcae/src/test/java/org/onap/policy/clamp/controlloop/participant/dcae/main/rest/TestListenerUtils.java b/participant/participant-impl/participant-impl-dcae/src/test/java/org/onap/policy/clamp/controlloop/participant/dcae/main/rest/TestListenerUtils.java new file mode 100644 index 000000000..c3cc8b755 --- /dev/null +++ b/participant/participant-impl/participant-impl-dcae/src/test/java/org/onap/policy/clamp/controlloop/participant/dcae/main/rest/TestListenerUtils.java @@ -0,0 +1,255 @@ +/*- + * ============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.dcae.main.rest; + +import java.io.File; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.Map; +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.dcae.main.handler.DcaeProvider; +import org.onap.policy.clamp.controlloop.participant.dcae.main.parameters.CommonTestData; +import org.onap.policy.clamp.controlloop.participant.dcae.main.parameters.ParticipantDcaeParameters; +import org.onap.policy.clamp.controlloop.participant.intermediary.handler.ParticipantHandler; +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; + +public class TestListenerUtils { + + private static final YamlJsonTranslator yamlTranslator = new YamlJsonTranslator(); + private static final Coder CODER = new StandardCoder(); + private static final String TOSCA_TEMPLATE_YAML = "examples/controlloop/PMSubscriptionHandling.yaml"; + static CommonTestData commonTestData = new CommonTestData(); + + @Getter + private static ParticipantHandler participantHandler; + + /** + * Method to initialize participantHandler. + */ + public static void initParticipantHandler() { + + final ParticipantDcaeParameters parameters = commonTestData.toObject( + commonTestData.getParticipantParameterGroupMap(CommonTestData.PARTICIPANT_GROUP_NAME), + ParticipantDcaeParameters.class); + + DcaeProvider dcaeProvider = new DcaeProvider(parameters); + + participantHandler = dcaeProvider.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("CDSParticipant0"); + participantId.setVersion("1.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("CDSParticipant0"); + participantId.setVersion("1.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("CDSParticipant0"); + participantId.setVersion("1.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("CDSParticipant0"); + participantId.setVersion("1.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() { + return testControlLoopYamlSerialization(TOSCA_TEMPLATE_YAML); + } + + private static ToscaServiceTemplate testControlLoopYamlSerialization(String controlLoopFilePath) { + String controlLoopString = ResourceUtils.getResourceAsString(controlLoopFilePath); + ToscaServiceTemplate serviceTemplate = yamlTranslator.fromYaml(controlLoopString, ToscaServiceTemplate.class); + return serviceTemplate; + } +} diff --git a/participant/participant-impl/participant-impl-dcae/src/test/java/org/onap/policy/clamp/controlloop/participant/dcae/main/startstop/TestMain.java b/participant/participant-impl/participant-impl-dcae/src/test/java/org/onap/policy/clamp/controlloop/participant/dcae/main/startstop/TestMain.java new file mode 100644 index 000000000..f779f3a57 --- /dev/null +++ b/participant/participant-impl/participant-impl-dcae/src/test/java/org/onap/policy/clamp/controlloop/participant/dcae/main/startstop/TestMain.java @@ -0,0 +1,151 @@ +/*- + * ============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.dcae.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.clamp.controlloop.participant.dcae.main.startstop.Main; +import org.onap.policy.clamp.controlloop.participant.dcae.main.startstop.ParticipantDcaeActivator; +import org.onap.policy.common.utils.resources.MessageConstants; +import org.onap.policy.common.utils.services.Registry; + +/** + * Class to perform unit test of {@link Main}}. + */ +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 ParticipantDcaeActivator activator = + Registry.getOrDefault(ControlLoopConstants.REG_CLRUNTIME_ACTIVATOR, + ParticipantDcaeActivator.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()); + + // ensure items were added to the registry + assertNotNull(Registry.get(ControlLoopConstants.REG_CLRUNTIME_ACTIVATOR, ParticipantDcaeActivator.class)); + + 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-dcae/src/test/java/org/onap/policy/clamp/controlloop/participant/dcae/main/startstop/TestParticipantDcaeActivator.java b/participant/participant-impl/participant-impl-dcae/src/test/java/org/onap/policy/clamp/controlloop/participant/dcae/main/startstop/TestParticipantDcaeActivator.java new file mode 100644 index 000000000..1903868e2 --- /dev/null +++ b/participant/participant-impl/participant-impl-dcae/src/test/java/org/onap/policy/clamp/controlloop/participant/dcae/main/startstop/TestParticipantDcaeActivator.java @@ -0,0 +1,94 @@ +/*- + * ============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.dcae.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.dcae.main.parameters.CommonTestData; +import org.onap.policy.clamp.controlloop.participant.dcae.main.parameters.ParticipantDcaeParameterHandler; +import org.onap.policy.clamp.controlloop.participant.dcae.main.parameters.ParticipantDcaeParameters; +import org.onap.policy.clamp.controlloop.participant.dcae.main.startstop.ParticipantDcaeActivator; +import org.onap.policy.clamp.controlloop.participant.dcae.main.startstop.ParticipantDcaeCommandLineArguments; +import org.onap.policy.common.utils.services.Registry; + +/** + * Class to perform unit test of {@link ParticipantDcaeActivator}}. + * + */ +public class TestParticipantDcaeActivator { + + private static ParticipantDcaeActivator 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 ParticipantDcaeCommandLineArguments arguments = + new ParticipantDcaeCommandLineArguments(participantConfigParameters); + final ParticipantDcaeParameters parGroup = + new ParticipantDcaeParameterHandler().getParameters(arguments); + activator = new ParticipantDcaeActivator(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()); + } +} |