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 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.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;
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;
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;
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";
83 private java.net.http.HttpClient javaClient;
85 private HttpResponse<String> javaResp;
87 private InvocationCallback<Response> callback;
89 private CompletableFuture<HttpResponse<String>> javaFuture;
90 private VfModuleDelete oper;
92 public VfModuleDeleteTest() {
93 super(DEFAULT_ACTOR, VfModuleDelete.NAME);
97 public static void setUpBeforeClass() throws Exception {
102 public static void tearDownAfterClass() {
111 public void setUp() throws Exception {
116 configureResponse(coder.encode(response));
118 oper = new MyOperation(params, config);
124 * Tests "success" case with simulator.
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());
132 params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor).build();
134 oper = new VfModuleDelete(params, config);
139 outcome = oper.start().get();
140 assertEquals(OperationResult.SUCCESS, outcome.getResult());
141 assertTrue(outcome.getResponse() instanceof SoResponse);
143 int count = oper.getProperty(OperationProperties.DATA_VF_COUNT);
144 assertEquals(VF_COUNT - 1, count);
148 public void testConstructor() {
149 assertEquals(DEFAULT_ACTOR, oper.getActorName());
150 assertEquals(VfModuleDelete.NAME, oper.getName());
151 assertTrue(oper.isUsePolling());
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");
160 public void testGetPropertyNames() {
162 assertThat(oper.getPropertyNames()).isEqualTo(
164 OperationProperties.AAI_SERVICE,
165 OperationProperties.AAI_VNF,
166 OperationProperties.AAI_DEFAULT_CLOUD_REGION,
167 OperationProperties.AAI_DEFAULT_TENANT,
168 OperationProperties.DATA_VF_COUNT));
173 public void testStartOperationAsync_testSuccessfulCompletion() throws Exception {
174 // use a real executor
175 params = params.toBuilder().executor(ForkJoinPool.commonPool()).build();
177 oper = new MyOperation(params, config) {
179 public long getPollWaitMs() {
186 final int origCount = 30;
187 oper.setVfCount(origCount);
189 CompletableFuture<OperationOutcome> future2 = oper.start();
191 outcome = future2.get(5, TimeUnit.SECONDS);
192 assertEquals(OperationResult.SUCCESS, outcome.getResult());
194 SoResponse resp = outcome.getResponse();
196 assertEquals(REQ_ID.toString(), resp.getRequestReferences().getRequestId());
198 assertEquals(origCount - 1, oper.getVfCount());
202 * Tests startOperationAsync() when polling is required.
205 public void testStartOperationAsyncWithPolling() throws Exception {
207 // indicate that the response was incomplete
208 configureResponse(coder.encode(response).replace("COMPLETE", "incomplete"));
210 lenient().when(rawResponse.getStatus()).thenReturn(500, 500, 500, 200, 200);
211 lenient().when(client.get(any(), any(), any())).thenAnswer(provideResponse(rawResponse));
213 // use a real executor
214 params = params.toBuilder().executor(ForkJoinPool.commonPool()).build();
216 oper = new MyOperation(params, config) {
218 public long getPollWaitMs() {
225 CompletableFuture<OperationOutcome> future2 = oper.start();
227 outcome = future2.get(5, TimeUnit.SECONDS);
228 assertEquals(OperationResult.SUCCESS, outcome.getResult());
232 public void testMakeRequest() throws CoderException {
233 Pair<String, SoRequest> pair = oper.makeRequest();
235 assertEquals("/my-service-instance-id/vnfs/my-vnf-id/vfModules/null", pair.getLeft());
237 verifyRequest("VfModuleDelete.json", pair.getRight());
241 public void testDelete() throws Exception {
242 SoRequest req = new SoRequest();
243 req.setRequestId(REQ_ID);
245 Map<String, Object> headers = Map.of("key-A", "value-A");
247 String reqText = oper.prettyPrint(req);
249 final CompletableFuture<Response> delFuture =
250 oper.delete("my-uri", headers, MediaType.APPLICATION_JSON, reqText, callback);
252 ArgumentCaptor<HttpRequest> reqCaptor = ArgumentCaptor.forClass(HttpRequest.class);
253 verify(javaClient).sendAsync(reqCaptor.capture(), any());
255 HttpRequest req2 = reqCaptor.getValue();
256 assertEquals("http://my-host:6969/my-uri", req2.uri().toString());
257 assertEquals("DELETE", req2.method());
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"));
263 assertTrue(delFuture.isDone());
264 Response resp = delFuture.get();
266 verify(callback).completed(resp);
268 assertEquals(200, resp.getStatus());
270 SoResponse resp2 = resp.readEntity(SoResponse.class);
271 assertEquals(SoOperation.COMPLETE, resp2.getRequest().getRequestStatus().getRequestState());
275 * Tests delete() when an exception is thrown in the future.
278 @SuppressWarnings("unchecked")
279 public void testDeleteException() throws Exception {
280 Throwable thrown = new IllegalStateException(EXPECTED_EXCEPTION);
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);
286 SoRequest req = new SoRequest();
287 req.setRequestId(REQ_ID);
289 String reqText = oper.prettyPrint(req);
291 CompletableFuture<Response> delFuture =
292 oper.delete("/my-uri", Map.of(), MediaType.APPLICATION_JSON, reqText, callback);
294 assertTrue(delFuture.isCompletedExceptionally());
296 ArgumentCaptor<Throwable> thrownCaptor = ArgumentCaptor.forClass(Throwable.class);
297 verify(callback).failed(thrownCaptor.capture());
298 assertSame(thrown, thrownCaptor.getValue().getCause());
302 * Tests addAuthHeader() when there is a username, but no password.
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);
311 ArgumentCaptor<String> keyCaptor = ArgumentCaptor.forClass(String.class);
312 ArgumentCaptor<String> valueCaptor = ArgumentCaptor.forClass(String.class);
314 verify(builder).header(keyCaptor.capture(), valueCaptor.capture());
316 assertEquals("Authorization", keyCaptor.getValue());
318 String encoded = Base64.getEncoder().encodeToString("the-user:the-password".getBytes(StandardCharsets.UTF_8));
319 assertEquals("Basic " + encoded, valueCaptor.getValue());
323 * Tests addAuthHeader() when there is no username.
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());
332 // repeat with empty username
333 lenient().when(client.getUserName()).thenReturn("");
334 oper.addAuthHeader(builder);
335 verify(builder, never()).header(any(), any());
339 * Tests addAuthHeader() when there is a username, but no password.
342 public void testAddAuthHeaderUserOnly() {
343 Builder builder = mock(Builder.class);
344 lenient().when(client.getUserName()).thenReturn("my-user");
345 oper.addAuthHeader(builder);
347 ArgumentCaptor<String> keyCaptor = ArgumentCaptor.forClass(String.class);
348 ArgumentCaptor<String> valueCaptor = ArgumentCaptor.forClass(String.class);
350 verify(builder).header(keyCaptor.capture(), valueCaptor.capture());
352 assertEquals("Authorization", keyCaptor.getValue());
354 String encoded = Base64.getEncoder().encodeToString("my-user:".getBytes(StandardCharsets.UTF_8));
355 assertEquals("Basic " + encoded, valueCaptor.getValue());
359 * Tests makeRequest() when a property is missing.
362 public void testMakeRequestMissingProperty() throws Exception {
365 ServiceInstance instance = new ServiceInstance();
366 oper.setProperty(OperationProperties.AAI_SERVICE, instance);
368 assertThatIllegalArgumentException().isThrownBy(() -> oper.makeRequest())
369 .withMessageContaining("missing service instance ID");
373 public void testMakeHttpClient() {
374 // must use a real operation to invoke this method
375 assertNotNull(new MyOperation(params, config).makeHttpClient());
378 private void initHostPort() {
379 lenient().when(client.getBaseUrl()).thenReturn("http://my-host:6969/");
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);
388 javaFuture = CompletableFuture.completedFuture(javaResp);
389 lenient().when(javaClient.sendAsync(any(), any(BodyHandlers.ofString().getClass()))).thenReturn(javaFuture);
392 private class MyOperation extends VfModuleDelete {
394 public MyOperation(ControlLoopOperationParams params, HttpPollingConfig config) {
395 super(params, config);
399 protected java.net.http.HttpClient makeHttpClient() {
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);
410 GenericVnf vnf = new GenericVnf();
411 vnf.setVnfId(VNF_ID);
412 oper.setProperty(OperationProperties.AAI_VNF, vnf);
414 CloudRegion cloudRegion = new CloudRegion();
415 cloudRegion.setCloudRegionId("my-cloud-id");
416 oper.setProperty(OperationProperties.AAI_DEFAULT_CLOUD_REGION, cloudRegion);
418 Tenant tenant = new Tenant();
419 tenant.setTenantId("my-tenant-id");
420 oper.setProperty(OperationProperties.AAI_DEFAULT_TENANT, tenant);
422 oper.setProperty(OperationProperties.DATA_VF_COUNT, VF_COUNT);