Add subrequest ID to 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.assertNotEquals;
27 import static org.junit.Assert.assertNotNull;
28 import static org.junit.Assert.assertNull;
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.apache.commons.lang3.tuple.Pair;
40 import org.junit.Before;
41 import org.junit.Test;
42 import org.onap.policy.appclcm.AppcLcmBody;
43 import org.onap.policy.appclcm.AppcLcmCommonHeader;
44 import org.onap.policy.appclcm.AppcLcmDmaapWrapper;
45 import org.onap.policy.appclcm.AppcLcmOutput;
46 import org.onap.policy.appclcm.AppcLcmResponseStatus;
47 import org.onap.policy.common.utils.coder.Coder;
48 import org.onap.policy.common.utils.coder.CoderException;
49 import org.onap.policy.common.utils.coder.StandardCoder;
50 import org.onap.policy.controlloop.ControlLoopOperation;
51 import org.onap.policy.controlloop.actor.test.BasicBidirectionalTopicOperation;
52 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
53 import org.onap.policy.controlloop.actorserviceprovider.controlloop.ControlLoopEventContext;
54 import org.onap.policy.controlloop.actorserviceprovider.impl.BidirectionalTopicOperation.Status;
55 import org.onap.policy.controlloop.policy.PolicyResult;
56 import org.onap.policy.controlloop.policy.Target;
57
58 public class AppcLcmOperationTest extends BasicBidirectionalTopicOperation {
59
60     private static final String EXPECTED_EXCEPTION = "expected exception";
61     private static final String PAYLOAD_KEY1 = "key-A";
62     private static final String PAYLOAD_VALUE1 = "value-A";
63     private static final String MY_MESSAGE = "my-message";
64     protected static final String MY_VNF = "my-vnf";
65     protected static final String RESOURCE_ID = "my-resource";
66     private static final int SUCCESS_CODE = 400;
67
68     private AppcLcmDmaapWrapper response;
69     private AppcLcmOperation oper;
70
71     /**
72      * Sets up.
73      */
74     @Before
75     public void setUp() {
76         super.setUpBasic();
77
78         response = makeResponse();
79
80         oper = new AppcLcmOperation(params, config);
81     }
82
83     @Test
84     public void testConstructor() {
85         assertEquals(DEFAULT_ACTOR, oper.getActorName());
86         assertEquals(DEFAULT_OPERATION, oper.getName());
87
88         // missing target entity
89         params = params.toBuilder().targetEntity("").build();
90         assertThatIllegalArgumentException().isThrownBy(() -> new AppcLcmOperation(params, config))
91                         .withMessage("missing targetEntity");
92     }
93
94     @Test
95     public void testStartPreprocessorAsync() throws Exception {
96         context = mock(ControlLoopEventContext.class);
97         when(context.getEvent()).thenReturn(event);
98         params = params.toBuilder().context(context).build();
99
100         AtomicBoolean guardStarted = new AtomicBoolean();
101
102         oper = new AppcLcmOperation(params, config) {
103             @Override
104             protected CompletableFuture<OperationOutcome> startGuardAsync() {
105                 guardStarted.set(true);
106                 return super.startGuardAsync();
107             }
108         };
109
110         CompletableFuture<OperationOutcome> future2 = oper.startPreprocessorAsync();
111         assertNotNull(future2);
112         assertFalse(future.isDone());
113         assertTrue(guardStarted.get());
114
115         assertTrue(executor.runAll(100));
116         assertTrue(future2.isDone());
117         assertEquals(PolicyResult.SUCCESS, future2.get().getResult());
118     }
119
120     @Test
121     public void testMakeRequest() {
122         Pair<String, AppcLcmDmaapWrapper> result = oper.makeRequest(2);
123         String subreq = result.getLeft();
124         assertNotNull(subreq);
125
126         AppcLcmDmaapWrapper request = result.getRight();
127         assertEquals("DefaultOperation", request.getBody().getInput().getAction());
128
129         AppcLcmCommonHeader header = request.getBody().getInput().getCommonHeader();
130         assertNotNull(header);
131         assertEquals(params.getRequestId(), header.getRequestId());
132
133         assertEquals(subreq, header.getSubRequestId());
134
135         assertEquals("{vnf-id=my-target}", request.getBody().getInput().getActionIdentifiers().toString());
136
137         // a subsequent request should have a different sub-request id
138         result = oper.makeRequest(2);
139         assertNotEquals(subreq, result.getLeft());
140         assertNotNull(result.getLeft());
141         assertEquals(result.getLeft(), result.getRight().getBody().getInput().getCommonHeader().getSubRequestId());
142     }
143
144     @Test
145     public void testConvertPayload() {
146         // only builds a payload for ConfigModify
147         params = params.toBuilder().operation(AppcLcmConstants.OPERATION_CONFIG_MODIFY).build();
148         oper = new AppcLcmOperation(params, config);
149
150         AppcLcmDmaapWrapper req = oper.makeRequest(2).getRight();
151         assertEquals("{\"key-A\":\"value-A\"}", req.getBody().getInput().getPayload());
152
153         // coder exception
154         oper = new AppcLcmOperation(params, config) {
155             @Override
156             protected Coder makeCoder() {
157                 return new StandardCoder() {
158                     @Override
159                     public String encode(Object object) throws CoderException {
160                         throw new CoderException(EXPECTED_EXCEPTION);
161                     }
162                 };
163             }
164         };
165
166         assertThatIllegalArgumentException().isThrownBy(() -> oper.makeRequest(2))
167                         .withMessage("Cannot convert payload");
168     }
169
170     @Test
171     public void testGetExpectedKeyValues() {
172         AppcLcmDmaapWrapper request = oper.makeRequest(2).getRight();
173         assertEquals(Arrays.asList(request.getBody().getInput().getCommonHeader().getSubRequestId()),
174                         oper.getExpectedKeyValues(50, request));
175     }
176
177     @Test
178     public void testDetmStatus() {
179         assertEquals(Status.SUCCESS, oper.detmStatus(null, response));
180
181         // failure
182         response.getBody().getOutput().getStatus().setCode(405);
183         assertEquals(Status.FAILURE, oper.detmStatus(null, response));
184
185         // error
186         response.getBody().getOutput().getStatus().setCode(200);
187         assertThatIllegalArgumentException().isThrownBy(() -> oper.detmStatus(null, response));
188
189         // reject
190         response.getBody().getOutput().getStatus().setCode(305);
191         assertThatIllegalArgumentException().isThrownBy(() -> oper.detmStatus(null, response));
192
193         // accepted
194         response.getBody().getOutput().getStatus().setCode(100);
195         assertEquals(Status.STILL_WAITING, oper.detmStatus(null, response));
196
197         // other
198         response.getBody().getOutput().getStatus().setCode(-1);
199         assertThatIllegalArgumentException().isThrownBy(() -> oper.detmStatus(null, response));
200
201         // null status
202         response.getBody().getOutput().setStatus(null);
203         assertThatIllegalArgumentException().isThrownBy(() -> oper.detmStatus(null, response));
204     }
205
206     @Test
207     public void testSetOutcome() {
208         oper.setOutcome(outcome, PolicyResult.SUCCESS, response);
209         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
210         assertEquals(MY_MESSAGE, outcome.getMessage());
211
212         // failure
213         oper.setOutcome(outcome, PolicyResult.FAILURE, response);
214         assertEquals(PolicyResult.FAILURE, outcome.getResult());
215         assertEquals(MY_MESSAGE, outcome.getMessage());
216
217         // null message
218         response.getBody().getOutput().getStatus().setMessage(null);
219         oper.setOutcome(outcome, PolicyResult.SUCCESS, response);
220         assertEquals(ControlLoopOperation.SUCCESS_MSG, outcome.getMessage());
221
222         // null status
223         response.getBody().getOutput().setStatus(null);
224         oper.setOutcome(outcome, PolicyResult.SUCCESS, response);
225         assertEquals(ControlLoopOperation.SUCCESS_MSG, outcome.getMessage());
226     }
227
228     @Test
229     public void testGetStatus() {
230         assertNotNull(oper.getStatus(response));
231
232         // null status
233         response.getBody().getOutput().setStatus(null);
234         assertNull(oper.getStatus(response));
235
236         // null outcome
237         response.getBody().setOutput(null);
238         assertNull(oper.getStatus(response));
239
240         // null body
241         response.setBody(null);
242         assertNull(oper.getStatus(response));
243
244         // null response
245         assertNull(oper.getStatus(null));
246     }
247
248     @Test
249     public void testOperationSupportsPayload() {
250         // these should support a payload
251         Set<String> supported = Set.of(AppcLcmConstants.OPERATION_CONFIG_MODIFY);
252
253         for (String name : supported) {
254             params = params.toBuilder().operation(name).build();
255             oper = new AppcLcmOperation(params, config);
256             assertTrue(name, oper.operationSupportsPayload());
257         }
258
259         // these should NOT support a payload
260         Set<String> unsupported = AppcLcmConstants.OPERATION_NAMES.stream().filter(name -> !supported.contains(name))
261                         .collect(Collectors.toSet());
262
263         for (String name : unsupported) {
264             params = params.toBuilder().operation(name).build();
265             oper = new AppcLcmOperation(params, config);
266             assertFalse(name, oper.operationSupportsPayload());
267         }
268
269         // pick an operation that would ordinarily support payloads
270         String sup = supported.iterator().next();
271
272         // verify that it still supports payload
273         params = params.toBuilder().operation(sup).build();
274         oper = new AppcLcmOperation(params, config);
275         assertTrue(oper.operationSupportsPayload());
276
277         // try with empty payload
278         params = params.toBuilder().payload(Map.of()).build();
279         oper = new AppcLcmOperation(params, config);
280         assertFalse(oper.operationSupportsPayload());
281
282         // try with null payload
283         params = params.toBuilder().payload(null).build();
284         oper = new AppcLcmOperation(params, config);
285         assertFalse(oper.operationSupportsPayload());
286     }
287
288     @Override
289     protected void makeContext() {
290         super.makeContext();
291
292         Target target = new Target();
293         target.setResourceID(RESOURCE_ID);
294
295         params = params.toBuilder().target(target).build();
296     }
297
298     @Override
299     protected Map<String, Object> makePayload() {
300         return Map.of(PAYLOAD_KEY1, PAYLOAD_VALUE1);
301     }
302
303     private AppcLcmDmaapWrapper makeResponse() {
304         AppcLcmDmaapWrapper response = new AppcLcmDmaapWrapper();
305
306         AppcLcmBody body = new AppcLcmBody();
307         response.setBody(body);
308
309         AppcLcmOutput output = new AppcLcmOutput();
310         body.setOutput(output);
311
312         AppcLcmResponseStatus status = new AppcLcmResponseStatus();
313         output.setStatus(status);
314         status.setMessage(MY_MESSAGE);
315         status.setCode(SUCCESS_CODE);
316
317         return response;
318     }
319 }