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