Set sub request ID before start callback
[policy/models.git] / models-interactions / model-actors / actor.cds / src / test / java / org / onap / policy / controlloop / actor / cds / GrpcOperationTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2020 Bell Canada. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  * ============LICENSE_END=========================================================
17  */
18
19 package org.onap.policy.controlloop.actor.cds;
20
21 import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
22 import static org.junit.Assert.assertEquals;
23 import static org.junit.Assert.assertNotNull;
24 import static org.junit.Assert.assertTrue;
25 import static org.mockito.Matchers.any;
26 import static org.mockito.Matchers.eq;
27 import static org.mockito.Mockito.mock;
28 import static org.mockito.Mockito.verify;
29 import static org.mockito.Mockito.when;
30
31 import java.util.HashMap;
32 import java.util.Map;
33 import java.util.UUID;
34 import java.util.concurrent.CompletableFuture;
35 import java.util.concurrent.CountDownLatch;
36 import java.util.concurrent.ExecutionException;
37 import java.util.concurrent.TimeUnit;
38 import java.util.concurrent.TimeoutException;
39 import java.util.concurrent.atomic.AtomicBoolean;
40 import org.junit.Before;
41 import org.junit.Test;
42 import org.junit.runner.RunWith;
43 import org.mockito.Mock;
44 import org.mockito.runners.MockitoJUnitRunner;
45 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput;
46 import org.onap.policy.aai.AaiCqResponse;
47 import org.onap.policy.cds.client.CdsProcessorGrpcClient;
48 import org.onap.policy.cds.properties.CdsServerProperties;
49 import org.onap.policy.common.utils.time.PseudoExecutor;
50 import org.onap.policy.controlloop.VirtualControlLoopEvent;
51 import org.onap.policy.controlloop.actor.cds.constants.CdsActorConstants;
52 import org.onap.policy.controlloop.actorserviceprovider.ActorService;
53 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
54 import org.onap.policy.controlloop.actorserviceprovider.controlloop.ControlLoopEventContext;
55 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
56 import org.onap.policy.controlloop.policy.PolicyResult;
57
58 @RunWith(MockitoJUnitRunner.class)
59 public class GrpcOperationTest {
60
61     private static final String CDS_BLUEPRINT_NAME = "vfw-cds";
62     private static final String CDS_BLUEPRINT_VERSION = "1.0.0";
63     private static final UUID REQUEST_ID = UUID.randomUUID();
64
65     @Mock
66     private CdsProcessorGrpcClient cdsClient;
67     private CdsServerProperties cdsProps;
68     private VirtualControlLoopEvent onset;
69     private PseudoExecutor executor;
70     private GrpcOperation operation;
71
72     /**
73      * Sets up the fields.
74      */
75     @Before
76     public void setUp() throws Exception {
77
78         // Setup the CDS properties
79         cdsProps = new CdsServerProperties();
80         cdsProps.setHost("10.10.10.10");
81         cdsProps.setPort(2000);
82         cdsProps.setUsername("testUser");
83         cdsProps.setPassword("testPassword");
84         cdsProps.setTimeout(1);
85
86         // Setup cdsClient
87         when(cdsClient.sendRequest(any(ExecutionServiceInput.class))).thenReturn(mock(CountDownLatch.class));
88
89         // Setup onset event
90         onset = new VirtualControlLoopEvent();
91         onset.setRequestId(REQUEST_ID);
92
93         // Setup executor
94         executor = new PseudoExecutor();
95     }
96
97     @Test
98     public void testStartPreprocessorAsync() throws InterruptedException, ExecutionException, TimeoutException {
99
100         CompletableFuture<OperationOutcome> future2 = new CompletableFuture<>();
101         ControlLoopEventContext context = mock(ControlLoopEventContext.class);
102         when(context.obtain(eq(AaiCqResponse.CONTEXT_KEY), any())).thenReturn(future2);
103         when(context.getEvent()).thenReturn(onset);
104
105         AtomicBoolean guardStarted = new AtomicBoolean();
106
107         ControlLoopOperationParams params = ControlLoopOperationParams.builder().actor(CdsActorConstants.CDS_ACTOR)
108                         .operation(GrpcOperation.NAME).context(context).actorService(new ActorService())
109                         .targetEntity("entity").build();
110         GrpcConfig config = new GrpcConfig(executor, cdsProps);
111
112         operation = new GrpcOperation(params, config) {
113             @Override
114             protected CompletableFuture<OperationOutcome> startGuardAsync() {
115                 guardStarted.set(true);
116                 return future2;
117             }
118         };
119
120         CompletableFuture<OperationOutcome> future3 = operation.startPreprocessorAsync();
121         assertNotNull(future3);
122         assertTrue(guardStarted.get());
123         verify(context).obtain(eq(AaiCqResponse.CONTEXT_KEY), any());
124
125         future2.complete(params.makeOutcome());
126         assertTrue(executor.runAll(100));
127         assertEquals(PolicyResult.SUCCESS, future3.get(2, TimeUnit.SECONDS).getResult());
128         assertTrue(future3.isDone());
129     }
130
131     @Test
132     public void testStartOperationAsync() throws Exception {
133
134         ControlLoopEventContext context = new ControlLoopEventContext(onset);
135         verifyOperation(context);
136     }
137
138     @Test
139     public void testStartOperationAsyncWithAdditionalParams() throws Exception {
140
141         Map<String, String> additionalParams = new HashMap<>();
142         additionalParams.put("test", "additionalParams");
143         onset.setAdditionalEventParams(additionalParams);
144         ControlLoopEventContext context = new ControlLoopEventContext(onset);
145         verifyOperation(context);
146     }
147
148     @Test
149     public void testStartOperationAsyncError() throws Exception {
150
151         ControlLoopEventContext context = new ControlLoopEventContext(onset);
152         ControlLoopOperationParams params = ControlLoopOperationParams.builder().actor(CdsActorConstants.CDS_ACTOR)
153                         .operation(GrpcOperation.NAME).context(context).actorService(new ActorService())
154                         .targetEntity("entity").build();
155
156         GrpcConfig config = new GrpcConfig(executor, cdsProps);
157         operation = new GrpcOperation(params, config);
158         assertThatIllegalArgumentException().isThrownBy(() -> operation.startOperationAsync(1, params.makeOutcome()));
159     }
160
161     private void verifyOperation(ControlLoopEventContext context) {
162
163         Map<String, Object> payloadMap = Map.of(CdsActorConstants.KEY_CBA_NAME, CDS_BLUEPRINT_NAME,
164                         CdsActorConstants.KEY_CBA_VERSION, CDS_BLUEPRINT_VERSION, "data",
165                         "{\"mapInfo\":{\"key\":\"val\"},\"arrayInfo\":[\"one\",\"two\"],\"paramInfo\":\"val\"}");
166
167         ControlLoopOperationParams params = ControlLoopOperationParams.builder().actor(CdsActorConstants.CDS_ACTOR)
168                         .operation(GrpcOperation.NAME).context(context).actorService(new ActorService())
169                         .targetEntity("entity").payload(payloadMap).build();
170
171         GrpcConfig config = new GrpcConfig(executor, cdsProps);
172         operation = new GrpcOperation(params, config);
173         assertEquals(1000, operation.getTimeoutMs(null));
174         assertEquals(1000, operation.getTimeoutMs(0));
175         assertEquals(2000, operation.getTimeoutMs(2));
176         operation.generateSubRequestId(1);
177         CompletableFuture<OperationOutcome> future3 = operation.startOperationAsync(1, params.makeOutcome());
178         assertNotNull(future3);
179     }
180 }