Make Actors event-agnostic
[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  * Modifications Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  * ============LICENSE_END=========================================================
18  */
19
20 package org.onap.policy.controlloop.actor.cds;
21
22 import static org.assertj.core.api.Assertions.assertThat;
23 import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertNotNull;
26 import static org.junit.Assert.assertTrue;
27 import static org.mockito.ArgumentMatchers.any;
28 import static org.mockito.Mockito.mock;
29 import static org.mockito.Mockito.when;
30
31 import java.util.Collections;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.UUID;
36 import java.util.concurrent.CompletableFuture;
37 import java.util.concurrent.CountDownLatch;
38 import java.util.concurrent.Executor;
39 import org.junit.AfterClass;
40 import org.junit.Before;
41 import org.junit.BeforeClass;
42 import org.junit.Test;
43 import org.mockito.Mock;
44 import org.mockito.MockitoAnnotations;
45 import org.onap.aai.domain.yang.GenericVnf;
46 import org.onap.aai.domain.yang.ServiceInstance;
47 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput;
48 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput;
49 import org.onap.policy.cds.client.CdsProcessorGrpcClient;
50 import org.onap.policy.cds.properties.CdsServerProperties;
51 import org.onap.policy.common.utils.coder.Coder;
52 import org.onap.policy.common.utils.coder.CoderException;
53 import org.onap.policy.common.utils.coder.StandardCoder;
54 import org.onap.policy.common.utils.coder.StandardCoderObject;
55 import org.onap.policy.common.utils.time.PseudoExecutor;
56 import org.onap.policy.controlloop.actor.cds.constants.CdsActorConstants;
57 import org.onap.policy.controlloop.actorserviceprovider.ActorService;
58 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
59 import org.onap.policy.controlloop.actorserviceprovider.OperationProperties;
60 import org.onap.policy.controlloop.actorserviceprovider.OperationResult;
61 import org.onap.policy.controlloop.actorserviceprovider.TargetType;
62 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
63 import org.onap.policy.simulators.CdsSimulator;
64 import org.onap.policy.simulators.Util;
65
66 public class GrpcOperationTest {
67     private static final String TARGET_ENTITY = "entity";
68     private static final String MY_VNF = "my-vnf";
69     private static final String MY_SVC_ID = "my-service-instance-id";
70     private static final String RESOURCE_ID = "my-resource-id";
71     private static final String CDS_BLUEPRINT_NAME = "vfw-cds";
72     private static final String CDS_BLUEPRINT_VERSION = "1.0.0";
73     private static final UUID REQUEST_ID = UUID.randomUUID();
74     private static final Coder coder = new StandardCoder();
75
76     protected static final Executor blockingExecutor = command -> {
77         Thread thread = new Thread(command);
78         thread.setDaemon(true);
79         thread.start();
80     };
81
82     private static CdsSimulator sim;
83
84     @Mock
85     private CdsProcessorGrpcClient cdsClient;
86     private CdsServerProperties cdsProps;
87     private PseudoExecutor executor;
88     private Map<String, String> targetEntityIds;
89     private ControlLoopOperationParams params;
90     private GrpcConfig config;
91     private GrpcOperation operation;
92
93     @BeforeClass
94     public static void setUpBeforeClass() throws Exception {
95         sim = Util.buildCdsSim();
96     }
97
98     @AfterClass
99     public static void tearDownAfterClass() {
100         sim.stop();
101     }
102
103     /**
104      * Sets up the fields.
105      */
106     @Before
107     public void setUp() throws Exception {
108         MockitoAnnotations.initMocks(this);
109
110         // Setup the CDS properties
111         cdsProps = new CdsServerProperties();
112         cdsProps.setHost("10.10.10.10");
113         cdsProps.setPort(2000);
114         cdsProps.setUsername("testUser");
115         cdsProps.setPassword("testPassword");
116         cdsProps.setTimeout(1);
117
118         // Setup cdsClient
119         when(cdsClient.sendRequest(any(ExecutionServiceInput.class))).thenReturn(mock(CountDownLatch.class));
120
121         // Setup executor
122         executor = new PseudoExecutor();
123
124         targetEntityIds = new HashMap<>();
125         targetEntityIds.put(ControlLoopOperationParams.PARAMS_ENTITY_RESOURCEID, RESOURCE_ID);
126
127         params = ControlLoopOperationParams.builder().actor(CdsActorConstants.CDS_ACTOR).operation(GrpcOperation.NAME)
128                         .requestId(REQUEST_ID).actorService(new ActorService()).targetEntity(TARGET_ENTITY)
129                         .build();
130     }
131
132     /**
133      * Tests "success" case with simulator.
134      */
135     @Test
136     public void testSuccess() throws Exception {
137         Map<String, Object> payload = Map.of("artifact_name", "my_artifact", "artifact_version", "1.0");
138
139         params = ControlLoopOperationParams.builder().actor(CdsActorConstants.CDS_ACTOR).operation("subscribe")
140                         .requestId(REQUEST_ID).actorService(new ActorService()).targetEntity(TARGET_ENTITY)
141                         .retry(0).timeoutSec(5).executor(blockingExecutor).payload(payload)
142                         .preprocessed(true).build();
143
144         cdsProps.setHost("localhost");
145         cdsProps.setPort(sim.getPort());
146         cdsProps.setTimeout(3);
147
148         GrpcConfig config = new GrpcConfig(blockingExecutor, cdsProps);
149
150         operation = new GrpcOperation(params, config);
151
152         // set the properties
153         operation.setProperty(OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES, Collections.emptyMap());
154
155         OperationOutcome outcome = operation.start().get();
156         assertEquals(OperationResult.SUCCESS, outcome.getResult());
157         assertTrue(outcome.getResponse() instanceof ExecutionServiceOutput);
158     }
159
160     @Test
161     public void testGetPropertyNames() {
162
163         /*
164          * check VNF case
165          */
166         operation = new GrpcOperation(params, config);
167
168         // @formatter:off
169         assertThat(operation.getPropertyNames()).isEqualTo(
170                         List.of(
171                             OperationProperties.AAI_RESOURCE_VNF,
172                             OperationProperties.AAI_SERVICE,
173                             OperationProperties.EVENT_ADDITIONAL_PARAMS,
174                             OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES));
175         // @formatter:on
176
177         /*
178          * check PNF case
179          */
180         params = params.toBuilder().targetType(TargetType.PNF).build();
181         operation = new GrpcOperation(params, config);
182
183         // @formatter:off
184         assertThat(operation.getPropertyNames()).isEqualTo(
185                         List.of(
186                             OperationProperties.AAI_PNF,
187                             OperationProperties.EVENT_ADDITIONAL_PARAMS,
188                             OperationProperties.OPT_CDS_GRPC_AAI_PROPERTIES));
189         // @formatter:on
190     }
191
192     @Test
193     public void testGetServiceInstanceId() {
194         operation = new GrpcOperation(params, config);
195         loadVnfData();
196         assertEquals(MY_SVC_ID, operation.getServiceInstanceId());
197     }
198
199     @Test
200     public void testGetVnfId() {
201         operation = new GrpcOperation(params, config);
202         loadVnfData();
203         assertEquals(MY_VNF, operation.getVnfId());
204     }
205
206     @Test
207     public void testStartOperationAsync() throws Exception {
208         verifyOperation(TargetType.VNF, this::loadVnfData);
209     }
210
211     /**
212      * Tests startOperationAsync() when the target type is PNF.
213      */
214     @Test
215     public void testStartOperationAsyncPnf() throws Exception {
216         verifyOperation(TargetType.PNF, this::loadPnfData);
217     }
218
219     @Test
220     public void testStartOperationAsyncError() throws Exception {
221         operation = new GrpcOperation(params, config);
222         assertThatIllegalArgumentException()
223                         .isThrownBy(() -> operation.startOperationAsync(1, params.makeOutcome(null)));
224     }
225
226     private void verifyOperation(TargetType targetType, Runnable loader) {
227
228         Map<String, Object> payloadMap = Map.of(CdsActorConstants.KEY_CBA_NAME, CDS_BLUEPRINT_NAME,
229                         CdsActorConstants.KEY_CBA_VERSION, CDS_BLUEPRINT_VERSION, "data",
230                         "{\"mapInfo\":{\"key\":\"val\"},\"arrayInfo\":[\"one\",\"two\"],\"paramInfo\":\"val\"}");
231
232         ControlLoopOperationParams params = ControlLoopOperationParams.builder().actor(CdsActorConstants.CDS_ACTOR)
233                         .operation(GrpcOperation.NAME).requestId(REQUEST_ID).actorService(new ActorService())
234                         .targetType(targetType).targetEntity(TARGET_ENTITY).payload(payloadMap).build();
235
236         GrpcConfig config = new GrpcConfig(executor, cdsProps);
237         operation = new GrpcOperation(params, config);
238         assertEquals(1000, operation.getTimeoutMs(null));
239         assertEquals(1000, operation.getTimeoutMs(0));
240         assertEquals(2000, operation.getTimeoutMs(2));
241         operation.generateSubRequestId(1);
242
243         loader.run();
244         CompletableFuture<OperationOutcome> future3 = operation.startOperationAsync(1, params.makeOutcome(null));
245         assertNotNull(future3);
246     }
247
248     private void loadPnfData() {
249         try {
250             String json = "{'dataA': 'valueA', 'dataB': 'valueB'}".replace('\'', '"');
251             StandardCoderObject sco = coder.decode(json, StandardCoderObject.class);
252
253             operation.setProperty(OperationProperties.AAI_PNF, sco);
254
255         } catch (CoderException e) {
256             throw new IllegalArgumentException("cannot decode PNF json", e);
257         }
258     }
259
260     private void loadVnfData() {
261         GenericVnf genvnf = new GenericVnf();
262         genvnf.setVnfId(MY_VNF);
263         operation.setProperty(OperationProperties.AAI_RESOURCE_VNF, genvnf);
264
265         ServiceInstance serviceInstance = new ServiceInstance();
266         serviceInstance.setServiceInstanceId(MY_SVC_ID);
267         operation.setProperty(OperationProperties.AAI_SERVICE, serviceInstance);
268     }
269 }