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