Java 17 Upgrade
[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-2021 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2020 Wipro Limited.
7  * Modifications Copyright (C) 2023 Nordix Foundation.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.controlloop.actor.so;
24
25 import static org.assertj.core.api.Assertions.assertThat;
26 import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
27 import static org.junit.Assert.assertEquals;
28 import static org.junit.Assert.assertNotNull;
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.lenient;
33 import static org.mockito.Mockito.mock;
34 import static org.mockito.Mockito.never;
35 import static org.mockito.Mockito.verify;
36
37 import jakarta.ws.rs.client.InvocationCallback;
38 import jakarta.ws.rs.core.MediaType;
39 import jakarta.ws.rs.core.Response;
40 import java.net.http.HttpHeaders;
41 import java.net.http.HttpRequest;
42 import java.net.http.HttpRequest.Builder;
43 import java.net.http.HttpResponse;
44 import java.net.http.HttpResponse.BodyHandlers;
45 import java.nio.charset.StandardCharsets;
46 import java.util.Base64;
47 import java.util.List;
48 import java.util.Map;
49 import java.util.concurrent.CompletableFuture;
50 import java.util.concurrent.ForkJoinPool;
51 import java.util.concurrent.TimeUnit;
52 import org.apache.commons.lang3.tuple.Pair;
53 import org.junit.AfterClass;
54 import org.junit.Before;
55 import org.junit.BeforeClass;
56 import org.junit.Test;
57 import org.junit.runner.RunWith;
58 import org.mockito.ArgumentCaptor;
59 import org.mockito.Mock;
60 import org.mockito.junit.MockitoJUnitRunner;
61 import org.onap.aai.domain.yang.CloudRegion;
62 import org.onap.aai.domain.yang.GenericVnf;
63 import org.onap.aai.domain.yang.ServiceInstance;
64 import org.onap.aai.domain.yang.Tenant;
65 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
66 import org.onap.policy.common.utils.coder.CoderException;
67 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
68 import org.onap.policy.controlloop.actorserviceprovider.OperationProperties;
69 import org.onap.policy.controlloop.actorserviceprovider.OperationResult;
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.so.SoRequest;
74 import org.onap.policy.so.SoResponse;
75
76 @RunWith(MockitoJUnitRunner.class)
77 public class VfModuleDeleteTest extends BasicSoOperation {
78     private static final String EXPECTED_EXCEPTION = "expected exception";
79     private static final String SVC_INSTANCE_ID = "my-service-instance-id";
80     private static final String VNF_ID = "my-vnf-id";
81
82     @Mock
83     private java.net.http.HttpClient javaClient;
84     @Mock
85     private HttpResponse<String> javaResp;
86     @Mock
87     private InvocationCallback<Response> callback;
88
89     private CompletableFuture<HttpResponse<String>> javaFuture;
90     private VfModuleDelete oper;
91
92     public VfModuleDeleteTest() {
93         super(DEFAULT_ACTOR, VfModuleDelete.NAME);
94     }
95
96     @BeforeClass
97     public static void setUpBeforeClass() throws Exception {
98         initBeforeClass();
99     }
100
101     @AfterClass
102     public static void tearDownAfterClass() {
103         destroyAfterClass();
104     }
105
106     /**
107      * Sets up.
108      */
109     @Override
110     @Before
111     public void setUp() throws Exception {
112         super.setUp();
113
114         initHostPort();
115
116         configureResponse(coder.encode(response));
117
118         oper = new MyOperation(params, config);
119
120         loadProperties();
121     }
122
123     /**
124      * Tests "success" case with simulator.
125      */
126     @Test
127     public void testSuccess() throws Exception {
128         HttpPollingParams opParams = HttpPollingParams.builder().clientName(MY_CLIENT).path("serviceInstances/v7")
129                         .pollPath("orchestrationRequests/v5/").maxPolls(2).build();
130         config = new HttpPollingConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory());
131
132         params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor).build();
133
134         oper = new VfModuleDelete(params, config);
135
136         loadProperties();
137
138         // run the operation
139         outcome = oper.start().get();
140         assertEquals(OperationResult.SUCCESS, outcome.getResult());
141         assertTrue(outcome.getResponse() instanceof SoResponse);
142
143         int count = oper.getProperty(OperationProperties.DATA_VF_COUNT);
144         assertEquals(VF_COUNT - 1, count);
145     }
146
147     @Test
148     public void testConstructor() {
149         assertEquals(DEFAULT_ACTOR, oper.getActorName());
150         assertEquals(VfModuleDelete.NAME, oper.getName());
151         assertTrue(oper.isUsePolling());
152
153         // verify that target validation is done
154         params = params.toBuilder().targetType(null).build();
155         assertThatIllegalArgumentException().isThrownBy(() -> new MyOperation(params, config))
156                         .withMessageContaining("Target information");
157     }
158
159     @Test
160     public void testGetPropertyNames() {
161         // @formatter:off
162         assertThat(oper.getPropertyNames()).isEqualTo(
163                         List.of(
164                             OperationProperties.AAI_SERVICE,
165                             OperationProperties.AAI_VNF,
166                             OperationProperties.AAI_DEFAULT_CLOUD_REGION,
167                             OperationProperties.AAI_DEFAULT_TENANT,
168                             OperationProperties.DATA_VF_COUNT));
169         // @formatter:on
170     }
171
172     @Test
173     public void testStartOperationAsync_testSuccessfulCompletion() throws Exception {
174         // use a real executor
175         params = params.toBuilder().executor(ForkJoinPool.commonPool()).build();
176
177         oper = new MyOperation(params, config) {
178             @Override
179             public long getPollWaitMs() {
180                 return 1;
181             }
182         };
183
184         loadProperties();
185
186         final int origCount = 30;
187         oper.setVfCount(origCount);
188
189         CompletableFuture<OperationOutcome> future2 = oper.start();
190
191         outcome = future2.get(5, TimeUnit.SECONDS);
192         assertEquals(OperationResult.SUCCESS, outcome.getResult());
193
194         SoResponse resp = outcome.getResponse();
195         assertNotNull(resp);
196         assertEquals(REQ_ID.toString(), resp.getRequestReferences().getRequestId());
197
198         assertEquals(origCount - 1, oper.getVfCount());
199     }
200
201     /**
202      * Tests startOperationAsync() when polling is required.
203      */
204     @Test
205     public void testStartOperationAsyncWithPolling() throws Exception {
206
207         // indicate that the response was incomplete
208         configureResponse(coder.encode(response).replace("COMPLETE", "incomplete"));
209
210         lenient().when(rawResponse.getStatus()).thenReturn(500, 500, 500, 200, 200);
211         lenient().when(client.get(any(), any(), any())).thenAnswer(provideResponse(rawResponse));
212
213         // use a real executor
214         params = params.toBuilder().executor(ForkJoinPool.commonPool()).build();
215
216         oper = new MyOperation(params, config) {
217             @Override
218             public long getPollWaitMs() {
219                 return 1;
220             }
221         };
222
223         loadProperties();
224
225         CompletableFuture<OperationOutcome> future2 = oper.start();
226
227         outcome = future2.get(5, TimeUnit.SECONDS);
228         assertEquals(OperationResult.SUCCESS, outcome.getResult());
229     }
230
231     @Test
232     public void testMakeRequest() throws CoderException {
233         Pair<String, SoRequest> pair = oper.makeRequest();
234
235         assertEquals("/my-service-instance-id/vnfs/my-vnf-id/vfModules/null", pair.getLeft());
236
237         verifyRequest("VfModuleDelete.json", pair.getRight());
238     }
239
240     @Test
241     public void testDelete() throws Exception {
242         SoRequest req = new SoRequest();
243         req.setRequestId(REQ_ID);
244
245         Map<String, Object> headers = Map.of("key-A", "value-A");
246
247         String reqText = oper.prettyPrint(req);
248
249         final CompletableFuture<Response> delFuture =
250                         oper.delete("my-uri", headers, MediaType.APPLICATION_JSON, reqText, 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         lenient().when(javaClient.sendAsync(any(), any(BodyHandlers.ofString().getClass()))).thenReturn(javaFuture);
285
286         SoRequest req = new SoRequest();
287         req.setRequestId(REQ_ID);
288
289         String reqText = oper.prettyPrint(req);
290
291         CompletableFuture<Response> delFuture =
292                         oper.delete("/my-uri", Map.of(), MediaType.APPLICATION_JSON, reqText, callback);
293
294         assertTrue(delFuture.isCompletedExceptionally());
295
296         ArgumentCaptor<Throwable> thrownCaptor = ArgumentCaptor.forClass(Throwable.class);
297         verify(callback).failed(thrownCaptor.capture());
298         assertSame(thrown, thrownCaptor.getValue().getCause());
299     }
300
301     /**
302      * Tests addAuthHeader() when there is a username, but no password.
303      */
304     @Test
305     public void testAddAuthHeader() {
306         Builder builder = mock(Builder.class);
307         lenient().when(client.getUserName()).thenReturn("the-user");
308         lenient().when(client.getPassword()).thenReturn("the-password");
309         oper.addAuthHeader(builder);
310
311         ArgumentCaptor<String> keyCaptor = ArgumentCaptor.forClass(String.class);
312         ArgumentCaptor<String> valueCaptor = ArgumentCaptor.forClass(String.class);
313
314         verify(builder).header(keyCaptor.capture(), valueCaptor.capture());
315
316         assertEquals("Authorization", keyCaptor.getValue());
317
318         String encoded = Base64.getEncoder().encodeToString("the-user:the-password".getBytes(StandardCharsets.UTF_8));
319         assertEquals("Basic " + encoded, valueCaptor.getValue());
320     }
321
322     /**
323      * Tests addAuthHeader() when there is no username.
324      */
325     @Test
326     public void testAddAuthHeaderNoUser() {
327         Builder builder = mock(Builder.class);
328         lenient().when(client.getPassword()).thenReturn("world");
329         oper.addAuthHeader(builder);
330         verify(builder, never()).header(any(), any());
331
332         // repeat with empty username
333         lenient().when(client.getUserName()).thenReturn("");
334         oper.addAuthHeader(builder);
335         verify(builder, never()).header(any(), any());
336     }
337
338     /**
339      * Tests addAuthHeader() when there is a username, but no password.
340      */
341     @Test
342     public void testAddAuthHeaderUserOnly() {
343         Builder builder = mock(Builder.class);
344         lenient().when(client.getUserName()).thenReturn("my-user");
345         oper.addAuthHeader(builder);
346
347         ArgumentCaptor<String> keyCaptor = ArgumentCaptor.forClass(String.class);
348         ArgumentCaptor<String> valueCaptor = ArgumentCaptor.forClass(String.class);
349
350         verify(builder).header(keyCaptor.capture(), valueCaptor.capture());
351
352         assertEquals("Authorization", keyCaptor.getValue());
353
354         String encoded = Base64.getEncoder().encodeToString("my-user:".getBytes(StandardCharsets.UTF_8));
355         assertEquals("Basic " + encoded, valueCaptor.getValue());
356     }
357
358     /**
359      * Tests makeRequest() when a property is missing.
360      */
361     @Test
362     public void testMakeRequestMissingProperty() throws Exception {
363         loadProperties();
364
365         ServiceInstance instance = new ServiceInstance();
366         oper.setProperty(OperationProperties.AAI_SERVICE, instance);
367
368         assertThatIllegalArgumentException().isThrownBy(() -> oper.makeRequest())
369                         .withMessageContaining("missing service instance ID");
370     }
371
372     @Test
373     public void testMakeHttpClient() {
374         // must use a real operation to invoke this method
375         assertNotNull(new MyOperation(params, config).makeHttpClient());
376     }
377
378     private void initHostPort() {
379         lenient().when(client.getBaseUrl()).thenReturn("http://my-host:6969/");
380     }
381
382     @SuppressWarnings("unchecked")
383     private void configureResponse(String responseText) throws CoderException {
384         // indicate that the response was completed
385         lenient().when(javaResp.statusCode()).thenReturn(200);
386         lenient().when(javaResp.body()).thenReturn(responseText);
387
388         javaFuture = CompletableFuture.completedFuture(javaResp);
389         lenient().when(javaClient.sendAsync(any(), any(BodyHandlers.ofString().getClass()))).thenReturn(javaFuture);
390     }
391
392     private class MyOperation extends VfModuleDelete {
393
394         public MyOperation(ControlLoopOperationParams params, HttpPollingConfig config) {
395             super(params, config);
396         }
397
398         @Override
399         protected java.net.http.HttpClient makeHttpClient() {
400             return javaClient;
401         }
402     }
403
404     private void loadProperties() {
405         // set the properties
406         ServiceInstance instance = new ServiceInstance();
407         instance.setServiceInstanceId(SVC_INSTANCE_ID);
408         oper.setProperty(OperationProperties.AAI_SERVICE, instance);
409
410         GenericVnf vnf = new GenericVnf();
411         vnf.setVnfId(VNF_ID);
412         oper.setProperty(OperationProperties.AAI_VNF, vnf);
413
414         CloudRegion cloudRegion = new CloudRegion();
415         cloudRegion.setCloudRegionId("my-cloud-id");
416         oper.setProperty(OperationProperties.AAI_DEFAULT_CLOUD_REGION, cloudRegion);
417
418         Tenant tenant = new Tenant();
419         tenant.setTenantId("my-tenant-id");
420         oper.setProperty(OperationProperties.AAI_DEFAULT_TENANT, tenant);
421
422         oper.setProperty(OperationProperties.DATA_VF_COUNT, VF_COUNT);
423     }
424 }