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