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