Improve code coverage on policy-participant module in clamp 23/131223/1
authorrameshiyer27 <ramesh.murugan.iyer@est.tech>
Tue, 27 Sep 2022 06:40:02 +0000 (07:40 +0100)
committerrameshiyer27 <ramesh.murugan.iyer@est.tech>
Tue, 27 Sep 2022 07:31:17 +0000 (08:31 +0100)
Added junits for handler and policy client classes which improves the
overall module covergae from 38.8% to 92%

Issue-ID: POLICY-4365
Signed-off-by: zrrmmua <ramesh.murugan.iyer@est.tech>
Change-Id: I0a860cff870b77a29a66f04645c64fdd8cf66313

participant/participant-impl/participant-impl-policy/src/main/java/org/onap/policy/clamp/acm/participant/policy/main/handler/AutomationCompositionElementHandler.java
participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/acm/participant/policy/client/HttpClientTest.java [new file with mode: 0644]
participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/acm/participant/policy/main/handler/AutomationCompositionElementHandlerTest.java
participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/acm/participant/policy/main/utils/MockRestEndpoint.java [new file with mode: 0644]
participant/participant-impl/participant-impl-policy/src/test/java/org/onap/policy/clamp/acm/participant/policy/main/utils/MockServer.java [new file with mode: 0644]

index e020d20..e367922 100644 (file)
@@ -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 (file)
index 0000000..9f1343e
--- /dev/null
@@ -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;
+    }
+
+
+
+}
index 6b2ddf7..454864f 100644 (file)
 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 (file)
index 0000000..9f56a29
--- /dev/null
@@ -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 (file)
index 0000000..7894b66
--- /dev/null
@@ -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;
+        }
+    }
+
+
+}