2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.controlloop.actor.so;
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertFalse;
27 import static org.junit.Assert.assertNotNull;
28 import static org.junit.Assert.assertNull;
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.mock;
33 import static org.mockito.Mockito.never;
34 import static org.mockito.Mockito.verify;
35 import static org.mockito.Mockito.when;
37 import java.net.http.HttpHeaders;
38 import java.net.http.HttpRequest;
39 import java.net.http.HttpRequest.Builder;
40 import java.net.http.HttpResponse;
41 import java.net.http.HttpResponse.BodyHandlers;
42 import java.nio.charset.StandardCharsets;
43 import java.util.Base64;
44 import java.util.List;
46 import java.util.concurrent.CompletableFuture;
47 import java.util.concurrent.ForkJoinPool;
48 import java.util.concurrent.TimeUnit;
49 import java.util.concurrent.atomic.AtomicBoolean;
50 import javax.ws.rs.client.InvocationCallback;
51 import javax.ws.rs.core.MediaType;
52 import javax.ws.rs.core.Response;
53 import org.apache.commons.lang3.tuple.Pair;
54 import org.junit.AfterClass;
55 import org.junit.Before;
56 import org.junit.BeforeClass;
57 import org.junit.Test;
58 import org.mockito.ArgumentCaptor;
59 import org.mockito.Mock;
60 import org.onap.aai.domain.yang.CloudRegion;
61 import org.onap.aai.domain.yang.GenericVnf;
62 import org.onap.aai.domain.yang.ModelVer;
63 import org.onap.aai.domain.yang.ServiceInstance;
64 import org.onap.aai.domain.yang.Tenant;
65 import org.onap.policy.aai.AaiCqResponse;
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.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.controlloop.policy.PolicyResult;
74 import org.onap.policy.so.SoRequest;
75 import org.onap.policy.so.SoResponse;
77 public class VfModuleDeleteTest extends BasicSoOperation {
78 private static final String EXPECTED_EXCEPTION = "expected exception";
79 private static final String MODEL_NAME2 = "my-model-name-B";
80 private static final String MODEL_VERS2 = "my-model-version-B";
81 private static final String SVC_INSTANCE_ID = "my-service-instance-id";
82 private static final String VNF_ID = "my-vnf-id";
85 private java.net.http.HttpClient javaClient;
87 private HttpResponse<String> javaResp;
89 private InvocationCallback<Response> callback;
91 private CompletableFuture<HttpResponse<String>> javaFuture;
92 private VfModuleDelete oper;
94 public VfModuleDeleteTest() {
95 super(DEFAULT_ACTOR, VfModuleDelete.NAME);
99 public static void setUpBeforeClass() throws Exception {
104 public static void tearDownAfterClass() {
112 public void setUp() throws Exception {
117 configureResponse(coder.encode(response));
119 oper = new MyOperation(params, config);
123 * Tests "success" case with simulator.
126 public void testSuccess() throws Exception {
127 HttpPollingParams opParams = HttpPollingParams.builder().clientName(MY_CLIENT).path("serviceInstances/v7")
128 .pollPath("orchestrationRequests/v5/").maxPolls(2).build();
129 config = new HttpPollingConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory());
131 params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor).build();
133 oper = new VfModuleDelete(params, config);
135 outcome = oper.start().get();
136 assertEquals(PolicyResult.SUCCESS, outcome.getResult());
137 assertTrue(outcome.getResponse() instanceof SoResponse);
141 * Tests "success" case with simulator, using properties instead of custom query data.
144 public void testSuccessViaProperties() throws Exception {
145 HttpPollingParams opParams = HttpPollingParams.builder().clientName(MY_CLIENT).path("serviceInstances/v7")
146 .pollPath("orchestrationRequests/v5/").maxPolls(2).build();
147 config = new HttpPollingConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory());
149 params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor).preprocessed(true).build();
150 params.getContext().removeProperty(AaiCqResponse.CONTEXT_KEY);
152 oper = new VfModuleDelete(params, config);
154 // set the properties
155 ServiceInstance instance = new ServiceInstance();
156 instance.setServiceInstanceId(SVC_INSTANCE_ID);
157 oper.setProperty(OperationProperties.AAI_SERVICE, instance);
159 GenericVnf vnf = new GenericVnf();
160 vnf.setVnfId(VNF_ID);
161 oper.setProperty(OperationProperties.AAI_VNF, vnf);
163 oper.setProperty(OperationProperties.AAI_DEFAULT_CLOUD_REGION, new CloudRegion());
164 oper.setProperty(OperationProperties.AAI_DEFAULT_TENANT, new Tenant());
166 oper.setProperty(OperationProperties.DATA_VF_COUNT, VF_COUNT);
169 outcome = oper.start().get();
170 assertEquals(PolicyResult.SUCCESS, outcome.getResult());
171 assertTrue(outcome.getResponse() instanceof SoResponse);
173 int count = oper.getProperty(OperationProperties.DATA_VF_COUNT);
174 assertEquals(VF_COUNT - 1, count);
178 public void testConstructor() {
179 assertEquals(DEFAULT_ACTOR, oper.getActorName());
180 assertEquals(VfModuleDelete.NAME, oper.getName());
182 // verify that target validation is done
183 params = params.toBuilder().target(null).build();
184 assertThatIllegalArgumentException().isThrownBy(() -> new MyOperation(params, config))
185 .withMessageContaining("Target information");
189 public void testGetPropertyNames() {
191 assertThat(oper.getPropertyNames()).isEqualTo(
193 OperationProperties.AAI_SERVICE,
194 OperationProperties.AAI_VNF,
195 OperationProperties.AAI_DEFAULT_CLOUD_REGION,
196 OperationProperties.AAI_DEFAULT_TENANT,
197 OperationProperties.DATA_VF_COUNT));
202 public void testStartPreprocessorAsync() throws Exception {
203 // insert CQ data so it's there for the check
204 context.setProperty(AaiCqResponse.CONTEXT_KEY, makeCqResponse());
206 AtomicBoolean guardStarted = new AtomicBoolean();
208 oper = new MyOperation(params, config) {
210 protected CompletableFuture<OperationOutcome> startGuardAsync() {
211 guardStarted.set(true);
212 return super.startGuardAsync();
216 CompletableFuture<OperationOutcome> future3 = oper.startPreprocessorAsync();
217 assertNotNull(future3);
218 assertTrue(guardStarted.get());
222 * Tests startPreprocessorAsync(), when preprocessing is disabled.
225 public void testStartPreprocessorAsyncDisabled() {
226 params = params.toBuilder().preprocessed(true).build();
227 assertNull(new MyOperation(params, config).startPreprocessorAsync());
231 public void testStartGuardAsync() throws Exception {
232 // remove CQ data so it's forced to query
233 context.removeProperty(AaiCqResponse.CONTEXT_KEY);
235 CompletableFuture<OperationOutcome> future2 = oper.startPreprocessorAsync();
236 assertTrue(executor.runAll(100));
237 assertFalse(future2.isDone());
239 provideCqResponse(makeCqResponse());
240 assertTrue(executor.runAll(100));
241 assertTrue(future2.isDone());
242 assertEquals(PolicyResult.SUCCESS, future2.get().getResult());
246 public void testMakeGuardPayload() {
247 final int origCount = 30;
248 oper.setVfCount(origCount);
250 CompletableFuture<OperationOutcome> future2 = oper.startPreprocessorAsync();
251 assertTrue(executor.runAll(100));
252 assertTrue(future2.isDone());
254 // get the payload from the request
255 ArgumentCaptor<ControlLoopOperationParams> captor = ArgumentCaptor.forClass(ControlLoopOperationParams.class);
256 verify(guardOperator).buildOperation(captor.capture());
258 Map<String, Object> payload = captor.getValue().getPayload();
259 assertNotNull(payload);
261 Integer newCount = (Integer) payload.get(VfModuleDelete.PAYLOAD_KEY_VF_COUNT);
262 assertNotNull(newCount);
263 assertEquals(origCount - 1, newCount.intValue());
267 public void testStartOperationAsync_testSuccessfulCompletion() throws Exception {
268 final int origCount = 30;
269 oper.setVfCount(origCount);
271 // use a real executor
272 params = params.toBuilder().executor(ForkJoinPool.commonPool()).build();
274 oper = new MyOperation(params, config) {
276 public long getPollWaitMs() {
281 CompletableFuture<OperationOutcome> future2 = oper.start();
283 outcome = future2.get(5, TimeUnit.SECONDS);
284 assertEquals(PolicyResult.SUCCESS, outcome.getResult());
286 SoResponse resp = outcome.getResponse();
288 assertEquals(REQ_ID.toString(), resp.getRequestReferences().getRequestId());
290 assertEquals(origCount - 1, oper.getVfCount());
294 * Tests startOperationAsync() when polling is required.
297 public void testStartOperationAsyncWithPolling() throws Exception {
299 // indicate that the response was incomplete
300 configureResponse(coder.encode(response).replace("COMPLETE", "incomplete"));
302 when(rawResponse.getStatus()).thenReturn(500, 500, 500, 200, 200);
303 when(client.get(any(), any(), any())).thenAnswer(provideResponse(rawResponse));
305 // use a real executor
306 params = params.toBuilder().executor(ForkJoinPool.commonPool()).build();
308 oper = new MyOperation(params, config) {
310 public long getPollWaitMs() {
315 CompletableFuture<OperationOutcome> future2 = oper.start();
317 outcome = future2.get(5, TimeUnit.SECONDS);
318 assertEquals(PolicyResult.SUCCESS, outcome.getResult());
322 public void testMakeRequest() throws CoderException {
323 Pair<String, SoRequest> pair = oper.makeRequest();
325 assertEquals("/my-service-instance-id/vnfs/my-vnf-id/vfModules/null", pair.getLeft());
327 verifyRequest("VfModuleDelete.json", pair.getRight());
331 public void testDelete() throws Exception {
332 SoRequest req = new SoRequest();
333 req.setRequestId(REQ_ID);
335 Map<String, Object> headers = Map.of("key-A", "value-A");
337 String reqText = oper.prettyPrint(req);
339 final CompletableFuture<Response> delFuture =
340 oper.delete("my-uri", headers, MediaType.APPLICATION_JSON, reqText, callback);
342 ArgumentCaptor<HttpRequest> reqCaptor = ArgumentCaptor.forClass(HttpRequest.class);
343 verify(javaClient).sendAsync(reqCaptor.capture(), any());
345 HttpRequest req2 = reqCaptor.getValue();
346 assertEquals("http://my-host:6969/my-uri", req2.uri().toString());
347 assertEquals("DELETE", req2.method());
349 HttpHeaders headers2 = req2.headers();
350 assertEquals("value-A", headers2.firstValue("key-A").orElse("missing-key"));
351 assertEquals(MediaType.APPLICATION_JSON, headers2.firstValue("Content-type").orElse("missing-key"));
353 assertTrue(delFuture.isDone());
354 Response resp = delFuture.get();
356 verify(callback).completed(resp);
358 assertEquals(200, resp.getStatus());
360 SoResponse resp2 = resp.readEntity(SoResponse.class);
361 assertEquals(SoOperation.COMPLETE, resp2.getRequest().getRequestStatus().getRequestState());
365 * Tests delete() when an exception is thrown in the future.
368 @SuppressWarnings("unchecked")
369 public void testDeleteException() throws Exception {
370 Throwable thrown = new IllegalStateException(EXPECTED_EXCEPTION);
372 // need a new future, with an exception
373 javaFuture = CompletableFuture.failedFuture(thrown);
374 when(javaClient.sendAsync(any(), any(BodyHandlers.ofString().getClass()))).thenReturn(javaFuture);
376 SoRequest req = new SoRequest();
377 req.setRequestId(REQ_ID);
379 String reqText = oper.prettyPrint(req);
381 CompletableFuture<Response> delFuture =
382 oper.delete("/my-uri", Map.of(), MediaType.APPLICATION_JSON, reqText, callback);
384 assertTrue(delFuture.isCompletedExceptionally());
386 ArgumentCaptor<Throwable> thrownCaptor = ArgumentCaptor.forClass(Throwable.class);
387 verify(callback).failed(thrownCaptor.capture());
388 assertSame(thrown, thrownCaptor.getValue().getCause());
392 * Tests addAuthHeader() when there is a username, but no password.
395 public void testAddAuthHeader() {
396 Builder builder = mock(Builder.class);
397 when(client.getUserName()).thenReturn("the-user");
398 when(client.getPassword()).thenReturn("the-password");
399 oper.addAuthHeader(builder);
401 ArgumentCaptor<String> keyCaptor = ArgumentCaptor.forClass(String.class);
402 ArgumentCaptor<String> valueCaptor = ArgumentCaptor.forClass(String.class);
404 verify(builder).header(keyCaptor.capture(), valueCaptor.capture());
406 assertEquals("Authorization", keyCaptor.getValue());
408 String encoded = Base64.getEncoder().encodeToString("the-user:the-password".getBytes(StandardCharsets.UTF_8));
409 assertEquals("Basic " + encoded, valueCaptor.getValue());
413 * Tests addAuthHeader() when there is no username.
416 public void testAddAuthHeaderNoUser() {
417 Builder builder = mock(Builder.class);
418 when(client.getPassword()).thenReturn("world");
419 oper.addAuthHeader(builder);
420 verify(builder, never()).header(any(), any());
422 // repeat with empty username
423 when(client.getUserName()).thenReturn("");
424 oper.addAuthHeader(builder);
425 verify(builder, never()).header(any(), any());
429 * Tests addAuthHeader() when there is a username, but no password.
432 public void testAddAuthHeaderUserOnly() {
433 Builder builder = mock(Builder.class);
434 when(client.getUserName()).thenReturn("my-user");
435 oper.addAuthHeader(builder);
437 ArgumentCaptor<String> keyCaptor = ArgumentCaptor.forClass(String.class);
438 ArgumentCaptor<String> valueCaptor = ArgumentCaptor.forClass(String.class);
440 verify(builder).header(keyCaptor.capture(), valueCaptor.capture());
442 assertEquals("Authorization", keyCaptor.getValue());
444 String encoded = Base64.getEncoder().encodeToString("my-user:".getBytes(StandardCharsets.UTF_8));
445 assertEquals("Basic " + encoded, valueCaptor.getValue());
449 public void testMakeHttpClient() {
450 // must use a real operation to invoke this method
451 assertNotNull(new MyOperation(params, config).makeHttpClient());
456 protected void makeContext() {
459 AaiCqResponse cq = mock(AaiCqResponse.class);
461 GenericVnf vnf = new GenericVnf();
462 when(cq.getGenericVnfByVfModuleModelInvariantId(MODEL_INVAR_ID)).thenReturn(vnf);
463 vnf.setVnfId(VNF_ID);
465 ServiceInstance instance = new ServiceInstance();
466 when(cq.getServiceInstance()).thenReturn(instance);
467 instance.setServiceInstanceId(SVC_INSTANCE_ID);
469 when(cq.getDefaultTenant()).thenReturn(new Tenant());
470 when(cq.getDefaultCloudRegion()).thenReturn(new CloudRegion());
472 ModelVer modelVers = new ModelVer();
473 when(cq.getModelVerByVersionId(any())).thenReturn(modelVers);
474 modelVers.setModelName(MODEL_NAME2);
475 modelVers.setModelVersion(MODEL_VERS2);
477 params.getContext().setProperty(AaiCqResponse.CONTEXT_KEY, cq);
480 private void initHostPort() {
481 when(client.getBaseUrl()).thenReturn("http://my-host:6969/");
484 @SuppressWarnings("unchecked")
485 private void configureResponse(String responseText) throws CoderException {
486 // indicate that the response was completed
487 when(javaResp.statusCode()).thenReturn(200);
488 when(javaResp.body()).thenReturn(responseText);
490 javaFuture = CompletableFuture.completedFuture(javaResp);
491 when(javaClient.sendAsync(any(), any(BodyHandlers.ofString().getClass()))).thenReturn(javaFuture);
494 private class MyOperation extends VfModuleDelete {
496 public MyOperation(ControlLoopOperationParams params, HttpPollingConfig config) {
497 super(params, config);
501 protected java.net.http.HttpClient makeHttpClient() {