diff options
Diffstat (limited to 'participant')
11 files changed, 564 insertions, 61 deletions
diff --git a/participant/participant-impl/participant-impl-acelement/src/test/java/org/onap/policy/clamp/acm/element/handler/MessageHandlerTest.java b/participant/participant-impl/participant-impl-acelement/src/test/java/org/onap/policy/clamp/acm/element/handler/MessageHandlerTest.java index 37d378b7a..dd651decc 100644 --- a/participant/participant-impl/participant-impl-acelement/src/test/java/org/onap/policy/clamp/acm/element/handler/MessageHandlerTest.java +++ b/participant/participant-impl/participant-impl-acelement/src/test/java/org/onap/policy/clamp/acm/element/handler/MessageHandlerTest.java @@ -21,6 +21,7 @@ package org.onap.policy.clamp.acm.element.handler; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -29,6 +30,7 @@ import java.util.List; import org.junit.jupiter.api.Test; import org.onap.policy.clamp.acm.element.main.parameters.AcElement; import org.onap.policy.clamp.acm.element.service.ElementService; +import org.onap.policy.clamp.common.acm.exception.AutomationCompositionRuntimeException; import org.onap.policy.clamp.models.acm.messages.dmaap.element.ElementStatus; import org.onap.policy.clamp.models.acm.messages.rest.element.ElementConfig; import org.onap.policy.clamp.models.acm.messages.rest.element.ElementType; @@ -38,6 +40,7 @@ class MessageHandlerTest { private static final String NAME = "name"; private static final String VERSION = "1.0.0"; + private static final String TOPIC = "topic"; @Test void testAppliesTo() { @@ -49,6 +52,30 @@ class MessageHandlerTest { } @Test + void testWrongConf() { + var starter = createMockElementService(ElementType.STARTER); + var bridge = createMockElementService(ElementType.BRIDGE); + var messageHandler = createMessageHandler(List.of(starter, bridge)); + + assertThatThrownBy(() -> messageHandler.getActiveService()) + .isInstanceOf(AutomationCompositionRuntimeException.class); + + var elementConfig = new ElementConfig(); + elementConfig.setElementType(ElementType.STARTER); + + assertThatThrownBy(() -> messageHandler.update(elementConfig)) + .isInstanceOf(AutomationCompositionRuntimeException.class); + + messageHandler.active(elementConfig); + + var newElementConfig = new ElementConfig(); + newElementConfig.setElementType(ElementType.BRIDGE); + + assertThatThrownBy(() -> messageHandler.update(newElementConfig)) + .isInstanceOf(AutomationCompositionRuntimeException.class); + } + + @Test void testStarter() { var starter = createMockElementService(ElementType.STARTER); var bridge = createMockElementService(ElementType.BRIDGE); @@ -81,7 +108,9 @@ class MessageHandlerTest { verify(bridge).update(elementConfig); var message = new ElementStatus(); - messageHandler.handleMessage(message); + message.setElementId(new ToscaConceptIdentifier(NAME, VERSION)); + var listener = new MessageListener(messageHandler); + listener.onTopicEvent(null, TOPIC, null, message); verify(bridge).handleMessage(message); messageHandler.deactivateElement(); } @@ -100,7 +129,9 @@ class MessageHandlerTest { assertThat(messageHandler.getActiveService()).isEqualTo(sink); var message = new ElementStatus(); - messageHandler.handleMessage(message); + message.setElementId(new ToscaConceptIdentifier(NAME, VERSION)); + var listener = new MessageListener(messageHandler); + listener.onTopicEvent(null, TOPIC, null, message); verify(sink).handleMessage(message); messageHandler.deactivateElement(); } diff --git a/participant/participant-impl/participant-impl-acelement/src/test/java/org/onap/policy/clamp/acm/element/service/BridgeServiceTest.java b/participant/participant-impl/participant-impl-acelement/src/test/java/org/onap/policy/clamp/acm/element/service/BridgeServiceTest.java index aae8d5893..0180cbba9 100644 --- a/participant/participant-impl/participant-impl-acelement/src/test/java/org/onap/policy/clamp/acm/element/service/BridgeServiceTest.java +++ b/participant/participant-impl/participant-impl-acelement/src/test/java/org/onap/policy/clamp/acm/element/service/BridgeServiceTest.java @@ -21,6 +21,7 @@ package org.onap.policy.clamp.acm.element.service; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -28,6 +29,7 @@ import static org.mockito.Mockito.verify; import org.junit.jupiter.api.Test; import org.onap.policy.clamp.acm.element.handler.MessagePublisher; import org.onap.policy.clamp.acm.element.main.parameters.AcElement; +import org.onap.policy.clamp.common.acm.exception.AutomationCompositionRuntimeException; import org.onap.policy.clamp.models.acm.messages.dmaap.element.ElementMessage; import org.onap.policy.clamp.models.acm.messages.dmaap.element.ElementStatus; import org.onap.policy.clamp.models.acm.messages.rest.element.ElementConfig; @@ -53,4 +55,16 @@ class BridgeServiceTest { bridgeService.handleMessage(new ElementStatus()); verify(messagePublisher).publishMsg(any(ElementMessage.class)); } + + @Test + void testWrongConf() { + var acElement = new AcElement(); + acElement.setElementId(new ToscaConceptIdentifier("onap.policy.clamp.ac.element1", "1.0.0")); + + var messagePublisher = new MessagePublisher(); + var bridgeService = new BridgeService(messagePublisher, acElement); + var elementStatus = new ElementStatus(); + assertThatThrownBy(() -> bridgeService.handleMessage(elementStatus)) + .isInstanceOf(AutomationCompositionRuntimeException.class); + } } diff --git a/participant/participant-impl/participant-impl-acelement/src/test/java/org/onap/policy/clamp/acm/element/service/StarterServiceTest.java b/participant/participant-impl/participant-impl-acelement/src/test/java/org/onap/policy/clamp/acm/element/service/StarterServiceTest.java index 28af70de7..97d808830 100644 --- a/participant/participant-impl/participant-impl-acelement/src/test/java/org/onap/policy/clamp/acm/element/service/StarterServiceTest.java +++ b/participant/participant-impl/participant-impl-acelement/src/test/java/org/onap/policy/clamp/acm/element/service/StarterServiceTest.java @@ -21,6 +21,7 @@ package org.onap.policy.clamp.acm.element.service; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.timeout; @@ -32,6 +33,7 @@ import org.onap.policy.clamp.acm.element.main.parameters.AcElement; import org.onap.policy.clamp.models.acm.messages.dmaap.element.ElementMessage; import org.onap.policy.clamp.models.acm.messages.rest.element.ElementConfig; import org.onap.policy.clamp.models.acm.messages.rest.element.ElementType; +import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; class StarterServiceTest { @@ -49,10 +51,15 @@ class StarterServiceTest { var elementConfig = new ElementConfig(); elementConfig.setTimerMs(100); elementConfig.setReceiverId(new ToscaConceptIdentifier("onap.policy.clamp.ac.element2", "1.0.0")); + + assertThatThrownBy(() -> starterService.update(elementConfig)).isInstanceOf(PfModelRuntimeException.class); + starterService.active(elementConfig); - verify(messagePublisher, timeout(200).atLeastOnce()).publishMsg(any(ElementMessage.class)); + verify(messagePublisher, timeout(500).atLeastOnce()).publishMsg(any(ElementMessage.class)); + + assertThatThrownBy(() -> starterService.active(elementConfig)).isInstanceOf(PfModelRuntimeException.class); + starterService.deactivate(); } } - } diff --git a/participant/participant-impl/participant-impl-http/src/test/java/org/onap/policy/clamp/acm/participant/http/utils/MockRestEndpoint.java b/participant/participant-impl/participant-impl-http/src/test/java/org/onap/policy/clamp/acm/participant/http/utils/MockRestEndpoint.java new file mode 100644 index 000000000..037e62986 --- /dev/null +++ b/participant/participant-impl/participant-impl-http/src/test/java/org/onap/policy/clamp/acm/participant/http/utils/MockRestEndpoint.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2022 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.acm.participant.http.utils; + +import java.util.List; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; + +/** + * The Class MockRestEndpoint creates rest server endpoints for simulating Rest calls. + */ +@Path("/") +@Produces("application/json") +public class MockRestEndpoint { + + /** + * Get dummy endpoint. + * + * @param name the name + * @param version the version + * @return the response + */ + @Path("get") + @GET + public Response getMessages(@QueryParam("name") String name, @QueryParam("version") String version) { + String createRequest = "dummy body"; + return Response.status(200).entity(List.of(createRequest)).build(); + } + + /** + * Post dummy endpoint. + * + * @param name the name + * @param version the version + * @param jsonString the message + * @return the response + */ + @Path("post") + @POST + public Response policyMessage(@QueryParam("name") String name, @QueryParam("version") String version, + final String jsonString) { + return Response.status(200).build(); + } +} diff --git a/participant/participant-impl/participant-impl-http/src/test/java/org/onap/policy/clamp/acm/participant/http/utils/MockServerRest.java b/participant/participant-impl/participant-impl-http/src/test/java/org/onap/policy/clamp/acm/participant/http/utils/MockServerRest.java new file mode 100644 index 000000000..1ac52124a --- /dev/null +++ b/participant/participant-impl/participant-impl-http/src/test/java/org/onap/policy/clamp/acm/participant/http/utils/MockServerRest.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2022 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.acm.participant.http.utils; + +import org.onap.policy.common.endpoints.http.server.HttpServletServer; +import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance; +import org.onap.policy.common.gson.GsonMessageBodyHandler; +import org.onap.policy.common.utils.network.NetworkUtil; + +/** + * The Class MockServerRest that manages test servers for REST requests for the test. + */ +public class MockServerRest implements AutoCloseable { + private static final String HOST = "localhost"; + private HttpServletServer restServer; + private int restServerPort = 0; + + /** + * Instantiates a new REST simulator. + */ + public MockServerRest(int restServerPort) { + this.restServerPort = restServerPort; + restServer = HttpServletServerFactoryInstance.getServerFactory().build("MockRestEndpoint", false, HOST, + restServerPort, "/", false, false); + restServer.addServletClass(null, MockRestEndpoint.class.getName()); + restServer.setSerializationProvider(GsonMessageBodyHandler.class.getName()); + restServer.start(); + } + + /** + * Validate the Rest server. + * @throws InterruptedException if is not alive + */ + public void validate() throws InterruptedException { + if (!NetworkUtil.isTcpPortOpen(HOST, restServerPort, 50, 200L)) { + throw new IllegalStateException("port " + restServerPort + " is still not in use"); + } + } + + @Override + public void close() throws Exception { + if (restServer != null) { + restServer.stop(); + restServer = null; + } + } +} diff --git a/participant/participant-impl/participant-impl-http/src/test/java/org/onap/policy/clamp/acm/participant/http/webclient/AcHttpClientTest.java b/participant/participant-impl/participant-impl-http/src/test/java/org/onap/policy/clamp/acm/participant/http/webclient/AcHttpClientTest.java index e0a04a12a..3ddd7b17c 100644 --- a/participant/participant-impl/participant-impl-http/src/test/java/org/onap/policy/clamp/acm/participant/http/webclient/AcHttpClientTest.java +++ b/participant/participant-impl/participant-impl-http/src/test/java/org/onap/policy/clamp/acm/participant/http/webclient/AcHttpClientTest.java @@ -22,26 +22,20 @@ package org.onap.policy.clamp.acm.participant.http.webclient; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.mockserver.model.HttpRequest.request; -import static org.mockserver.model.HttpResponse.response; import java.io.IOException; -import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import javax.ws.rs.core.MediaType; import org.apache.commons.lang3.tuple.Pair; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockserver.integration.ClientAndServer; -import org.mockserver.model.Parameter; import org.onap.policy.clamp.acm.participant.http.main.models.ConfigRequest; -import org.onap.policy.clamp.acm.participant.http.main.models.ConfigurationEntity; import org.onap.policy.clamp.acm.participant.http.main.webclient.AcHttpClient; import org.onap.policy.clamp.acm.participant.http.utils.CommonTestData; +import org.onap.policy.clamp.acm.participant.http.utils.MockServerRest; import org.onap.policy.common.utils.network.NetworkUtil; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; import org.springframework.test.context.junit.jupiter.SpringExtension; @@ -55,75 +49,57 @@ class AcHttpClientTest { private final String testMockUrl = "http://localhost"; - private static ClientAndServer mockServer; + private static MockServerRest mockServer; /** * Set up Mock server. */ @BeforeAll - static void setUpMockServer() throws IOException { + static void setUpMockServer() throws IOException, InterruptedException { mockServerPort = NetworkUtil.allocPort(); - mockServer = ClientAndServer.startClientAndServer(mockServerPort); + mockServer = new MockServerRest(mockServerPort); + mockServer.validate(); commonTestData = new CommonTestData(); - List<Parameter> queryParams = new ArrayList<>(); - commonTestData.getQueryParams().forEach((k, v) -> queryParams.add(new Parameter(k, v))); - - mockServer.when(request().withMethod("GET").withPath("/get") - .withHeader("Content-type", MediaType.APPLICATION_JSON) - .withHeader("Accept", MediaType.APPLICATION_JSON).withQueryStringParameters(queryParams)) - .respond(response().withBody("dummy body").withStatusCode(200) - .withHeader("Content-Type", MediaType.APPLICATION_JSON)); - - mockServer.when(request().withMethod("POST").withPath("/post") - .withHeader("Content-type", MediaType.APPLICATION_JSON) - .withHeader("Accept", MediaType.APPLICATION_JSON).withQueryStringParameters(queryParams) - .withBody("Test body")) - .respond(response().withStatusCode(200)); } @AfterAll - public static void stopServer() { - mockServer.stop(); + public static void stopServer() throws Exception { + mockServer.close(); mockServer = null; } - @Test void test_validRequest() { - //Add valid rest requests POST, GET - ConfigurationEntity configurationEntity = commonTestData.getConfigurationEntity(); + // Add valid rest requests POST, GET + var configurationEntity = commonTestData.getConfigurationEntity(); Map<ToscaConceptIdentifier, Pair<Integer, String>> responseMap = new HashMap<>(); - Map<String, String> headers = commonTestData.getHeaders(); - ConfigRequest configRequest = new ConfigRequest(testMockUrl + ":" + mockServerPort, headers, - List.of(configurationEntity), 10); + var headers = commonTestData.getHeaders(); + var configRequest = + new ConfigRequest(testMockUrl + ":" + mockServerPort, headers, List.of(configurationEntity), 10); - AcHttpClient client = new AcHttpClient(configRequest, responseMap); + var client = new AcHttpClient(configRequest, responseMap); assertDoesNotThrow(client::run); - assertThat(responseMap).hasSize(2).containsKey(commonTestData - .restParamsWithGet().getRestRequestId()); + assertThat(responseMap).hasSize(2).containsKey(commonTestData.restParamsWithGet().getRestRequestId()); - Pair<Integer, String> restResponseMap = responseMap.get(commonTestData - .restParamsWithGet().getRestRequestId()); + var restResponseMap = responseMap.get(commonTestData.restParamsWithGet().getRestRequestId()); assertThat(restResponseMap.getKey()).isEqualTo(200); } @Test void test_invalidRequest() { - //Add rest requests Invalid POST, Valid GET - ConfigurationEntity configurationEntity = commonTestData.getInvalidConfigurationEntity(); + // Add rest requests Invalid POST, Valid GET + var configurationEntity = commonTestData.getInvalidConfigurationEntity(); Map<ToscaConceptIdentifier, Pair<Integer, String>> responseMap = new HashMap<>(); - Map<String, String> headers = commonTestData.getHeaders(); - ConfigRequest configRequest = new ConfigRequest(testMockUrl + ":" + mockServerPort, headers, - List.of(configurationEntity), 10); + var headers = commonTestData.getHeaders(); + var configRequest = + new ConfigRequest(testMockUrl + ":" + mockServerPort, headers, List.of(configurationEntity), 10); - AcHttpClient client = new AcHttpClient(configRequest, responseMap); + var client = new AcHttpClient(configRequest, responseMap); assertDoesNotThrow(client::run); - assertThat(responseMap).hasSize(2).containsKey(commonTestData - .restParamsWithGet().getRestRequestId()); - Pair<Integer, String> response = responseMap - .get(commonTestData.restParamsWithInvalidPost().getRestRequestId()); + assertThat(responseMap).hasSize(2).containsKey(commonTestData.restParamsWithGet().getRestRequestId()); + var response = responseMap.get(commonTestData.restParamsWithInvalidPost().getRestRequestId()); assertThat(response.getKey()).isEqualTo(404); } } diff --git a/participant/participant-impl/participant-impl-policy/src/main/java/org/onap/policy/clamp/acm/participant/policy/main/handler/AutomationCompositionElementHandler.java b/participant/participant-impl/participant-impl-policy/src/main/java/org/onap/policy/clamp/acm/participant/policy/main/handler/AutomationCompositionElementHandler.java index e020d209e..e3679229d 100644 --- a/participant/participant-impl/participant-impl-policy/src/main/java/org/onap/policy/clamp/acm/participant/policy/main/handler/AutomationCompositionElementHandler.java +++ b/participant/participant-impl/participant-impl-policy/src/main/java/org/onap/policy/clamp/acm/participant/policy/main/handler/AutomationCompositionElementHandler.java @@ -175,9 +175,9 @@ public class AutomationCompositionElementHandler implements AutomationCompositio } /** - * Callback method to handle an update on a automation composition element. + * Callback method to handle an update on automation composition element. * - * @param element the information on the automation composition element + * @param element the information on the automation composition element * @param acElementDefinition toscaNodeTemplate * @throws PfModelException in case of an exception */ diff --git a/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/acm/participant/policy/client/HttpClientTest.java b/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/acm/participant/policy/client/HttpClientTest.java new file mode 100644 index 000000000..9f1343e67 --- /dev/null +++ b/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/acm/participant/policy/client/HttpClientTest.java @@ -0,0 +1,134 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2022 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.acm.participant.policy.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.IOException; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.onap.policy.clamp.acm.participant.policy.main.parameters.ParticipantPolicyParameters; +import org.onap.policy.clamp.acm.participant.policy.main.utils.MockServer; +import org.onap.policy.clamp.common.acm.exception.AutomationCompositionRuntimeException; +import org.onap.policy.common.endpoints.parameters.RestClientParameters; +import org.onap.policy.common.utils.network.NetworkUtil; +import org.onap.policy.models.pdp.concepts.DeploymentSubGroup; +import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; + +/** + * Tests for api and pap http clients. + */ +public class HttpClientTest { + + private static int mockServerPort; + + private static PolicyApiHttpClient apiHttpClient; + + private static PolicyPapHttpClient papHttpClient; + + private static MockServer mockServer; + + /** + * Set up Mock server. + */ + @BeforeAll + static void setUpMockServer() throws IOException, InterruptedException { + mockServerPort = NetworkUtil.allocPort(); + mockServer = new MockServer(mockServerPort); + mockServer.validate(); + // Setup mock api and pap client + ParticipantPolicyParameters params = new ParticipantPolicyParameters(); + RestClientParameters restClientParameters = getMockClientParameters(mockServerPort); + params.setPolicyApiParameters(restClientParameters); + params.setPolicyPapParameters(restClientParameters); + + apiHttpClient = new PolicyApiHttpClient(params); + papHttpClient = new PolicyPapHttpClient(params); + } + + + @Test + void testCreatePolicy() { + assertDoesNotThrow(() -> apiHttpClient.createPolicy(getTestToscaServiceTemplate())); + } + + @Test + void testCreatePolicyTypes() { + assertDoesNotThrow(() -> apiHttpClient.createPolicyType(getTestToscaServiceTemplate())); + } + + @Test + void testDeletePolicy() { + assertDoesNotThrow(() -> apiHttpClient.deletePolicy("dummyPolicy", "1.0.0")); + } + + @Test + void testDeletePolicyType() { + assertDoesNotThrow(() -> apiHttpClient.deletePolicyType("dummyPolicy", "1.0.0")); + } + + @Test + void testDeployPolicy() { + assertDoesNotThrow(() -> papHttpClient.handlePolicyDeployOrUndeploy("dummyPolicy", "1.0.0", + DeploymentSubGroup.Action.POST)); + } + + @Test + void testUnDeployPolicy() { + assertDoesNotThrow(() -> papHttpClient.handlePolicyDeployOrUndeploy("dummyPolicy", "1.0.0", + DeploymentSubGroup.Action.DELETE)); + } + + @Test + void testInvalidEndpoint() { + Response response = apiHttpClient.executePost("/invalid", Entity.entity(getTestToscaServiceTemplate(), + MediaType.APPLICATION_JSON)); + assertThat(response.getStatus()).isEqualTo(404); + } + + @Test + void testInvalidClientParameter() { + assertThrows(AutomationCompositionRuntimeException.class, + () -> new PolicyApiHttpClient(new ParticipantPolicyParameters())); + } + + + private ToscaServiceTemplate getTestToscaServiceTemplate() { + return new ToscaServiceTemplate(); + } + + private static RestClientParameters getMockClientParameters(int port) { + RestClientParameters params = new RestClientParameters(); + params.setName("policyClient"); + params.setHostname("localhost"); + params.setPort(port); + params.setUseHttps(false); + return params; + } + + + +} diff --git a/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/acm/participant/policy/main/handler/AutomationCompositionElementHandlerTest.java b/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/acm/participant/policy/main/handler/AutomationCompositionElementHandlerTest.java index 6b2ddf7e3..454864fd7 100644 --- a/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/acm/participant/policy/main/handler/AutomationCompositionElementHandlerTest.java +++ b/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/acm/participant/policy/main/handler/AutomationCompositionElementHandlerTest.java @@ -21,9 +21,14 @@ package org.onap.policy.clamp.acm.participant.policy.main.handler; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; +import java.util.List; +import java.util.Map; import java.util.UUID; +import javax.ws.rs.core.Response; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.onap.policy.clamp.acm.participant.intermediary.api.ParticipantIntermediaryApi; @@ -32,9 +37,14 @@ import org.onap.policy.clamp.acm.participant.policy.client.PolicyPapHttpClient; import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionElement; import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionOrderedState; import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionState; +import org.onap.policy.models.base.PfModelException; 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.ToscaPolicy; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType; import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; +import org.onap.policy.models.tosca.authorative.concepts.ToscaTopologyTemplate; + class AutomationCompositionElementHandlerTest { @@ -44,6 +54,9 @@ class AutomationCompositionElementHandlerTest { private static final ToscaConceptIdentifier automationCompositionId = new ToscaConceptIdentifier(ID_NAME, ID_VERSION); + private PolicyApiHttpClient api = Mockito.mock(PolicyApiHttpClient.class); + private PolicyPapHttpClient pap = Mockito.mock(PolicyPapHttpClient.class); + @Test void testHandlerDoesNotThrowExceptions() { AutomationCompositionElementHandler handler = getTestingHandler(); @@ -65,19 +78,12 @@ class AutomationCompositionElementHandlerTest { automationCompositionElementId, AutomationCompositionState.PASSIVE, AutomationCompositionOrderedState.RUNNING)); - var element = getTestingAcElement(); - var acElementDefinition = Mockito.mock(ToscaNodeTemplate.class); - - assertDoesNotThrow(() -> handler - .automationCompositionElementUpdate(automationCompositionId, element, acElementDefinition)); assertDoesNotThrow(() -> handler .handleStatistics(automationCompositionElementId)); } private AutomationCompositionElementHandler getTestingHandler() { - var api = Mockito.mock(PolicyApiHttpClient.class); - var pap = Mockito.mock(PolicyPapHttpClient.class); var handler = new AutomationCompositionElementHandler(api, pap); var intermediaryApi = Mockito.mock(ParticipantIntermediaryApi.class); var element = getTestingAcElement(); @@ -94,8 +100,43 @@ class AutomationCompositionElementHandlerTest { element.setOrderedState(AutomationCompositionOrderedState.UNINITIALISED); element.setParticipantId(automationCompositionId); element.setState(AutomationCompositionState.UNINITIALISED); - var template = Mockito.mock(ToscaServiceTemplate.class); + var template = new ToscaServiceTemplate(); + template.setToscaTopologyTemplate(new ToscaTopologyTemplate()); + template.getToscaTopologyTemplate().setPolicies(List.of(Map.of("DummyPolicy", new ToscaPolicy()))); + template.setPolicyTypes(Map.of("dummy policy type", new ToscaPolicyType())); element.setToscaServiceTemplateFragment(template); return element; } + + @Test + void testAcElementUpdate() throws PfModelException { + // Mock success scenario for policy creation and deployment + doReturn(Response.ok().build()).when(api).createPolicyType(any()); + doReturn(Response.ok().build()).when(api).createPolicy(any()); + doReturn(Response.accepted().build()).when(pap).handlePolicyDeployOrUndeploy(any(), any(), any()); + + AutomationCompositionElementHandler handler = getTestingHandler(); + var element = getTestingAcElement(); + var acElementDefinition = Mockito.mock(ToscaNodeTemplate.class); + + assertDoesNotThrow(() -> handler + .automationCompositionElementUpdate(automationCompositionId, element, acElementDefinition)); + + assertDoesNotThrow(() -> handler + .automationCompositionElementStateChange(automationCompositionId, + automationCompositionElementId, + AutomationCompositionState.PASSIVE, + AutomationCompositionOrderedState.UNINITIALISED)); + + + //Mock failure in policy deployment + doReturn(Response.serverError().build()).when(pap).handlePolicyDeployOrUndeploy(any(), any(), any()); + assertDoesNotThrow(() -> handler + .automationCompositionElementUpdate(automationCompositionId, element, acElementDefinition)); + + // Mock failure in policy type creation + doReturn(Response.serverError().build()).when(api).createPolicyType(any()); + assertDoesNotThrow(() -> handler + .automationCompositionElementUpdate(automationCompositionId, element, acElementDefinition)); + } } diff --git a/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/acm/participant/policy/main/utils/MockRestEndpoint.java b/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/acm/participant/policy/main/utils/MockRestEndpoint.java new file mode 100644 index 000000000..9f56a29ca --- /dev/null +++ b/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/acm/participant/policy/main/utils/MockRestEndpoint.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2022 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.acm.participant.policy.main.utils; + +import io.swagger.annotations.ApiParam; +import javax.ws.rs.DELETE; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Response; +import org.onap.policy.models.pdp.concepts.DeploymentGroups; +import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; +import org.springframework.web.bind.annotation.RequestBody; + + +/** + * Mock rest endpoints for api and pap servers. + */ +@Path("/") +@Produces("application/json") +public class MockRestEndpoint { + + /** + * Dummy endpoint for create policy types. + * + * @param body tosca service template + * @return the response + */ + @Path("policy/api/v1/policytypes") + @POST + public Response createPolicyType( + @RequestBody @ApiParam(value = "Entity body", required = true) ToscaServiceTemplate body) { + return Response.status(200).build(); + } + + /** + * Dummy endpoint for create policies. + * + * @param body tosca service template + * @return the response + */ + @Path("policy/api/v1/policies") + @POST + public Response createPolicy( + @RequestBody @ApiParam(value = "Entity body ", required = true) ToscaServiceTemplate body) { + return Response.status(200).build(); + } + + /** + * Dummy endpoint for delete policy types. + * + * @return the response + */ + @Path("policy/api/v1/policytypes/{policyTypeId}/versions/{versionId}") + @DELETE + public Response deletePolicyType() { + return Response.status(200).build(); + } + + /** + * Dummy endpoint for delete policy. + * + * @return the response + */ + @Path("policy/api/v1/policies/{policyId}/versions/{versionId}") + @DELETE + public Response deletePolicy() { + return Response.status(200).build(); + } + + /** + * Dummy endpoint for deploy/undeploy policy in pap. + * + * @param body pdp deployment group + * @return the response + */ + @Path("policy/pap/v1/pdps/deployments/batch") + @POST + public Response handlePolicyDeployOrUndeploy( + @RequestBody @ApiParam(value = "Entity body", required = true) DeploymentGroups body) { + return Response.status(200).build(); + } + +} diff --git a/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/acm/participant/policy/main/utils/MockServer.java b/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/acm/participant/policy/main/utils/MockServer.java new file mode 100644 index 000000000..7894b66a6 --- /dev/null +++ b/participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/acm/participant/policy/main/utils/MockServer.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2022 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.acm.participant.policy.main.utils; + +import org.onap.policy.common.endpoints.http.server.HttpServletServer; +import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance; +import org.onap.policy.common.gson.GsonMessageBodyHandler; +import org.onap.policy.common.utils.network.NetworkUtil; + +/** + * Mock REST server for pap and api tests. + */ +public class MockServer implements AutoCloseable { + private static final String HOST = "localhost"; + private HttpServletServer restServer; + private int restServerPort = 0; + + /** + * Instantiates a new REST simulator. + */ + public MockServer(int restServerPort) { + this.restServerPort = restServerPort; + restServer = HttpServletServerFactoryInstance.getServerFactory().build("MockRestEndpoint", false, HOST, + restServerPort, "/", false, false); + restServer.addServletClass(null, MockRestEndpoint.class.getName()); + restServer.setSerializationProvider(GsonMessageBodyHandler.class.getName()); + restServer.start(); + } + + /** + * Validate the Rest server. + * @throws InterruptedException if is not alive + */ + public void validate() throws InterruptedException { + if (!NetworkUtil.isTcpPortOpen(HOST, restServerPort, 50, 200L)) { + throw new IllegalStateException("port " + restServerPort + " is still not in use"); + } + } + + @Override + public void close() throws Exception { + if (restServer != null) { + restServer.stop(); + restServer = null; + } + } + + +} |