2 * ============LICENSE_START=======================================================
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, 2024 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
13 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
23 package org.onap.policy.controlloop.actor.so;
25 import static org.assertj.core.api.Assertions.assertThat;
26 import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
27 import static org.junit.jupiter.api.Assertions.assertEquals;
28 import static org.junit.jupiter.api.Assertions.assertInstanceOf;
29 import static org.junit.jupiter.api.Assertions.assertNotNull;
30 import static org.junit.jupiter.api.Assertions.assertSame;
31 import static org.junit.jupiter.api.Assertions.assertTrue;
32 import static org.mockito.ArgumentMatchers.any;
33 import static org.mockito.Mockito.lenient;
34 import static org.mockito.Mockito.mock;
35 import static org.mockito.Mockito.never;
36 import static org.mockito.Mockito.verify;
38 import jakarta.ws.rs.client.InvocationCallback;
39 import jakarta.ws.rs.core.MediaType;
40 import jakarta.ws.rs.core.Response;
41 import java.net.http.HttpHeaders;
42 import java.net.http.HttpRequest;
43 import java.net.http.HttpRequest.Builder;
44 import java.net.http.HttpResponse;
45 import java.net.http.HttpResponse.BodyHandlers;
46 import java.nio.charset.StandardCharsets;
47 import java.util.Base64;
48 import java.util.List;
50 import java.util.concurrent.CompletableFuture;
51 import java.util.concurrent.ForkJoinPool;
52 import java.util.concurrent.TimeUnit;
53 import org.apache.commons.lang3.tuple.Pair;
54 import org.junit.jupiter.api.AfterAll;
55 import org.junit.jupiter.api.BeforeAll;
56 import org.junit.jupiter.api.BeforeEach;
57 import org.junit.jupiter.api.Test;
58 import org.junit.jupiter.api.extension.ExtendWith;
59 import org.mockito.ArgumentCaptor;
60 import org.mockito.Mock;
61 import org.mockito.junit.jupiter.MockitoExtension;
62 import org.onap.aai.domain.yang.CloudRegion;
63 import org.onap.aai.domain.yang.GenericVnf;
64 import org.onap.aai.domain.yang.ServiceInstance;
65 import org.onap.aai.domain.yang.Tenant;
66 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
67 import org.onap.policy.common.utils.coder.CoderException;
68 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
69 import org.onap.policy.controlloop.actorserviceprovider.OperationProperties;
70 import org.onap.policy.controlloop.actorserviceprovider.OperationResult;
71 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
72 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpPollingConfig;
73 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpPollingParams;
74 import org.onap.policy.so.SoRequest;
75 import org.onap.policy.so.SoResponse;
77 @ExtendWith(MockitoExtension.class)
78 class VfModuleDeleteTest extends BasicSoOperation {
79 private static final String EXPECTED_EXCEPTION = "expected exception";
80 private static final String SVC_INSTANCE_ID = "my-service-instance-id";
81 private static final String VNF_ID = "my-vnf-id";
84 private java.net.http.HttpClient javaClient;
86 private HttpResponse<String> javaResp;
88 private InvocationCallback<Response> callback;
90 private CompletableFuture<HttpResponse<String>> javaFuture;
91 private VfModuleDelete oper;
93 VfModuleDeleteTest() {
94 super(DEFAULT_ACTOR, VfModuleDelete.NAME);
98 static void setUpBeforeClass() throws Exception {
103 static void tearDownAfterClass() {
112 void setUp() throws Exception {
117 configureResponse(coder.encode(response));
119 oper = new MyOperation(params, config);
125 * Tests "success" case with simulator.
128 void testSuccess() throws Exception {
129 HttpPollingParams opParams = HttpPollingParams.builder().clientName(MY_CLIENT).path("serviceInstances/v7")
130 .pollPath("orchestrationRequests/v5/").maxPolls(2).build();
131 config = new HttpPollingConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory());
133 params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor).build();
135 oper = new VfModuleDelete(params, config);
140 outcome = oper.start().get();
141 assertEquals(OperationResult.SUCCESS, outcome.getResult());
142 assertInstanceOf(SoResponse.class, outcome.getResponse());
144 int count = oper.getProperty(OperationProperties.DATA_VF_COUNT);
145 assertEquals(VF_COUNT - 1, count);
149 void testConstructor() {
150 assertEquals(DEFAULT_ACTOR, oper.getActorName());
151 assertEquals(VfModuleDelete.NAME, oper.getName());
152 assertTrue(oper.isUsePolling());
154 // verify that target validation is done
155 params = params.toBuilder().targetType(null).build();
156 assertThatIllegalArgumentException().isThrownBy(() -> new MyOperation(params, config))
157 .withMessageContaining("Target information");
161 void testGetPropertyNames() {
163 assertThat(oper.getPropertyNames()).isEqualTo(
165 OperationProperties.AAI_SERVICE,
166 OperationProperties.AAI_VNF,
167 OperationProperties.AAI_DEFAULT_CLOUD_REGION,
168 OperationProperties.AAI_DEFAULT_TENANT,
169 OperationProperties.DATA_VF_COUNT));
174 void testStartOperationAsync_testSuccessfulCompletion() throws Exception {
175 // use a real executor
176 params = params.toBuilder().executor(ForkJoinPool.commonPool()).build();
178 oper = new MyOperation(params, config) {
180 public long getPollWaitMs() {
187 final int origCount = 30;
188 oper.setVfCount(origCount);
190 CompletableFuture<OperationOutcome> future2 = oper.start();
192 outcome = future2.get(5, TimeUnit.SECONDS);
193 assertEquals(OperationResult.SUCCESS, outcome.getResult());
195 SoResponse resp = outcome.getResponse();
197 assertEquals(REQ_ID.toString(), resp.getRequestReferences().getRequestId());
199 assertEquals(origCount - 1, oper.getVfCount());
203 * Tests startOperationAsync() when polling is required.
206 void testStartOperationAsyncWithPolling() throws Exception {
208 // indicate that the response was incomplete
209 configureResponse(coder.encode(response).replace("COMPLETE", "incomplete"));
211 lenient().when(rawResponse.getStatus()).thenReturn(500, 500, 500, 200, 200);
212 lenient().when(client.get(any(), any(), any())).thenAnswer(provideResponse(rawResponse));
214 // use a real executor
215 params = params.toBuilder().executor(ForkJoinPool.commonPool()).build();
217 oper = new MyOperation(params, config) {
219 public long getPollWaitMs() {
226 CompletableFuture<OperationOutcome> future2 = oper.start();
228 outcome = future2.get(5, TimeUnit.SECONDS);
229 assertEquals(OperationResult.SUCCESS, outcome.getResult());
233 void testMakeRequest() throws CoderException {
234 Pair<String, SoRequest> pair = oper.makeRequest();
236 assertEquals("/my-service-instance-id/vnfs/my-vnf-id/vfModules/null", pair.getLeft());
238 verifyRequest("VfModuleDelete.json", pair.getRight());
242 void testDelete() throws Exception {
243 SoRequest req = new SoRequest();
244 req.setRequestId(REQ_ID);
246 Map<String, Object> headers = Map.of("key-A", "value-A");
248 String reqText = oper.prettyPrint(req);
250 final CompletableFuture<Response> delFuture =
251 oper.delete("my-uri", headers, MediaType.APPLICATION_JSON, reqText, callback);
253 ArgumentCaptor<HttpRequest> reqCaptor = ArgumentCaptor.forClass(HttpRequest.class);
254 verify(javaClient).sendAsync(reqCaptor.capture(), any());
256 HttpRequest req2 = reqCaptor.getValue();
257 assertEquals("http://my-host:6969/my-uri", req2.uri().toString());
258 assertEquals("DELETE", req2.method());
260 HttpHeaders headers2 = req2.headers();
261 assertEquals("value-A", headers2.firstValue("key-A").orElse("missing-key"));
262 assertEquals(MediaType.APPLICATION_JSON, headers2.firstValue("Content-type").orElse("missing-key"));
264 assertTrue(delFuture.isDone());
265 Response resp = delFuture.get();
267 verify(callback).completed(resp);
269 assertEquals(200, resp.getStatus());
271 SoResponse resp2 = resp.readEntity(SoResponse.class);
272 assertEquals(SoOperation.COMPLETE, resp2.getRequest().getRequestStatus().getRequestState());
276 * Tests delete() when an exception is thrown in the future.
279 @SuppressWarnings("unchecked")
280 void testDeleteException() {
281 Throwable thrown = new IllegalStateException(EXPECTED_EXCEPTION);
283 // need a new future, with an exception
284 javaFuture = CompletableFuture.failedFuture(thrown);
285 lenient().when(javaClient.sendAsync(any(), any(BodyHandlers.ofString().getClass()))).thenReturn(javaFuture);
287 SoRequest req = new SoRequest();
288 req.setRequestId(REQ_ID);
290 String reqText = oper.prettyPrint(req);
292 CompletableFuture<Response> delFuture =
293 oper.delete("/my-uri", Map.of(), MediaType.APPLICATION_JSON, reqText, callback);
295 assertTrue(delFuture.isCompletedExceptionally());
297 ArgumentCaptor<Throwable> thrownCaptor = ArgumentCaptor.forClass(Throwable.class);
298 verify(callback).failed(thrownCaptor.capture());
299 assertSame(thrown, thrownCaptor.getValue().getCause());
303 * Tests addAuthHeader() when there is a username, but no password.
306 void testAddAuthHeader() {
307 Builder builder = mock(Builder.class);
308 lenient().when(client.getUserName()).thenReturn("the-user");
309 lenient().when(client.getPassword()).thenReturn("the-password");
310 oper.addAuthHeader(builder);
312 ArgumentCaptor<String> keyCaptor = ArgumentCaptor.forClass(String.class);
313 ArgumentCaptor<String> valueCaptor = ArgumentCaptor.forClass(String.class);
315 verify(builder).header(keyCaptor.capture(), valueCaptor.capture());
317 assertEquals("Authorization", keyCaptor.getValue());
319 String encoded = Base64.getEncoder().encodeToString("the-user:the-password".getBytes(StandardCharsets.UTF_8));
320 assertEquals("Basic " + encoded, valueCaptor.getValue());
324 * Tests addAuthHeader() when there is no username.
327 void testAddAuthHeaderNoUser() {
328 Builder builder = mock(Builder.class);
329 lenient().when(client.getPassword()).thenReturn("world");
330 oper.addAuthHeader(builder);
331 verify(builder, never()).header(any(), any());
333 // repeat with empty username
334 lenient().when(client.getUserName()).thenReturn("");
335 oper.addAuthHeader(builder);
336 verify(builder, never()).header(any(), any());
340 * Tests addAuthHeader() when there is a username, but no password.
343 void testAddAuthHeaderUserOnly() {
344 Builder builder = mock(Builder.class);
345 lenient().when(client.getUserName()).thenReturn("my-user");
346 oper.addAuthHeader(builder);
348 ArgumentCaptor<String> keyCaptor = ArgumentCaptor.forClass(String.class);
349 ArgumentCaptor<String> valueCaptor = ArgumentCaptor.forClass(String.class);
351 verify(builder).header(keyCaptor.capture(), valueCaptor.capture());
353 assertEquals("Authorization", keyCaptor.getValue());
355 String encoded = Base64.getEncoder().encodeToString("my-user:".getBytes(StandardCharsets.UTF_8));
356 assertEquals("Basic " + encoded, valueCaptor.getValue());
360 * Tests makeRequest() when a property is missing.
363 void testMakeRequestMissingProperty() {
366 ServiceInstance instance = new ServiceInstance();
367 oper.setProperty(OperationProperties.AAI_SERVICE, instance);
369 assertThatIllegalArgumentException().isThrownBy(() -> oper.makeRequest())
370 .withMessageContaining("missing service instance ID");
374 void testMakeHttpClient() {
375 // must use a real operation to invoke this method
376 assertNotNull(new MyOperation(params, config).makeHttpClient());
379 private void initHostPort() {
380 lenient().when(client.getBaseUrl()).thenReturn("http://my-host:6969/");
383 @SuppressWarnings("unchecked")
384 private void configureResponse(String responseText) {
385 // indicate that the response was completed
386 lenient().when(javaResp.statusCode()).thenReturn(200);
387 lenient().when(javaResp.body()).thenReturn(responseText);
389 javaFuture = CompletableFuture.completedFuture(javaResp);
390 lenient().when(javaClient.sendAsync(any(), any(BodyHandlers.ofString().getClass()))).thenReturn(javaFuture);
393 private class MyOperation extends VfModuleDelete {
395 MyOperation(ControlLoopOperationParams params, HttpPollingConfig config) {
396 super(params, config);
400 protected java.net.http.HttpClient makeHttpClient() {
405 private void loadProperties() {
406 // set the properties
407 ServiceInstance instance = new ServiceInstance();
408 instance.setServiceInstanceId(SVC_INSTANCE_ID);
409 oper.setProperty(OperationProperties.AAI_SERVICE, instance);
411 GenericVnf vnf = new GenericVnf();
412 vnf.setVnfId(VNF_ID);
413 oper.setProperty(OperationProperties.AAI_VNF, vnf);
415 CloudRegion cloudRegion = new CloudRegion();
416 cloudRegion.setCloudRegionId("my-cloud-id");
417 oper.setProperty(OperationProperties.AAI_DEFAULT_CLOUD_REGION, cloudRegion);
419 Tenant tenant = new Tenant();
420 tenant.setTenantId("my-tenant-id");
421 oper.setProperty(OperationProperties.AAI_DEFAULT_TENANT, tenant);
423 oper.setProperty(OperationProperties.DATA_VF_COUNT, VF_COUNT);