Make Actors event-agnostic
[policy/models.git] / models-interactions / model-actors / actor.cds / src / test / java / org / onap / policy / controlloop / actor / cds / GrpcOperationTest.java
index fe8d428..da069d8 100644 (file)
 
 package org.onap.policy.controlloop.actor.cds;
 
+import static org.assertj.core.api.Assertions.assertThat;
 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.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
+import java.util.Collections;
 import java.util.HashMap;
+import java.util.List;
 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.Executor;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import java.util.concurrent.atomic.AtomicBoolean;
 import org.junit.AfterClass;
 import org.junit.Before;
 import org.junit.BeforeClass;
@@ -49,7 +46,6 @@ import org.onap.aai.domain.yang.GenericVnf;
 import org.onap.aai.domain.yang.ServiceInstance;
 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput;
 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput;
-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.coder.Coder;
@@ -57,16 +53,13 @@ import org.onap.policy.common.utils.coder.CoderException;
 import org.onap.policy.common.utils.coder.StandardCoder;
 import org.onap.policy.common.utils.coder.StandardCoderObject;
 import org.onap.policy.common.utils.time.PseudoExecutor;
-import org.onap.policy.controlloop.VirtualControlLoopEvent;
-import org.onap.policy.controlloop.actor.aai.AaiGetPnfOperation;
 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.OperationProperties;
+import org.onap.policy.controlloop.actorserviceprovider.OperationResult;
+import org.onap.policy.controlloop.actorserviceprovider.TargetType;
 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
-import org.onap.policy.controlloop.policy.PolicyResult;
-import org.onap.policy.controlloop.policy.Target;
-import org.onap.policy.controlloop.policy.TargetType;
 import org.onap.policy.simulators.CdsSimulator;
 import org.onap.policy.simulators.Util;
 
@@ -91,9 +84,10 @@ public class GrpcOperationTest {
     @Mock
     private CdsProcessorGrpcClient cdsClient;
     private CdsServerProperties cdsProps;
-    private VirtualControlLoopEvent onset;
     private PseudoExecutor executor;
-    private Target target;
+    private Map<String, String> targetEntityIds;
+    private ControlLoopOperationParams params;
+    private GrpcConfig config;
     private GrpcOperation operation;
 
     @BeforeClass
@@ -124,16 +118,15 @@ public class GrpcOperationTest {
         // 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();
 
-        target = new Target();
-        target.setType(TargetType.VM);
-        target.setResourceID(RESOURCE_ID);
+        targetEntityIds = new HashMap<>();
+        targetEntityIds.put(ControlLoopOperationParams.PARAMS_ENTITY_RESOURCEID, RESOURCE_ID);
+
+        params = ControlLoopOperationParams.builder().actor(CdsActorConstants.CDS_ACTOR).operation(GrpcOperation.NAME)
+                        .requestId(REQUEST_ID).actorService(new ActorService()).targetEntity(TARGET_ENTITY)
+                        .build();
     }
 
     /**
@@ -141,15 +134,12 @@ public class GrpcOperationTest {
      */
     @Test
     public void testSuccess() throws Exception {
-        ControlLoopEventContext context = new ControlLoopEventContext(onset);
-        loadCqData(context);
-
         Map<String, Object> payload = Map.of("artifact_name", "my_artifact", "artifact_version", "1.0");
 
-        final ControlLoopOperationParams params = ControlLoopOperationParams.builder()
-                        .actor(CdsActorConstants.CDS_ACTOR).operation("subscribe").context(context)
-                        .actorService(new ActorService()).targetEntity(TARGET_ENTITY).target(target).retry(0)
-                        .timeoutSec(5).executor(blockingExecutor).payload(payload).build();
+        params = ControlLoopOperationParams.builder().actor(CdsActorConstants.CDS_ACTOR).operation("subscribe")
+                        .requestId(REQUEST_ID).actorService(new ActorService()).targetEntity(TARGET_ENTITY)
+                        .retry(0).timeoutSec(5).executor(blockingExecutor).payload(payload)
+                        .preprocessed(true).build();
 
         cdsProps.setHost("localhost");
         cdsProps.setPort(sim.getPort());
@@ -157,99 +147,65 @@ public class GrpcOperationTest {
 
         GrpcConfig config = new GrpcConfig(blockingExecutor, cdsProps);
 
-        operation = new GrpcOperation(params, config) {
-            @Override
-            protected CompletableFuture<OperationOutcome> startGuardAsync() {
-                // indicate that guard completed successfully
-                return CompletableFuture.completedFuture(params.makeOutcome());
-            }
-        };
+        operation = new GrpcOperation(params, config);
+
+        // set the properties
+        operation.setProperty(OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES, Collections.emptyMap());
 
         OperationOutcome outcome = operation.start().get();
-        assertEquals(PolicyResult.SUCCESS, outcome.getResult());
+        assertEquals(OperationResult.SUCCESS, outcome.getResult());
         assertTrue(outcome.getResponse() instanceof ExecutionServiceOutput);
     }
 
     @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);
+    public void testGetPropertyNames() {
 
-        AtomicBoolean guardStarted = new AtomicBoolean();
-
-        ControlLoopOperationParams params = ControlLoopOperationParams.builder().actor(CdsActorConstants.CDS_ACTOR)
-                        .operation(GrpcOperation.NAME).context(context).actorService(new ActorService())
-                        .targetEntity(TARGET_ENTITY).target(target).build();
-        GrpcConfig config = new GrpcConfig(executor, cdsProps);
-
-        operation = new GrpcOperation(params, config) {
-            @Override
-            protected CompletableFuture<OperationOutcome> startGuardAsync() {
-                guardStarted.set(true);
-                return future2;
-            }
-        };
+        /*
+         * check VNF case
+         */
+        operation = new GrpcOperation(params, config);
 
-        CompletableFuture<OperationOutcome> future3 = operation.startPreprocessorAsync();
-        assertNotNull(future3);
-        assertTrue(guardStarted.get());
-        verify(context).obtain(eq(AaiCqResponse.CONTEXT_KEY), any());
+        // @formatter:off
+        assertThat(operation.getPropertyNames()).isEqualTo(
+                        List.of(
+                            OperationProperties.AAI_RESOURCE_VNF,
+                            OperationProperties.AAI_SERVICE,
+                            OperationProperties.EVENT_ADDITIONAL_PARAMS,
+                            OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES));
+        // @formatter:on
+
+        /*
+         * check PNF case
+         */
+        params = params.toBuilder().targetType(TargetType.PNF).build();
+        operation = new GrpcOperation(params, config);
 
-        future2.complete(params.makeOutcome());
-        assertTrue(executor.runAll(100));
-        assertEquals(PolicyResult.SUCCESS, future3.get(2, TimeUnit.SECONDS).getResult());
-        assertTrue(future3.isDone());
+        // @formatter:off
+        assertThat(operation.getPropertyNames()).isEqualTo(
+                        List.of(
+                            OperationProperties.AAI_PNF,
+                            OperationProperties.EVENT_ADDITIONAL_PARAMS,
+                            OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES));
+        // @formatter:on
     }
 
-    /**
-     * Tests startPreprocessorAsync() when the target type is PNF.
-     */
     @Test
-    public void testStartPreprocessorAsyncPnf() 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();
-
-        target.setType(TargetType.PNF);
-
-        ControlLoopOperationParams params = ControlLoopOperationParams.builder().actor(CdsActorConstants.CDS_ACTOR)
-                        .operation(GrpcOperation.NAME).context(context).actorService(new ActorService())
-                        .targetEntity(TARGET_ENTITY).target(target).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(AaiGetPnfOperation.getKey(TARGET_ENTITY)), any());
+    public void testGetServiceInstanceId() {
+        operation = new GrpcOperation(params, config);
+        loadVnfData();
+        assertEquals(MY_SVC_ID, operation.getServiceInstanceId());
+    }
 
-        future2.complete(params.makeOutcome());
-        assertTrue(executor.runAll(100));
-        assertEquals(PolicyResult.SUCCESS, future3.get(2, TimeUnit.SECONDS).getResult());
-        assertTrue(future3.isDone());
+    @Test
+    public void testGetVnfId() {
+        operation = new GrpcOperation(params, config);
+        loadVnfData();
+        assertEquals(MY_VNF, operation.getVnfId());
     }
 
     @Test
     public void testStartOperationAsync() throws Exception {
-
-        ControlLoopEventContext context = new ControlLoopEventContext(onset);
-        loadCqData(context);
-
-        verifyOperation(context);
+        verifyOperation(TargetType.VNF, this::loadVnfData);
     }
 
     /**
@@ -257,48 +213,25 @@ public class GrpcOperationTest {
      */
     @Test
     public void testStartOperationAsyncPnf() throws Exception {
-
-        target.setType(TargetType.PNF);
-
-        ControlLoopEventContext context = new ControlLoopEventContext(onset);
-        loadPnfData(context);
-
-        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);
-        loadCqData(context);
-        verifyOperation(context);
+        verifyOperation(TargetType.PNF, this::loadPnfData);
     }
 
     @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(TARGET_ENTITY).target(target).build();
-
-        GrpcConfig config = new GrpcConfig(executor, cdsProps);
         operation = new GrpcOperation(params, config);
-        assertThatIllegalArgumentException().isThrownBy(() -> operation.startOperationAsync(1, params.makeOutcome()));
+        assertThatIllegalArgumentException()
+                        .isThrownBy(() -> operation.startOperationAsync(1, params.makeOutcome(null)));
     }
 
-    private void verifyOperation(ControlLoopEventContext context) {
+    private void verifyOperation(TargetType targetType, Runnable loader) {
 
         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(TARGET_ENTITY).target(target).payload(payloadMap).build();
+                        .operation(GrpcOperation.NAME).requestId(REQUEST_ID).actorService(new ActorService())
+                        .targetType(targetType).targetEntity(TARGET_ENTITY).payload(payloadMap).build();
 
         GrpcConfig config = new GrpcConfig(executor, cdsProps);
         operation = new GrpcOperation(params, config);
@@ -306,28 +239,31 @@ public class GrpcOperationTest {
         assertEquals(1000, operation.getTimeoutMs(0));
         assertEquals(2000, operation.getTimeoutMs(2));
         operation.generateSubRequestId(1);
-        CompletableFuture<OperationOutcome> future3 = operation.startOperationAsync(1, params.makeOutcome());
+
+        loader.run();
+        CompletableFuture<OperationOutcome> future3 = operation.startOperationAsync(1, params.makeOutcome(null));
         assertNotNull(future3);
     }
 
-    private void loadPnfData(ControlLoopEventContext context) throws CoderException {
-        String json = "{'dataA': 'valueA', 'dataB': 'valueB'}".replace('\'', '"');
-        StandardCoderObject sco = coder.decode(json, StandardCoderObject.class);
+    private void loadPnfData() {
+        try {
+            String json = "{'dataA': 'valueA', 'dataB': 'valueB'}".replace('\'', '"');
+            StandardCoderObject sco = coder.decode(json, StandardCoderObject.class);
+
+            operation.setProperty(OperationProperties.AAI_PNF, sco);
 
-        context.setProperty(AaiGetPnfOperation.getKey(TARGET_ENTITY), sco);
+        } catch (CoderException e) {
+            throw new IllegalArgumentException("cannot decode PNF json", e);
+        }
     }
 
-    private void loadCqData(ControlLoopEventContext context) {
+    private void loadVnfData() {
         GenericVnf genvnf = new GenericVnf();
         genvnf.setVnfId(MY_VNF);
+        operation.setProperty(OperationProperties.AAI_RESOURCE_VNF, genvnf);
 
         ServiceInstance serviceInstance = new ServiceInstance();
         serviceInstance.setServiceInstanceId(MY_SVC_ID);
-
-        AaiCqResponse cq = mock(AaiCqResponse.class);
-        when(cq.getGenericVnfByModelInvariantId(any())).thenReturn(genvnf);
-        when(cq.getServiceInstance()).thenReturn(serviceInstance);
-
-        context.setProperty(AaiCqResponse.CONTEXT_KEY, cq);
+        operation.setProperty(OperationProperties.AAI_SERVICE, serviceInstance);
     }
 }