Testcases for cds actor 42/102642/2
authorRam Krishna Verma <ram_krishna.verma@bell.ca>
Fri, 28 Feb 2020 22:53:54 +0000 (17:53 -0500)
committerRam Krishna Verma <ram_krishna.verma@bell.ca>
Mon, 2 Mar 2020 16:05:40 +0000 (11:05 -0500)
Adding test cases for cds actor, operator, operation & manager.
Coverage is more than 95% overall.
Fixed review comments.

Issue-ID: POLICY-2384
Change-Id: I64beeb0c46918b990ad7e67248559169fc7940a1
Signed-off-by: Ram Krishna Verma <ram_krishna.verma@bell.ca>
models-interactions/model-actors/actor.cds/src/main/java/org/onap/policy/controlloop/actor/cds/CdsActorServiceProvider.java
models-interactions/model-actors/actor.cds/src/test/java/org/onap/policy/controlloop/actor/cds/GrpcActorServiceManagerTest.java [new file with mode: 0644]
models-interactions/model-actors/actor.cds/src/test/java/org/onap/policy/controlloop/actor/cds/GrpcOperationTest.java [new file with mode: 0644]
models-interactions/model-actors/actor.cds/src/test/java/org/onap/policy/controlloop/actor/cds/GrpcOperatorTest.java [new file with mode: 0644]
models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/impl/BidirectionalTopicOperatorTest.java
models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/impl/HttpOperatorTest.java
models-interactions/model-impl/cds/src/main/java/org/onap/policy/cds/client/CdsProcessorHandler.java

index 91ee55d..0b0ae6b 100644 (file)
@@ -1,6 +1,6 @@
 /*-
  * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Bell Canada. All rights reserved.
+ * Copyright (C) 2019-2020 Bell Canada. All rights reserved.
  * Modifications Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
diff --git a/models-interactions/model-actors/actor.cds/src/test/java/org/onap/policy/controlloop/actor/cds/GrpcActorServiceManagerTest.java b/models-interactions/model-actors/actor.cds/src/test/java/org/onap/policy/controlloop/actor/cds/GrpcActorServiceManagerTest.java
new file mode 100644 (file)
index 0000000..187b69e
--- /dev/null
@@ -0,0 +1,94 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2020 Bell Canada. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.controlloop.actor.cds;
+
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType;
+import org.onap.ccsdk.cds.controllerblueprints.common.api.Status;
+import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput;
+import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
+import org.onap.policy.controlloop.policy.PolicyResult;
+
+@RunWith(MockitoJUnitRunner.class)
+public class GrpcActorServiceManagerTest {
+
+    CdsActorServiceManager manager;
+    CompletableFuture<OperationOutcome> future;
+    ExecutionServiceOutput output;
+
+    /**
+     * Sets up the fields.
+     */
+    @Before
+    public void setUp() throws Exception {
+        future = new CompletableFuture<>();
+        manager = new CdsActorServiceManager(new OperationOutcome(), future);
+    }
+
+    @Test
+    public void testOnMessageSuccess() throws InterruptedException, ExecutionException, TimeoutException {
+
+        Status status = Status.newBuilder().setEventType(EventType.EVENT_COMPONENT_EXECUTED).build();
+        output = ExecutionServiceOutput.newBuilder().setStatus(status).build();
+        manager.onMessage(output);
+        assertEquals(PolicyResult.SUCCESS, future.get(2, TimeUnit.SECONDS).getResult());
+        assertTrue(future.isDone());
+    }
+
+    @Test
+    public void testOnMessageProcessing() throws InterruptedException, ExecutionException, TimeoutException {
+
+        Status status = Status.newBuilder().setEventType(EventType.EVENT_COMPONENT_PROCESSING).build();
+        output = ExecutionServiceOutput.newBuilder().setStatus(status).build();
+        manager.onMessage(output);
+        assertThatThrownBy(() -> future.get(200, TimeUnit.MILLISECONDS)).isInstanceOf(TimeoutException.class);
+        assertFalse(future.isDone());
+    }
+
+    @Test
+    public void testOnMessageFailure() throws InterruptedException, ExecutionException, TimeoutException {
+
+        Status status = Status.newBuilder().setEventType(EventType.EVENT_COMPONENT_FAILURE).build();
+        output = ExecutionServiceOutput.newBuilder().setStatus(status).build();
+        manager.onMessage(output);
+        assertEquals(PolicyResult.FAILURE, future.get(2, TimeUnit.SECONDS).getResult());
+        assertTrue(future.isDone());
+    }
+
+    @Test
+    public void testOnError() throws InterruptedException, ExecutionException, TimeoutException {
+
+        Exception exception = new Exception("something failed");
+        manager.onError(exception);
+        assertTrue(future.isCompletedExceptionally());
+        assertTrue(future.isDone());
+    }
+}
diff --git a/models-interactions/model-actors/actor.cds/src/test/java/org/onap/policy/controlloop/actor/cds/GrpcOperationTest.java b/models-interactions/model-actors/actor.cds/src/test/java/org/onap/policy/controlloop/actor/cds/GrpcOperationTest.java
new file mode 100644 (file)
index 0000000..81636b1
--- /dev/null
@@ -0,0 +1,179 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2020 Bell Canada. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.controlloop.actor.cds;
+
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput;
+import org.onap.policy.aai.AaiCqResponse;
+import org.onap.policy.cds.client.CdsProcessorGrpcClient;
+import org.onap.policy.cds.properties.CdsServerProperties;
+import org.onap.policy.common.utils.time.PseudoExecutor;
+import org.onap.policy.controlloop.VirtualControlLoopEvent;
+import org.onap.policy.controlloop.actor.cds.constants.CdsActorConstants;
+import org.onap.policy.controlloop.actorserviceprovider.ActorService;
+import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
+import org.onap.policy.controlloop.actorserviceprovider.controlloop.ControlLoopEventContext;
+import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
+import org.onap.policy.controlloop.policy.PolicyResult;
+
+@RunWith(MockitoJUnitRunner.class)
+public class GrpcOperationTest {
+
+    private static final String CDS_BLUEPRINT_NAME = "vfw-cds";
+    private static final String CDS_BLUEPRINT_VERSION = "1.0.0";
+    private static final UUID REQUEST_ID = UUID.randomUUID();
+
+    @Mock
+    private CdsProcessorGrpcClient cdsClient;
+    private CdsServerProperties cdsProps;
+    private VirtualControlLoopEvent onset;
+    private PseudoExecutor executor;
+    private GrpcOperation operation;
+
+    /**
+     * Sets up the fields.
+     */
+    @Before
+    public void setUp() throws Exception {
+
+        // Setup the CDS properties
+        cdsProps = new CdsServerProperties();
+        cdsProps.setHost("10.10.10.10");
+        cdsProps.setPort(2000);
+        cdsProps.setUsername("testUser");
+        cdsProps.setPassword("testPassword");
+        cdsProps.setTimeout(1);
+
+        // Setup cdsClient
+        when(cdsClient.sendRequest(any(ExecutionServiceInput.class))).thenReturn(mock(CountDownLatch.class));
+
+        // Setup onset event
+        onset = new VirtualControlLoopEvent();
+        onset.setRequestId(REQUEST_ID);
+
+        // Setup executor
+        executor = new PseudoExecutor();
+    }
+
+    @Test
+    public void testStartPreprocessorAsync() throws InterruptedException, ExecutionException, TimeoutException {
+
+        CompletableFuture<OperationOutcome> future2 = new CompletableFuture<>();
+        ControlLoopEventContext context = mock(ControlLoopEventContext.class);
+        when(context.obtain(eq(AaiCqResponse.CONTEXT_KEY), any())).thenReturn(future2);
+        when(context.getEvent()).thenReturn(onset);
+
+        AtomicBoolean guardStarted = new AtomicBoolean();
+
+        ControlLoopOperationParams params = ControlLoopOperationParams.builder().actor(CdsActorConstants.CDS_ACTOR)
+                        .operation(GrpcOperation.NAME).context(context).actorService(new ActorService())
+                        .targetEntity("entity").build();
+        GrpcConfig config = new GrpcConfig(executor, cdsProps);
+
+        operation = new GrpcOperation(params, config) {
+            @Override
+            protected CompletableFuture<OperationOutcome> startGuardAsync() {
+                guardStarted.set(true);
+                return future2;
+            }
+        };
+
+        CompletableFuture<OperationOutcome> future3 = operation.startPreprocessorAsync();
+        assertNotNull(future3);
+        assertTrue(guardStarted.get());
+        verify(context).obtain(eq(AaiCqResponse.CONTEXT_KEY), any());
+
+        future2.complete(params.makeOutcome());
+        assertTrue(executor.runAll(100));
+        assertEquals(PolicyResult.SUCCESS, future3.get(2, TimeUnit.SECONDS).getResult());
+        assertTrue(future3.isDone());
+    }
+
+    @Test
+    public void testStartOperationAsync() throws Exception {
+
+        ControlLoopEventContext context = new ControlLoopEventContext(onset);
+        verifyOperation(context);
+    }
+
+    @Test
+    public void testStartOperationAsyncWithAdditionalParams() throws Exception {
+
+        Map<String, String> additionalParams = new HashMap<>();
+        additionalParams.put("test", "additionalParams");
+        onset.setAdditionalEventParams(additionalParams);
+        ControlLoopEventContext context = new ControlLoopEventContext(onset);
+        verifyOperation(context);
+    }
+
+    @Test
+    public void testStartOperationAsyncError() throws Exception {
+
+        ControlLoopEventContext context = new ControlLoopEventContext(onset);
+        ControlLoopOperationParams params = ControlLoopOperationParams.builder().actor(CdsActorConstants.CDS_ACTOR)
+                        .operation(GrpcOperation.NAME).context(context).actorService(new ActorService())
+                        .targetEntity("entity").build();
+
+        GrpcConfig config = new GrpcConfig(executor, cdsProps);
+        operation = new GrpcOperation(params, config);
+        assertThatIllegalArgumentException().isThrownBy(() -> operation.startOperationAsync(1, params.makeOutcome()));
+    }
+
+    private void verifyOperation(ControlLoopEventContext context) {
+
+        Map<String, Object> payloadMap = Map.of(CdsActorConstants.KEY_CBA_NAME, CDS_BLUEPRINT_NAME,
+                        CdsActorConstants.KEY_CBA_VERSION, CDS_BLUEPRINT_VERSION, "data",
+                        "{\"mapInfo\":{\"key\":\"val\"},\"arrayInfo\":[\"one\",\"two\"],\"paramInfo\":\"val\"}");
+
+        ControlLoopOperationParams params = ControlLoopOperationParams.builder().actor(CdsActorConstants.CDS_ACTOR)
+                        .operation(GrpcOperation.NAME).context(context).actorService(new ActorService())
+                        .targetEntity("entity").payload(payloadMap).build();
+
+        GrpcConfig config = new GrpcConfig(executor, cdsProps);
+        operation = new GrpcOperation(params, config);
+        assertEquals(1000, operation.getTimeoutMs(null));
+        assertEquals(1000, operation.getTimeoutMs(0));
+        assertEquals(2000, operation.getTimeoutMs(2));
+        CompletableFuture<OperationOutcome> future3 = operation.startOperationAsync(1, params.makeOutcome());
+        assertNotNull(future3);
+    }
+}
diff --git a/models-interactions/model-actors/actor.cds/src/test/java/org/onap/policy/controlloop/actor/cds/GrpcOperatorTest.java b/models-interactions/model-actors/actor.cds/src/test/java/org/onap/policy/controlloop/actor/cds/GrpcOperatorTest.java
new file mode 100644 (file)
index 0000000..2fd54e4
--- /dev/null
@@ -0,0 +1,107 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2020 Bell Canada. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.controlloop.actor.cds;
+
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.Assert.assertEquals;
+
+import java.util.Map;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.MockitoAnnotations;
+import org.onap.policy.cds.properties.CdsServerProperties;
+import org.onap.policy.controlloop.VirtualControlLoopEvent;
+import org.onap.policy.controlloop.actor.cds.constants.CdsActorConstants;
+import org.onap.policy.controlloop.actorserviceprovider.Operation;
+import org.onap.policy.controlloop.actorserviceprovider.Util;
+import org.onap.policy.controlloop.actorserviceprovider.controlloop.ControlLoopEventContext;
+import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
+import org.onap.policy.controlloop.actorserviceprovider.parameters.ParameterValidationRuntimeException;
+
+public class GrpcOperatorTest {
+
+    GrpcOperator operation;
+    Map<String, Object> paramMap;
+    Map<String, Object> invalidParamMap;
+
+    /**
+     * Initializes fields, including {@link #operation}.
+     */
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+        operation = new GrpcOperator(CdsActorConstants.CDS_ACTOR, GrpcOperation.NAME, GrpcOperation::new);
+
+        CdsServerProperties props = new CdsServerProperties();
+        props.setHost("grpcHost");
+        props.setPort(1234);
+        props.setUsername("grpcUsername");
+        props.setPassword("grpcPassword");
+        props.setTimeout(30);
+
+        paramMap = Util.translateToMap(GrpcOperation.NAME, props);
+        props.setHost(null);
+        invalidParamMap = Util.translateToMap(GrpcOperation.NAME, props);
+    }
+
+    @Test
+    public void testGrpcOperator() {
+        assertEquals(CdsActorConstants.CDS_ACTOR, operation.getActorName());
+        assertEquals(GrpcOperation.NAME, operation.getName());
+        assertEquals(CdsActorConstants.CDS_ACTOR + "." + GrpcOperation.NAME, operation.getFullName());
+    }
+
+
+    @Test
+    public void testDoConfigure() {
+
+        operation.doConfigure(paramMap);
+        assertEquals(30000, operation.getCurrentConfig().getTimeoutMs());
+
+        // use invalidParamsMap
+        assertThatExceptionOfType(ParameterValidationRuntimeException.class)
+                        .isThrownBy(() -> operation.makeConfiguration(invalidParamMap));
+    }
+
+    @Test
+    public void testBuildOperation() {
+        VirtualControlLoopEvent event = new VirtualControlLoopEvent();
+        ControlLoopEventContext context = new ControlLoopEventContext(event);
+        ControlLoopOperationParams params = ControlLoopOperationParams.builder().actor(CdsActorConstants.CDS_ACTOR)
+                        .operation(GrpcOperation.NAME).context(context).build();
+
+        // not configured yet
+        assertThatIllegalStateException().isThrownBy(() -> operation.buildOperation(params));
+
+        operation.configure(paramMap);
+
+        // not running yet
+        assertThatIllegalStateException().isThrownBy(() -> operation.buildOperation(params));
+
+        operation.start();
+        Operation operation1 = operation.buildOperation(params);
+        assertEquals(GrpcOperation.NAME, operation1.getName());
+
+        // with no operation-maker
+        GrpcOperator oper2 = new GrpcOperator(CdsActorConstants.CDS_ACTOR, GrpcOperation.NAME);
+        assertThatThrownBy(() -> oper2.buildOperation(params)).isInstanceOf(UnsupportedOperationException.class);
+    }
+}
index ae923c0..b5e3de3 100644 (file)
@@ -125,13 +125,14 @@ public class BidirectionalTopicOperatorTest {
 
         ControlLoopOperationParams params2 = ControlLoopOperationParams.builder().build();
 
-        // not running yet
-        assertThatIllegalStateException().isThrownBy(() -> oper2.buildOperation(params2));
-
         // configure and start it
         params = BidirectionalTopicParams.builder().sourceTopic(MY_SOURCE).sinkTopic(MY_SINK).timeoutSec(TIMEOUT_SEC)
                         .build();
         oper2.configure(Util.translateToMap(OPERATION, params));
+
+        // not running yet
+        assertThatIllegalStateException().isThrownBy(() -> oper2.buildOperation(params2));
+
         oper2.start();
 
         assertSame(operation, oper2.buildOperation(params2));
index 873a306..f85ef30 100644 (file)
@@ -116,13 +116,14 @@ public class HttpOperatorTest {
         ControlLoopOperationParams params =
                         ControlLoopOperationParams.builder().actor(ACTOR).operation(OPERATION).context(context).build();
 
-        // not running yet
-        assertThatIllegalStateException().isThrownBy(() -> oper2.buildOperation(params));
-
         // configure and start it
         HttpParams params2 = HttpParams.builder().clientName(HTTP_CLIENT).path(PATH).timeoutSec(TIMEOUT).build();
         Map<String, Object> paramMap = Util.translateToMap(OPERATION, params2);
         oper2.configure(paramMap);
+
+        // not running yet
+        assertThatIllegalStateException().isThrownBy(() -> oper2.buildOperation(params));
+
         oper2.start();
 
         Operation operation1 = oper2.buildOperation(params);
index 9dd249c..5c011d8 100644 (file)
@@ -30,7 +30,7 @@ import org.onap.policy.cds.api.CdsProcessorListener;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-class CdsProcessorHandler {
+public class CdsProcessorHandler {
 
     private static final Logger LOGGER = LoggerFactory.getLogger(CdsProcessorHandler.class);