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