Merge "Remove Target and TargetType"
[policy/models.git] / models-interactions / model-actors / actor.appclcm / src / test / java / org / onap / policy / controlloop / actor / appclcm / AppcLcmOperationTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.controlloop.actor.appclcm;
22
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertFalse;
27 import static org.junit.Assert.assertNotNull;
28 import static org.junit.Assert.assertNull;
29 import static org.junit.Assert.assertSame;
30 import static org.junit.Assert.assertTrue;
31 import static org.mockito.Mockito.mock;
32 import static org.mockito.Mockito.when;
33
34 import java.util.Arrays;
35 import java.util.HashMap;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.Set;
39 import java.util.concurrent.CompletableFuture;
40 import java.util.concurrent.atomic.AtomicBoolean;
41 import java.util.stream.Collectors;
42 import org.junit.After;
43 import org.junit.AfterClass;
44 import org.junit.Before;
45 import org.junit.BeforeClass;
46 import org.junit.Test;
47 import org.onap.policy.appclcm.AppcLcmBody;
48 import org.onap.policy.appclcm.AppcLcmCommonHeader;
49 import org.onap.policy.appclcm.AppcLcmDmaapWrapper;
50 import org.onap.policy.appclcm.AppcLcmOutput;
51 import org.onap.policy.appclcm.AppcLcmResponseStatus;
52 import org.onap.policy.common.endpoints.event.comm.TopicSink;
53 import org.onap.policy.common.endpoints.event.comm.TopicSource;
54 import org.onap.policy.common.utils.coder.Coder;
55 import org.onap.policy.common.utils.coder.CoderException;
56 import org.onap.policy.common.utils.coder.StandardCoder;
57 import org.onap.policy.controlloop.ControlLoopOperation;
58 import org.onap.policy.controlloop.actor.test.BasicBidirectionalTopicOperation;
59 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
60 import org.onap.policy.controlloop.actorserviceprovider.OperationProperties;
61 import org.onap.policy.controlloop.actorserviceprovider.OperationResult;
62 import org.onap.policy.controlloop.actorserviceprovider.controlloop.ControlLoopEventContext;
63 import org.onap.policy.controlloop.actorserviceprovider.impl.BidirectionalTopicOperation.Status;
64 import org.onap.policy.controlloop.actorserviceprovider.parameters.BidirectionalTopicConfig;
65 import org.onap.policy.controlloop.actorserviceprovider.parameters.BidirectionalTopicParams;
66 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
67 import org.onap.policy.simulators.AppcLcmTopicServer;
68 import org.onap.policy.simulators.TopicServer;
69
70 public class AppcLcmOperationTest extends BasicBidirectionalTopicOperation<AppcLcmDmaapWrapper> {
71
72     private static final String EXPECTED_EXCEPTION = "expected exception";
73     private static final String PAYLOAD_KEY1 = "key-A";
74     private static final String PAYLOAD_VALUE1 = "value-A";
75     private static final String MY_MESSAGE = "my-message";
76     protected static final String MY_VNF = "my-vnf";
77     protected static final String RESOURCE_ID = "my-resource";
78     private static final int SUCCESS_CODE = 400;
79
80     private AppcLcmDmaapWrapper response;
81     private AppcLcmOperation oper;
82
83     @BeforeClass
84     public static void setUpBeforeClass() throws Exception {
85         initBeforeClass(MY_SINK, MY_SOURCE);
86     }
87
88     @AfterClass
89     public static void tearDownAfterClass() {
90         destroyAfterClass();
91     }
92
93     /**
94      * Sets up.
95      */
96     @Before
97     public void setUp() {
98         super.setUpBasic();
99
100         response = makeResponse();
101
102         oper = new AppcLcmOperation(params, config);
103     }
104
105     @After
106     public void tearDown() {
107         super.tearDownBasic();
108     }
109
110     @Override
111     protected TopicServer<AppcLcmDmaapWrapper> makeServer(TopicSink sink, TopicSource source) {
112         return new AppcLcmTopicServer(sink, source);
113     }
114
115     /**
116      * Tests "success" case with simulator.
117      */
118     @Test
119     public void testSuccess() throws Exception {
120         BidirectionalTopicParams opParams =
121                         BidirectionalTopicParams.builder().sinkTopic(MY_SINK).sourceTopic(MY_SOURCE).build();
122         config = new BidirectionalTopicConfig(blockingExecutor, opParams, topicMgr, AppcLcmOperation.SELECTOR_KEYS);
123
124         params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor).build();
125
126         oper = new AppcLcmOperation(params, config) {
127             @Override
128             protected CompletableFuture<OperationOutcome> startGuardAsync() {
129                 return null;
130             }
131         };
132
133         outcome = oper.start().get();
134         assertEquals(OperationResult.SUCCESS, outcome.getResult());
135         assertTrue(outcome.getResponse() instanceof AppcLcmDmaapWrapper);
136     }
137
138     @Test
139     public void testConstructor() {
140         assertEquals(DEFAULT_ACTOR, oper.getActorName());
141         assertEquals(DEFAULT_OPERATION, oper.getName());
142     }
143
144     @Test
145     public void testGetPropertyNames() {
146         assertThat(oper.getPropertyNames()).isEqualTo(List.of(OperationProperties.AAI_TARGET_ENTITY));
147     }
148
149     @Test
150     public void testStartPreprocessorAsync() throws Exception {
151         context = mock(ControlLoopEventContext.class);
152         when(context.getEvent()).thenReturn(event);
153         params = params.toBuilder().context(context).build();
154
155         AtomicBoolean guardStarted = new AtomicBoolean();
156
157         oper = new AppcLcmOperation(params, config) {
158             @Override
159             protected CompletableFuture<OperationOutcome> startGuardAsync() {
160                 guardStarted.set(true);
161                 return super.startGuardAsync();
162             }
163         };
164
165         CompletableFuture<OperationOutcome> future2 = oper.startPreprocessorAsync();
166         assertNotNull(future2);
167         assertFalse(future.isDone());
168         assertTrue(guardStarted.get());
169
170         assertTrue(executor.runAll(100));
171         assertTrue(future2.isDone());
172         outcome = future2.get();
173         assertEquals(OperationResult.SUCCESS, outcome.getResult());
174     }
175
176     @Test
177     public void testMakeRequest() {
178         oper.generateSubRequestId(2);
179         String subreq = oper.getSubRequestId();
180         assertNotNull(subreq);
181
182         AppcLcmDmaapWrapper request = oper.makeRequest(2);
183         assertEquals("DefaultOperation", request.getBody().getInput().getAction());
184
185         AppcLcmCommonHeader header = request.getBody().getInput().getCommonHeader();
186         assertNotNull(header);
187         assertEquals(params.getRequestId(), header.getRequestId());
188
189         assertEquals(subreq, header.getSubRequestId());
190
191         assertEquals("{vnf-id=my-target}", request.getBody().getInput().getActionIdentifiers().toString());
192
193         request = oper.makeRequest(2);
194         assertEquals(subreq, request.getBody().getInput().getCommonHeader().getSubRequestId());
195     }
196
197     @Test
198     public void testConvertPayload() {
199         // only builds a payload for ConfigModify
200         params = params.toBuilder().operation(AppcLcmConstants.OPERATION_CONFIG_MODIFY).build();
201         oper = new AppcLcmOperation(params, config);
202
203         oper.generateSubRequestId(2);
204         AppcLcmDmaapWrapper req = oper.makeRequest(2);
205         assertEquals("{\"key-A\":\"value-A\"}", req.getBody().getInput().getPayload());
206
207         // coder exception
208         oper = new AppcLcmOperation(params, config) {
209             @Override
210             protected Coder getCoder() {
211                 return new StandardCoder() {
212                     @Override
213                     public String encode(Object object) throws CoderException {
214                         throw new CoderException(EXPECTED_EXCEPTION);
215                     }
216                 };
217             }
218         };
219
220         oper.generateSubRequestId(2);
221
222         assertThatIllegalArgumentException().isThrownBy(() -> oper.makeRequest(2))
223                         .withMessage("Cannot convert payload");
224     }
225
226     @Test
227     public void testGetExpectedKeyValues() {
228         oper.generateSubRequestId(2);
229         AppcLcmDmaapWrapper request = oper.makeRequest(2);
230         assertEquals(Arrays.asList(request.getBody().getInput().getCommonHeader().getSubRequestId()),
231                         oper.getExpectedKeyValues(50, request));
232     }
233
234     @Test
235     public void testDetmStatus() {
236         assertEquals(Status.SUCCESS, oper.detmStatus(null, response));
237
238         // failure
239         response.getBody().getOutput().getStatus().setCode(405);
240         assertEquals(Status.FAILURE, oper.detmStatus(null, response));
241
242         // error
243         response.getBody().getOutput().getStatus().setCode(200);
244         assertThatIllegalArgumentException().isThrownBy(() -> oper.detmStatus(null, response));
245
246         // reject
247         response.getBody().getOutput().getStatus().setCode(305);
248         assertThatIllegalArgumentException().isThrownBy(() -> oper.detmStatus(null, response));
249
250         // accepted
251         response.getBody().getOutput().getStatus().setCode(100);
252         assertEquals(Status.STILL_WAITING, oper.detmStatus(null, response));
253
254         // other
255         response.getBody().getOutput().getStatus().setCode(-1);
256         assertThatIllegalArgumentException().isThrownBy(() -> oper.detmStatus(null, response));
257
258         // null status
259         response.getBody().getOutput().setStatus(null);
260         assertThatIllegalArgumentException().isThrownBy(() -> oper.detmStatus(null, response));
261     }
262
263     @Test
264     public void testSetOutcome() {
265         oper.setOutcome(outcome, OperationResult.SUCCESS, response);
266         assertEquals(OperationResult.SUCCESS, outcome.getResult());
267         assertEquals(MY_MESSAGE, outcome.getMessage());
268         assertSame(response, outcome.getResponse());
269
270         // failure
271         oper.setOutcome(outcome, OperationResult.FAILURE, response);
272         assertEquals(OperationResult.FAILURE, outcome.getResult());
273         assertEquals(MY_MESSAGE, outcome.getMessage());
274         assertSame(response, outcome.getResponse());
275
276         // null message
277         response.getBody().getOutput().getStatus().setMessage(null);
278         oper.setOutcome(outcome, OperationResult.SUCCESS, response);
279         assertEquals(ControlLoopOperation.SUCCESS_MSG, outcome.getMessage());
280         assertSame(response, outcome.getResponse());
281
282         // null status
283         response.getBody().getOutput().setStatus(null);
284         oper.setOutcome(outcome, OperationResult.SUCCESS, response);
285         assertEquals(ControlLoopOperation.SUCCESS_MSG, outcome.getMessage());
286         assertSame(response, outcome.getResponse());
287     }
288
289     @Test
290     public void testGetStatus() {
291         assertNotNull(oper.getStatus(response));
292
293         // null status
294         response.getBody().getOutput().setStatus(null);
295         assertNull(oper.getStatus(response));
296
297         // null outcome
298         response.getBody().setOutput(null);
299         assertNull(oper.getStatus(response));
300
301         // null body
302         response.setBody(null);
303         assertNull(oper.getStatus(response));
304
305         // null response
306         assertNull(oper.getStatus(null));
307     }
308
309     @Test
310     public void testOperationSupportsPayload() {
311         // these should support a payload
312         Set<String> supported = Set.of(AppcLcmConstants.OPERATION_CONFIG_MODIFY);
313
314         for (String name : supported) {
315             params = params.toBuilder().operation(name).build();
316             oper = new AppcLcmOperation(params, config);
317             assertTrue(name, oper.operationSupportsPayload());
318         }
319
320         // these should NOT support a payload
321         Set<String> unsupported = AppcLcmConstants.OPERATION_NAMES.stream().filter(name -> !supported.contains(name))
322                         .collect(Collectors.toSet());
323
324         for (String name : unsupported) {
325             params = params.toBuilder().operation(name).build();
326             oper = new AppcLcmOperation(params, config);
327             assertFalse(name, oper.operationSupportsPayload());
328         }
329
330         // pick an operation that would ordinarily support payloads
331         String sup = supported.iterator().next();
332
333         // verify that it still supports payload
334         params = params.toBuilder().operation(sup).build();
335         oper = new AppcLcmOperation(params, config);
336         assertTrue(oper.operationSupportsPayload());
337
338         // try with empty payload
339         params = params.toBuilder().payload(Map.of()).build();
340         oper = new AppcLcmOperation(params, config);
341         assertFalse(oper.operationSupportsPayload());
342
343         // try with null payload
344         params = params.toBuilder().payload(null).build();
345         oper = new AppcLcmOperation(params, config);
346         assertFalse(oper.operationSupportsPayload());
347     }
348
349     @Override
350     protected void makeContext() {
351         super.makeContext();
352
353         Map<String, String> targetEntities = new HashMap<>();
354         targetEntities.put(ControlLoopOperationParams.PARAMS_ENTITY_RESOURCEID, RESOURCE_ID);
355
356         params = params.toBuilder().targetEntityIds(targetEntities).build();
357     }
358
359     @Override
360     protected Map<String, Object> makePayload() {
361         return Map.of(PAYLOAD_KEY1, PAYLOAD_VALUE1);
362     }
363
364     private AppcLcmDmaapWrapper makeResponse() {
365         AppcLcmDmaapWrapper response = new AppcLcmDmaapWrapper();
366
367         AppcLcmBody body = new AppcLcmBody();
368         response.setBody(body);
369
370         AppcLcmOutput output = new AppcLcmOutput();
371         body.setOutput(output);
372
373         AppcLcmResponseStatus status = new AppcLcmResponseStatus();
374         output.setStatus(status);
375         status.setMessage(MY_MESSAGE);
376         status.setCode(SUCCESS_CODE);
377
378         return response;
379     }
380 }