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