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