Add property lists to Actors
[policy/models.git] / models-interactions / model-actors / actor.so / src / test / java / org / onap / policy / controlloop / actor / so / VfModuleDeleteTest.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.so;
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.assertSame;
29 import static org.junit.Assert.assertTrue;
30 import static org.mockito.ArgumentMatchers.any;
31 import static org.mockito.Mockito.mock;
32 import static org.mockito.Mockito.never;
33 import static org.mockito.Mockito.verify;
34 import static org.mockito.Mockito.when;
35
36 import java.net.http.HttpHeaders;
37 import java.net.http.HttpRequest;
38 import java.net.http.HttpRequest.Builder;
39 import java.net.http.HttpResponse;
40 import java.net.http.HttpResponse.BodyHandlers;
41 import java.nio.charset.StandardCharsets;
42 import java.util.Base64;
43 import java.util.List;
44 import java.util.Map;
45 import java.util.concurrent.CompletableFuture;
46 import java.util.concurrent.ForkJoinPool;
47 import java.util.concurrent.TimeUnit;
48 import java.util.concurrent.atomic.AtomicBoolean;
49 import javax.ws.rs.client.InvocationCallback;
50 import javax.ws.rs.core.MediaType;
51 import javax.ws.rs.core.Response;
52 import org.apache.commons.lang3.tuple.Pair;
53 import org.junit.AfterClass;
54 import org.junit.Before;
55 import org.junit.BeforeClass;
56 import org.junit.Test;
57 import org.mockito.ArgumentCaptor;
58 import org.mockito.Mock;
59 import org.onap.aai.domain.yang.CloudRegion;
60 import org.onap.aai.domain.yang.GenericVnf;
61 import org.onap.aai.domain.yang.ModelVer;
62 import org.onap.aai.domain.yang.ServiceInstance;
63 import org.onap.aai.domain.yang.Tenant;
64 import org.onap.policy.aai.AaiCqResponse;
65 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
66 import org.onap.policy.common.utils.coder.CoderException;
67 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
68 import org.onap.policy.controlloop.actorserviceprovider.OperationProperties;
69 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
70 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpPollingConfig;
71 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpPollingParams;
72 import org.onap.policy.controlloop.policy.PolicyResult;
73 import org.onap.policy.so.SoRequest;
74 import org.onap.policy.so.SoResponse;
75
76 public class VfModuleDeleteTest extends BasicSoOperation {
77     private static final String EXPECTED_EXCEPTION = "expected exception";
78     private static final String MODEL_NAME2 = "my-model-name-B";
79     private static final String MODEL_VERS2 = "my-model-version-B";
80     private static final String SVC_INSTANCE_ID = "my-service-instance-id";
81     private static final String VNF_ID = "my-vnf-id";
82
83     @Mock
84     private java.net.http.HttpClient javaClient;
85     @Mock
86     private HttpResponse<String> javaResp;
87     @Mock
88     private InvocationCallback<Response> callback;
89
90     private CompletableFuture<HttpResponse<String>> javaFuture;
91     private VfModuleDelete oper;
92
93     public VfModuleDeleteTest() {
94         super(DEFAULT_ACTOR, VfModuleDelete.NAME);
95     }
96
97     @BeforeClass
98     public static void setUpBeforeClass() throws Exception {
99         initBeforeClass();
100     }
101
102     @AfterClass
103     public static void tearDownAfterClass() {
104         destroyAfterClass();
105     }
106
107     /**
108      * Sets up.
109      */
110     @Before
111     public void setUp() throws Exception {
112         super.setUp();
113
114         initHostPort();
115
116         configureResponse(coder.encode(response));
117
118         oper = new MyOperation(params, config);
119     }
120
121     /**
122      * Tests "success" case with simulator.
123      */
124     @Test
125     public void testSuccess() throws Exception {
126         HttpPollingParams opParams = HttpPollingParams.builder().clientName(MY_CLIENT).path("serviceInstances/v7")
127                         .pollPath("orchestrationRequests/v5/").maxPolls(2).build();
128         config = new HttpPollingConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory());
129
130         params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor).build();
131
132         oper = new VfModuleDelete(params, config);
133
134         outcome = oper.start().get();
135         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
136         assertTrue(outcome.getResponse() instanceof SoResponse);
137     }
138
139     @Test
140     public void testConstructor() {
141         assertEquals(DEFAULT_ACTOR, oper.getActorName());
142         assertEquals(VfModuleDelete.NAME, oper.getName());
143
144         // verify that target validation is done
145         params = params.toBuilder().target(null).build();
146         assertThatIllegalArgumentException().isThrownBy(() -> new MyOperation(params, config))
147                         .withMessageContaining("Target information");
148     }
149
150     @Test
151     public void testGetPropertyNames() {
152         // @formatter:off
153         assertThat(oper.getPropertyNames()).isEqualTo(
154                         List.of(
155                             OperationProperties.AAI_MODEL_SERVICE,
156                             OperationProperties.AAI_MODEL_VNF,
157                             OperationProperties.AAI_MODEL_CLOUD_REGION,
158                             OperationProperties.AAI_MODEL_TENANT,
159                             OperationProperties.DATA_VF_COUNT));
160         // @formatter:on
161     }
162
163     @Test
164     public void testStartPreprocessorAsync() throws Exception {
165         // insert CQ data so it's there for the check
166         context.setProperty(AaiCqResponse.CONTEXT_KEY, makeCqResponse());
167
168         AtomicBoolean guardStarted = new AtomicBoolean();
169
170         oper = new MyOperation(params, config) {
171             @Override
172             protected CompletableFuture<OperationOutcome> startGuardAsync() {
173                 guardStarted.set(true);
174                 return super.startGuardAsync();
175             }
176         };
177
178         CompletableFuture<OperationOutcome> future3 = oper.startPreprocessorAsync();
179         assertNotNull(future3);
180         assertTrue(guardStarted.get());
181     }
182
183     @Test
184     public void testStartGuardAsync() throws Exception {
185         // remove CQ data so it's forced to query
186         context.removeProperty(AaiCqResponse.CONTEXT_KEY);
187
188         CompletableFuture<OperationOutcome> future2 = oper.startPreprocessorAsync();
189         assertTrue(executor.runAll(100));
190         assertFalse(future2.isDone());
191
192         provideCqResponse(makeCqResponse());
193         assertTrue(executor.runAll(100));
194         assertTrue(future2.isDone());
195         assertEquals(PolicyResult.SUCCESS, future2.get().getResult());
196     }
197
198     @Test
199     public void testMakeGuardPayload() {
200         final int origCount = 30;
201         oper.setVfCount(origCount);
202
203         CompletableFuture<OperationOutcome> future2 = oper.startPreprocessorAsync();
204         assertTrue(executor.runAll(100));
205         assertTrue(future2.isDone());
206
207         // get the payload from the request
208         ArgumentCaptor<ControlLoopOperationParams> captor = ArgumentCaptor.forClass(ControlLoopOperationParams.class);
209         verify(guardOperator).buildOperation(captor.capture());
210
211         Map<String, Object> payload = captor.getValue().getPayload();
212         assertNotNull(payload);
213
214         Integer newCount = (Integer) payload.get(VfModuleDelete.PAYLOAD_KEY_VF_COUNT);
215         assertNotNull(newCount);
216         assertEquals(origCount - 1, newCount.intValue());
217     }
218
219     @Test
220     public void testStartOperationAsync_testSuccessfulCompletion() throws Exception {
221         final int origCount = 30;
222         oper.setVfCount(origCount);
223
224         // use a real executor
225         params = params.toBuilder().executor(ForkJoinPool.commonPool()).build();
226
227         oper = new MyOperation(params, config) {
228             @Override
229             public long getPollWaitMs() {
230                 return 1;
231             }
232         };
233
234         CompletableFuture<OperationOutcome> future2 = oper.start();
235
236         outcome = future2.get(5, TimeUnit.SECONDS);
237         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
238
239         SoResponse resp = outcome.getResponse();
240         assertNotNull(resp);
241         assertEquals(REQ_ID.toString(), resp.getRequestReferences().getRequestId());
242
243         assertEquals(origCount - 1, oper.getVfCount());
244     }
245
246     /**
247      * Tests startOperationAsync() when polling is required.
248      */
249     @Test
250     public void testStartOperationAsyncWithPolling() throws Exception {
251
252         // indicate that the response was incomplete
253         configureResponse(coder.encode(response).replace("COMPLETE", "incomplete"));
254
255         when(rawResponse.getStatus()).thenReturn(500, 500, 500, 200, 200);
256         when(client.get(any(), any(), any())).thenAnswer(provideResponse(rawResponse));
257
258         // use a real executor
259         params = params.toBuilder().executor(ForkJoinPool.commonPool()).build();
260
261         oper = new MyOperation(params, config) {
262             @Override
263             public long getPollWaitMs() {
264                 return 1;
265             }
266         };
267
268         CompletableFuture<OperationOutcome> future2 = oper.start();
269
270         outcome = future2.get(5, TimeUnit.SECONDS);
271         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
272     }
273
274     @Test
275     public void testMakeRequest() throws CoderException {
276         Pair<String, SoRequest> pair = oper.makeRequest();
277
278         assertEquals("/my-service-instance-id/vnfs/my-vnf-id/vfModules/null", pair.getLeft());
279
280         verifyRequest("VfModuleDelete.json", pair.getRight());
281     }
282
283     @Test
284     public void testDelete() throws Exception {
285         SoRequest req = new SoRequest();
286         req.setRequestId(REQ_ID);
287
288         Map<String, Object> headers = Map.of("key-A", "value-A");
289
290         String reqText = oper.prettyPrint(req);
291
292         final CompletableFuture<Response> delFuture =
293                         oper.delete("my-uri", headers, MediaType.APPLICATION_JSON, reqText, callback);
294
295         ArgumentCaptor<HttpRequest> reqCaptor = ArgumentCaptor.forClass(HttpRequest.class);
296         verify(javaClient).sendAsync(reqCaptor.capture(), any());
297
298         HttpRequest req2 = reqCaptor.getValue();
299         assertEquals("http://my-host:6969/my-uri", req2.uri().toString());
300         assertEquals("DELETE", req2.method());
301
302         HttpHeaders headers2 = req2.headers();
303         assertEquals("value-A", headers2.firstValue("key-A").orElse("missing-key"));
304         assertEquals(MediaType.APPLICATION_JSON, headers2.firstValue("Content-type").orElse("missing-key"));
305
306         assertTrue(delFuture.isDone());
307         Response resp = delFuture.get();
308
309         verify(callback).completed(resp);
310
311         assertEquals(200, resp.getStatus());
312
313         SoResponse resp2 = resp.readEntity(SoResponse.class);
314         assertEquals(SoOperation.COMPLETE, resp2.getRequest().getRequestStatus().getRequestState());
315     }
316
317     /**
318      * Tests delete() when an exception is thrown in the future.
319      */
320     @Test
321     @SuppressWarnings("unchecked")
322     public void testDeleteException() throws Exception {
323         Throwable thrown = new IllegalStateException(EXPECTED_EXCEPTION);
324
325         // need a new future, with an exception
326         javaFuture = CompletableFuture.failedFuture(thrown);
327         when(javaClient.sendAsync(any(), any(BodyHandlers.ofString().getClass()))).thenReturn(javaFuture);
328
329         SoRequest req = new SoRequest();
330         req.setRequestId(REQ_ID);
331
332         String reqText = oper.prettyPrint(req);
333
334         CompletableFuture<Response> delFuture =
335                         oper.delete("/my-uri", Map.of(), MediaType.APPLICATION_JSON, reqText, callback);
336
337         assertTrue(delFuture.isCompletedExceptionally());
338
339         ArgumentCaptor<Throwable> thrownCaptor = ArgumentCaptor.forClass(Throwable.class);
340         verify(callback).failed(thrownCaptor.capture());
341         assertSame(thrown, thrownCaptor.getValue().getCause());
342     }
343
344     /**
345      * Tests addAuthHeader() when there is a username, but no password.
346      */
347     @Test
348     public void testAddAuthHeader() {
349         Builder builder = mock(Builder.class);
350         when(client.getUserName()).thenReturn("the-user");
351         when(client.getPassword()).thenReturn("the-password");
352         oper.addAuthHeader(builder);
353
354         ArgumentCaptor<String> keyCaptor = ArgumentCaptor.forClass(String.class);
355         ArgumentCaptor<String> valueCaptor = ArgumentCaptor.forClass(String.class);
356
357         verify(builder).header(keyCaptor.capture(), valueCaptor.capture());
358
359         assertEquals("Authorization", keyCaptor.getValue());
360
361         String encoded = Base64.getEncoder().encodeToString("the-user:the-password".getBytes(StandardCharsets.UTF_8));
362         assertEquals("Basic " + encoded, valueCaptor.getValue());
363     }
364
365     /**
366      * Tests addAuthHeader() when there is no username.
367      */
368     @Test
369     public void testAddAuthHeaderNoUser() {
370         Builder builder = mock(Builder.class);
371         when(client.getPassword()).thenReturn("world");
372         oper.addAuthHeader(builder);
373         verify(builder, never()).header(any(), any());
374
375         // repeat with empty username
376         when(client.getUserName()).thenReturn("");
377         oper.addAuthHeader(builder);
378         verify(builder, never()).header(any(), any());
379     }
380
381     /**
382      * Tests addAuthHeader() when there is a username, but no password.
383      */
384     @Test
385     public void testAddAuthHeaderUserOnly() {
386         Builder builder = mock(Builder.class);
387         when(client.getUserName()).thenReturn("my-user");
388         oper.addAuthHeader(builder);
389
390         ArgumentCaptor<String> keyCaptor = ArgumentCaptor.forClass(String.class);
391         ArgumentCaptor<String> valueCaptor = ArgumentCaptor.forClass(String.class);
392
393         verify(builder).header(keyCaptor.capture(), valueCaptor.capture());
394
395         assertEquals("Authorization", keyCaptor.getValue());
396
397         String encoded = Base64.getEncoder().encodeToString("my-user:".getBytes(StandardCharsets.UTF_8));
398         assertEquals("Basic " + encoded, valueCaptor.getValue());
399     }
400
401     @Test
402     public void testMakeHttpClient() {
403         // must use a real operation to invoke this method
404         assertNotNull(new MyOperation(params, config).makeHttpClient());
405     }
406
407
408     @Override
409     protected void makeContext() {
410         super.makeContext();
411
412         AaiCqResponse cq = mock(AaiCqResponse.class);
413
414         GenericVnf vnf = new GenericVnf();
415         when(cq.getGenericVnfByVfModuleModelInvariantId(MODEL_INVAR_ID)).thenReturn(vnf);
416         vnf.setVnfId(VNF_ID);
417
418         ServiceInstance instance = new ServiceInstance();
419         when(cq.getServiceInstance()).thenReturn(instance);
420         instance.setServiceInstanceId(SVC_INSTANCE_ID);
421
422         when(cq.getDefaultTenant()).thenReturn(new Tenant());
423         when(cq.getDefaultCloudRegion()).thenReturn(new CloudRegion());
424
425         ModelVer modelVers = new ModelVer();
426         when(cq.getModelVerByVersionId(any())).thenReturn(modelVers);
427         modelVers.setModelName(MODEL_NAME2);
428         modelVers.setModelVersion(MODEL_VERS2);
429
430         params.getContext().setProperty(AaiCqResponse.CONTEXT_KEY, cq);
431     }
432
433     private void initHostPort() {
434         when(client.getBaseUrl()).thenReturn("http://my-host:6969/");
435     }
436
437     @SuppressWarnings("unchecked")
438     private void configureResponse(String responseText) throws CoderException {
439         // indicate that the response was completed
440         when(javaResp.statusCode()).thenReturn(200);
441         when(javaResp.body()).thenReturn(responseText);
442
443         javaFuture = CompletableFuture.completedFuture(javaResp);
444         when(javaClient.sendAsync(any(), any(BodyHandlers.ofString().getClass()))).thenReturn(javaFuture);
445     }
446
447     private class MyOperation extends VfModuleDelete {
448
449         public MyOperation(ControlLoopOperationParams params, HttpPollingConfig config) {
450             super(params, config);
451         }
452
453         @Override
454         protected java.net.http.HttpClient makeHttpClient() {
455             return javaClient;
456         }
457     }
458 }