Include response in OperationOutcome
[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 {
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     @SuppressWarnings("rawtypes")
107     protected TopicServer 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 testStartPreprocessorAsync() throws Exception {
147         context = mock(ControlLoopEventContext.class);
148         when(context.getEvent()).thenReturn(event);
149         params = params.toBuilder().context(context).build();
150
151         AtomicBoolean guardStarted = new AtomicBoolean();
152
153         oper = new AppcLcmOperation(params, config) {
154             @Override
155             protected CompletableFuture<OperationOutcome> startGuardAsync() {
156                 guardStarted.set(true);
157                 return super.startGuardAsync();
158             }
159         };
160
161         CompletableFuture<OperationOutcome> future2 = oper.startPreprocessorAsync();
162         assertNotNull(future2);
163         assertFalse(future.isDone());
164         assertTrue(guardStarted.get());
165
166         assertTrue(executor.runAll(100));
167         assertTrue(future2.isDone());
168         outcome = future2.get();
169         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
170     }
171
172     @Test
173     public void testMakeRequest() {
174         oper.generateSubRequestId(2);
175         String subreq = oper.getSubRequestId();
176         assertNotNull(subreq);
177
178         AppcLcmDmaapWrapper request = oper.makeRequest(2);
179         assertEquals("DefaultOperation", request.getBody().getInput().getAction());
180
181         AppcLcmCommonHeader header = request.getBody().getInput().getCommonHeader();
182         assertNotNull(header);
183         assertEquals(params.getRequestId(), header.getRequestId());
184
185         assertEquals(subreq, header.getSubRequestId());
186
187         assertEquals("{vnf-id=my-target}", request.getBody().getInput().getActionIdentifiers().toString());
188
189         request = oper.makeRequest(2);
190         assertEquals(subreq, request.getBody().getInput().getCommonHeader().getSubRequestId());
191     }
192
193     @Test
194     public void testConvertPayload() {
195         // only builds a payload for ConfigModify
196         params = params.toBuilder().operation(AppcLcmConstants.OPERATION_CONFIG_MODIFY).build();
197         oper = new AppcLcmOperation(params, config);
198
199         oper.generateSubRequestId(2);
200         AppcLcmDmaapWrapper req = oper.makeRequest(2);
201         assertEquals("{\"key-A\":\"value-A\"}", req.getBody().getInput().getPayload());
202
203         // coder exception
204         oper = new AppcLcmOperation(params, config) {
205             @Override
206             protected Coder makeCoder() {
207                 return new StandardCoder() {
208                     @Override
209                     public String encode(Object object) throws CoderException {
210                         throw new CoderException(EXPECTED_EXCEPTION);
211                     }
212                 };
213             }
214         };
215
216         oper.generateSubRequestId(2);
217
218         assertThatIllegalArgumentException().isThrownBy(() -> oper.makeRequest(2))
219                         .withMessage("Cannot convert payload");
220     }
221
222     @Test
223     public void testGetExpectedKeyValues() {
224         oper.generateSubRequestId(2);
225         AppcLcmDmaapWrapper request = oper.makeRequest(2);
226         assertEquals(Arrays.asList(request.getBody().getInput().getCommonHeader().getSubRequestId()),
227                         oper.getExpectedKeyValues(50, request));
228     }
229
230     @Test
231     public void testDetmStatus() {
232         assertEquals(Status.SUCCESS, oper.detmStatus(null, response));
233
234         // failure
235         response.getBody().getOutput().getStatus().setCode(405);
236         assertEquals(Status.FAILURE, oper.detmStatus(null, response));
237
238         // error
239         response.getBody().getOutput().getStatus().setCode(200);
240         assertThatIllegalArgumentException().isThrownBy(() -> oper.detmStatus(null, response));
241
242         // reject
243         response.getBody().getOutput().getStatus().setCode(305);
244         assertThatIllegalArgumentException().isThrownBy(() -> oper.detmStatus(null, response));
245
246         // accepted
247         response.getBody().getOutput().getStatus().setCode(100);
248         assertEquals(Status.STILL_WAITING, oper.detmStatus(null, response));
249
250         // other
251         response.getBody().getOutput().getStatus().setCode(-1);
252         assertThatIllegalArgumentException().isThrownBy(() -> oper.detmStatus(null, response));
253
254         // null status
255         response.getBody().getOutput().setStatus(null);
256         assertThatIllegalArgumentException().isThrownBy(() -> oper.detmStatus(null, response));
257     }
258
259     @Test
260     public void testSetOutcome() {
261         oper.setOutcome(outcome, PolicyResult.SUCCESS, response);
262         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
263         assertEquals(MY_MESSAGE, outcome.getMessage());
264         assertSame(response, outcome.getResponse());
265
266         // failure
267         oper.setOutcome(outcome, PolicyResult.FAILURE, response);
268         assertEquals(PolicyResult.FAILURE, outcome.getResult());
269         assertEquals(MY_MESSAGE, outcome.getMessage());
270         assertSame(response, outcome.getResponse());
271
272         // null message
273         response.getBody().getOutput().getStatus().setMessage(null);
274         oper.setOutcome(outcome, PolicyResult.SUCCESS, response);
275         assertEquals(ControlLoopOperation.SUCCESS_MSG, outcome.getMessage());
276         assertSame(response, outcome.getResponse());
277
278         // null status
279         response.getBody().getOutput().setStatus(null);
280         oper.setOutcome(outcome, PolicyResult.SUCCESS, response);
281         assertEquals(ControlLoopOperation.SUCCESS_MSG, outcome.getMessage());
282         assertSame(response, outcome.getResponse());
283     }
284
285     @Test
286     public void testGetStatus() {
287         assertNotNull(oper.getStatus(response));
288
289         // null status
290         response.getBody().getOutput().setStatus(null);
291         assertNull(oper.getStatus(response));
292
293         // null outcome
294         response.getBody().setOutput(null);
295         assertNull(oper.getStatus(response));
296
297         // null body
298         response.setBody(null);
299         assertNull(oper.getStatus(response));
300
301         // null response
302         assertNull(oper.getStatus(null));
303     }
304
305     @Test
306     public void testOperationSupportsPayload() {
307         // these should support a payload
308         Set<String> supported = Set.of(AppcLcmConstants.OPERATION_CONFIG_MODIFY);
309
310         for (String name : supported) {
311             params = params.toBuilder().operation(name).build();
312             oper = new AppcLcmOperation(params, config);
313             assertTrue(name, oper.operationSupportsPayload());
314         }
315
316         // these should NOT support a payload
317         Set<String> unsupported = AppcLcmConstants.OPERATION_NAMES.stream().filter(name -> !supported.contains(name))
318                         .collect(Collectors.toSet());
319
320         for (String name : unsupported) {
321             params = params.toBuilder().operation(name).build();
322             oper = new AppcLcmOperation(params, config);
323             assertFalse(name, oper.operationSupportsPayload());
324         }
325
326         // pick an operation that would ordinarily support payloads
327         String sup = supported.iterator().next();
328
329         // verify that it still supports payload
330         params = params.toBuilder().operation(sup).build();
331         oper = new AppcLcmOperation(params, config);
332         assertTrue(oper.operationSupportsPayload());
333
334         // try with empty payload
335         params = params.toBuilder().payload(Map.of()).build();
336         oper = new AppcLcmOperation(params, config);
337         assertFalse(oper.operationSupportsPayload());
338
339         // try with null payload
340         params = params.toBuilder().payload(null).build();
341         oper = new AppcLcmOperation(params, config);
342         assertFalse(oper.operationSupportsPayload());
343     }
344
345     @Override
346     protected void makeContext() {
347         super.makeContext();
348
349         Target target = new Target();
350         target.setResourceID(RESOURCE_ID);
351
352         params = params.toBuilder().target(target).build();
353     }
354
355     @Override
356     protected Map<String, Object> makePayload() {
357         return Map.of(PAYLOAD_KEY1, PAYLOAD_VALUE1);
358     }
359
360     private AppcLcmDmaapWrapper makeResponse() {
361         AppcLcmDmaapWrapper response = new AppcLcmDmaapWrapper();
362
363         AppcLcmBody body = new AppcLcmBody();
364         response.setBody(body);
365
366         AppcLcmOutput output = new AppcLcmOutput();
367         body.setOutput(output);
368
369         AppcLcmResponseStatus status = new AppcLcmResponseStatus();
370         output.setStatus(status);
371         status.setMessage(MY_MESSAGE);
372         status.setCode(SUCCESS_CODE);
373
374         return response;
375     }
376 }