Test new actors against simulators
[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.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 {
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     @SuppressWarnings("rawtypes")
108     protected TopicServer makeServer(TopicSink sink, TopicSource source) {
109         return new AppcLcmTopicServer(sink, source);
110     }
111
112     /**
113      * Tests "success" case with simulator.
114      */
115     @Test
116     public void testSuccess() throws Exception {
117         BidirectionalTopicParams opParams =
118                         BidirectionalTopicParams.builder().sinkTopic(MY_SINK).sourceTopic(MY_SOURCE).build();
119         config = new BidirectionalTopicConfig(blockingExecutor, opParams, topicMgr, AppcLcmOperation.SELECTOR_KEYS);
120
121         params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor).build();
122
123         oper = new AppcLcmOperation(params, config) {
124             @Override
125             protected CompletableFuture<OperationOutcome> startGuardAsync() {
126                 return null;
127             }
128         };
129
130         outcome = oper.start().get();
131         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
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         assertEquals(PolicyResult.SUCCESS, future2.get().getResult());
169     }
170
171     @Test
172     public void testMakeRequest() {
173         Pair<String, AppcLcmDmaapWrapper> result = oper.makeRequest(2);
174         String subreq = result.getLeft();
175         assertNotNull(subreq);
176
177         AppcLcmDmaapWrapper request = result.getRight();
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         // a subsequent request should have a different sub-request id
189         result = oper.makeRequest(2);
190         assertNotEquals(subreq, result.getLeft());
191         assertNotNull(result.getLeft());
192         assertEquals(result.getLeft(), result.getRight().getBody().getInput().getCommonHeader().getSubRequestId());
193     }
194
195     @Test
196     public void testConvertPayload() {
197         // only builds a payload for ConfigModify
198         params = params.toBuilder().operation(AppcLcmConstants.OPERATION_CONFIG_MODIFY).build();
199         oper = new AppcLcmOperation(params, config);
200
201         AppcLcmDmaapWrapper req = oper.makeRequest(2).getRight();
202         assertEquals("{\"key-A\":\"value-A\"}", req.getBody().getInput().getPayload());
203
204         // coder exception
205         oper = new AppcLcmOperation(params, config) {
206             @Override
207             protected Coder makeCoder() {
208                 return new StandardCoder() {
209                     @Override
210                     public String encode(Object object) throws CoderException {
211                         throw new CoderException(EXPECTED_EXCEPTION);
212                     }
213                 };
214             }
215         };
216
217         assertThatIllegalArgumentException().isThrownBy(() -> oper.makeRequest(2))
218                         .withMessage("Cannot convert payload");
219     }
220
221     @Test
222     public void testGetExpectedKeyValues() {
223         AppcLcmDmaapWrapper request = oper.makeRequest(2).getRight();
224         assertEquals(Arrays.asList(request.getBody().getInput().getCommonHeader().getSubRequestId()),
225                         oper.getExpectedKeyValues(50, request));
226     }
227
228     @Test
229     public void testDetmStatus() {
230         assertEquals(Status.SUCCESS, oper.detmStatus(null, response));
231
232         // failure
233         response.getBody().getOutput().getStatus().setCode(405);
234         assertEquals(Status.FAILURE, oper.detmStatus(null, response));
235
236         // error
237         response.getBody().getOutput().getStatus().setCode(200);
238         assertThatIllegalArgumentException().isThrownBy(() -> oper.detmStatus(null, response));
239
240         // reject
241         response.getBody().getOutput().getStatus().setCode(305);
242         assertThatIllegalArgumentException().isThrownBy(() -> oper.detmStatus(null, response));
243
244         // accepted
245         response.getBody().getOutput().getStatus().setCode(100);
246         assertEquals(Status.STILL_WAITING, oper.detmStatus(null, response));
247
248         // other
249         response.getBody().getOutput().getStatus().setCode(-1);
250         assertThatIllegalArgumentException().isThrownBy(() -> oper.detmStatus(null, response));
251
252         // null status
253         response.getBody().getOutput().setStatus(null);
254         assertThatIllegalArgumentException().isThrownBy(() -> oper.detmStatus(null, response));
255     }
256
257     @Test
258     public void testSetOutcome() {
259         oper.setOutcome(outcome, PolicyResult.SUCCESS, response);
260         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
261         assertEquals(MY_MESSAGE, outcome.getMessage());
262
263         // failure
264         oper.setOutcome(outcome, PolicyResult.FAILURE, response);
265         assertEquals(PolicyResult.FAILURE, outcome.getResult());
266         assertEquals(MY_MESSAGE, outcome.getMessage());
267
268         // null message
269         response.getBody().getOutput().getStatus().setMessage(null);
270         oper.setOutcome(outcome, PolicyResult.SUCCESS, response);
271         assertEquals(ControlLoopOperation.SUCCESS_MSG, outcome.getMessage());
272
273         // null status
274         response.getBody().getOutput().setStatus(null);
275         oper.setOutcome(outcome, PolicyResult.SUCCESS, response);
276         assertEquals(ControlLoopOperation.SUCCESS_MSG, outcome.getMessage());
277     }
278
279     @Test
280     public void testGetStatus() {
281         assertNotNull(oper.getStatus(response));
282
283         // null status
284         response.getBody().getOutput().setStatus(null);
285         assertNull(oper.getStatus(response));
286
287         // null outcome
288         response.getBody().setOutput(null);
289         assertNull(oper.getStatus(response));
290
291         // null body
292         response.setBody(null);
293         assertNull(oper.getStatus(response));
294
295         // null response
296         assertNull(oper.getStatus(null));
297     }
298
299     @Test
300     public void testOperationSupportsPayload() {
301         // these should support a payload
302         Set<String> supported = Set.of(AppcLcmConstants.OPERATION_CONFIG_MODIFY);
303
304         for (String name : supported) {
305             params = params.toBuilder().operation(name).build();
306             oper = new AppcLcmOperation(params, config);
307             assertTrue(name, oper.operationSupportsPayload());
308         }
309
310         // these should NOT support a payload
311         Set<String> unsupported = AppcLcmConstants.OPERATION_NAMES.stream().filter(name -> !supported.contains(name))
312                         .collect(Collectors.toSet());
313
314         for (String name : unsupported) {
315             params = params.toBuilder().operation(name).build();
316             oper = new AppcLcmOperation(params, config);
317             assertFalse(name, oper.operationSupportsPayload());
318         }
319
320         // pick an operation that would ordinarily support payloads
321         String sup = supported.iterator().next();
322
323         // verify that it still supports payload
324         params = params.toBuilder().operation(sup).build();
325         oper = new AppcLcmOperation(params, config);
326         assertTrue(oper.operationSupportsPayload());
327
328         // try with empty payload
329         params = params.toBuilder().payload(Map.of()).build();
330         oper = new AppcLcmOperation(params, config);
331         assertFalse(oper.operationSupportsPayload());
332
333         // try with null payload
334         params = params.toBuilder().payload(null).build();
335         oper = new AppcLcmOperation(params, config);
336         assertFalse(oper.operationSupportsPayload());
337     }
338
339     @Override
340     protected void makeContext() {
341         super.makeContext();
342
343         Target target = new Target();
344         target.setResourceID(RESOURCE_ID);
345
346         params = params.toBuilder().target(target).build();
347     }
348
349     @Override
350     protected Map<String, Object> makePayload() {
351         return Map.of(PAYLOAD_KEY1, PAYLOAD_VALUE1);
352     }
353
354     private AppcLcmDmaapWrapper makeResponse() {
355         AppcLcmDmaapWrapper response = new AppcLcmDmaapWrapper();
356
357         AppcLcmBody body = new AppcLcmBody();
358         response.setBody(body);
359
360         AppcLcmOutput output = new AppcLcmOutput();
361         body.setOutput(output);
362
363         AppcLcmResponseStatus status = new AppcLcmResponseStatus();
364         output.setStatus(status);
365         status.setMessage(MY_MESSAGE);
366         status.setCode(SUCCESS_CODE);
367
368         return response;
369     }
370 }