Merge "Add version to compliant operational policies"
[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         Integer newCount = (Integer) payload.get(VfModuleDelete.PAYLOAD_KEY_VF_COUNT);
170         assertNotNull(newCount);
171         assertEquals(origCount - 1, newCount.intValue());
172     }
173
174     @Test
175     public void testStartOperationAsync_testSuccessfulCompletion() throws Exception {
176         final int origCount = 30;
177         oper.setVfCount(origCount);
178
179         // use a real executor
180         params = params.toBuilder().executor(ForkJoinPool.commonPool()).build();
181
182         oper = new MyOperation(params, config) {
183             @Override
184             public long getWaitMsGet() {
185                 return 1;
186             }
187         };
188
189         CompletableFuture<OperationOutcome> future2 = oper.start();
190
191         outcome = future2.get(5, TimeUnit.SECONDS);
192         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
193
194         assertEquals(origCount - 1, oper.getVfCount());
195     }
196
197     /**
198      * Tests startOperationAsync() when "get" operations are required.
199      */
200     @Test
201     public void testStartOperationAsyncWithGets() throws Exception {
202
203         // indicate that the response was incomplete
204         configureResponse(coder.encode(response).replace("COMPLETE", "incomplete"));
205
206         when(rawResponse.getStatus()).thenReturn(500, 500, 500, 200, 200);
207         when(client.get(any(), any(), any())).thenAnswer(provideResponse(rawResponse));
208
209         // use a real executor
210         params = params.toBuilder().executor(ForkJoinPool.commonPool()).build();
211
212         oper = new MyOperation(params, config) {
213             @Override
214             public long getWaitMsGet() {
215                 return 1;
216             }
217         };
218
219         CompletableFuture<OperationOutcome> future2 = oper.start();
220
221         outcome = future2.get(5, TimeUnit.SECONDS);
222         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
223     }
224
225     @Test
226     public void testMakeRequest() throws CoderException {
227         Pair<String, SoRequest> pair = oper.makeRequest();
228
229         assertEquals("/my-service-instance-id/vnfs/my-vnf-id/vfModules/null", pair.getLeft());
230
231         verifyRequest("VfModuleDelete.json", pair.getRight());
232     }
233
234     @Test
235     public void testDelete() throws Exception {
236         SoRequest req = new SoRequest();
237         req.setRequestId(REQ_ID);
238
239         Map<String, Object> headers = Map.of("key-A", "value-A");
240
241         final CompletableFuture<Response> delFuture =
242                         oper.delete("my-uri", headers, MediaType.APPLICATION_JSON, req, callback);
243
244         ArgumentCaptor<HttpRequest> reqCaptor = ArgumentCaptor.forClass(HttpRequest.class);
245         verify(javaClient).sendAsync(reqCaptor.capture(), any());
246
247         HttpRequest req2 = reqCaptor.getValue();
248         assertEquals("http://my-host:6969/my-uri", req2.uri().toString());
249         assertEquals("DELETE", req2.method());
250
251         HttpHeaders headers2 = req2.headers();
252         assertEquals("value-A", headers2.firstValue("key-A").orElse("missing-key"));
253         assertEquals(MediaType.APPLICATION_JSON, headers2.firstValue("Content-type").orElse("missing-key"));
254
255         assertTrue(delFuture.isDone());
256         Response resp = delFuture.get();
257
258         verify(callback).completed(resp);
259
260         assertEquals(200, resp.getStatus());
261
262         SoResponse resp2 = resp.readEntity(SoResponse.class);
263         assertEquals(SoOperation.COMPLETE, resp2.getRequest().getRequestStatus().getRequestState());
264     }
265
266     /**
267      * Tests delete() when an exception is thrown in the future.
268      */
269     @Test
270     @SuppressWarnings("unchecked")
271     public void testDeleteException() throws Exception {
272         Throwable thrown = new IllegalStateException(EXPECTED_EXCEPTION);
273
274         // need a new future, with an exception
275         javaFuture = CompletableFuture.failedFuture(thrown);
276         when(javaClient.sendAsync(any(), any(BodyHandlers.ofString().getClass()))).thenReturn(javaFuture);
277
278         SoRequest req = new SoRequest();
279         req.setRequestId(REQ_ID);
280
281         CompletableFuture<Response> delFuture =
282                         oper.delete("/my-uri", Map.of(), MediaType.APPLICATION_JSON, req, callback);
283
284         assertTrue(delFuture.isCompletedExceptionally());
285
286         ArgumentCaptor<Throwable> thrownCaptor = ArgumentCaptor.forClass(Throwable.class);
287         verify(callback).failed(thrownCaptor.capture());
288         assertSame(thrown, thrownCaptor.getValue().getCause());
289     }
290
291     @Test
292     public void testEncodeBody() {
293         // try when request is already a string
294         assertEquals("hello", oper.encodeRequest("hello"));
295
296         // try with a real request
297         SoRequest req = new SoRequest();
298         req.setRequestId(REQ_ID);
299         assertEquals("{\"requestId\":\"" + REQ_ID.toString() + "\"}", oper.encodeRequest(req));
300
301         // coder throws an exception
302         oper = new MyOperation(params, config) {
303             @Override
304             protected Coder makeCoder() {
305                 return new StandardCoder() {
306                     @Override
307                     public String encode(Object object) throws CoderException {
308                         throw new CoderException(EXPECTED_EXCEPTION);
309                     }
310                 };
311             }
312         };
313
314         assertThatIllegalArgumentException().isThrownBy(() -> oper.encodeRequest(req))
315                         .withMessage("cannot encode request");
316     }
317
318     /**
319      * Tests addAuthHeader() when there is a username, but no password.
320      */
321     @Test
322     public void testAddAuthHeader() {
323         Builder builder = mock(Builder.class);
324         when(client.getUserName()).thenReturn("the-user");
325         when(client.getPassword()).thenReturn("the-password");
326         oper.addAuthHeader(builder);
327
328         ArgumentCaptor<String> keyCaptor = ArgumentCaptor.forClass(String.class);
329         ArgumentCaptor<String> valueCaptor = ArgumentCaptor.forClass(String.class);
330
331         verify(builder).header(keyCaptor.capture(), valueCaptor.capture());
332
333         assertEquals("Authorization", keyCaptor.getValue());
334
335         String encoded = Base64.getEncoder().encodeToString("the-user:the-password".getBytes(StandardCharsets.UTF_8));
336         assertEquals("Basic " + encoded, valueCaptor.getValue());
337     }
338
339     /**
340      * Tests addAuthHeader() when there is no username.
341      */
342     @Test
343     public void testAddAuthHeaderNoUser() {
344         Builder builder = mock(Builder.class);
345         when(client.getPassword()).thenReturn("world");
346         oper.addAuthHeader(builder);
347         verify(builder, never()).header(any(), any());
348
349         // repeat with empty username
350         when(client.getUserName()).thenReturn("");
351         oper.addAuthHeader(builder);
352         verify(builder, never()).header(any(), any());
353     }
354
355     /**
356      * Tests addAuthHeader() when there is a username, but no password.
357      */
358     @Test
359     public void testAddAuthHeaderUserOnly() {
360         Builder builder = mock(Builder.class);
361         when(client.getUserName()).thenReturn("my-user");
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("my-user:".getBytes(StandardCharsets.UTF_8));
372         assertEquals("Basic " + encoded, valueCaptor.getValue());
373     }
374
375     @Test
376     public void testMakeHttpClient() {
377         // must use a real operation to invoke this method
378         assertNotNull(new VfModuleDelete(params, config).makeHttpClient());
379     }
380
381
382     @Override
383     protected void makeContext() {
384         super.makeContext();
385
386         AaiCqResponse cq = mock(AaiCqResponse.class);
387
388         GenericVnf vnf = new GenericVnf();
389         when(cq.getGenericVnfByVfModuleModelInvariantId(MODEL_INVAR_ID)).thenReturn(vnf);
390         vnf.setVnfId(VNF_ID);
391
392         ServiceInstance instance = new ServiceInstance();
393         when(cq.getServiceInstance()).thenReturn(instance);
394         instance.setServiceInstanceId(SVC_INSTANCE_ID);
395
396         when(cq.getDefaultTenant()).thenReturn(new Tenant());
397         when(cq.getDefaultCloudRegion()).thenReturn(new CloudRegion());
398
399         ModelVer modelVers = new ModelVer();
400         when(cq.getModelVerByVersionId(any())).thenReturn(modelVers);
401         modelVers.setModelName(MODEL_NAME2);
402         modelVers.setModelVersion(MODEL_VERS2);
403
404         params.getContext().setProperty(AaiCqResponse.CONTEXT_KEY, cq);
405     }
406
407     private void initHostPort() {
408         when(client.getBaseUrl()).thenReturn("http://my-host:6969/");
409     }
410
411     @SuppressWarnings("unchecked")
412     private void configureResponse(String responseText) throws CoderException {
413         // indicate that the response was completed
414         when(javaResp.statusCode()).thenReturn(200);
415         when(javaResp.body()).thenReturn(responseText);
416
417         javaFuture = CompletableFuture.completedFuture(javaResp);
418         when(javaClient.sendAsync(any(), any(BodyHandlers.ofString().getClass()))).thenReturn(javaFuture);
419     }
420
421     private class MyOperation extends VfModuleDelete {
422
423         public MyOperation(ControlLoopOperationParams params, HttpConfig config) {
424             super(params, config);
425         }
426
427         @Override
428         protected java.net.http.HttpClient makeHttpClient() {
429             return javaClient;
430         }
431     }
432 }