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