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