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.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;
 
  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;
 
  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.CoderException;
 
  65 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
 
  66 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
 
  67 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig;
 
  68 import org.onap.policy.controlloop.policy.PolicyResult;
 
  69 import org.onap.policy.so.SoRequest;
 
  70 import org.onap.policy.so.SoResponse;
 
  72 public class VfModuleDeleteTest extends BasicSoOperation {
 
  73     private static final String EXPECTED_EXCEPTION = "expected exception";
 
  74     private static final String MODEL_NAME2 = "my-model-name-B";
 
  75     private static final String MODEL_VERS2 = "my-model-version-B";
 
  76     private static final String SVC_INSTANCE_ID = "my-service-instance-id";
 
  77     private static final String VNF_ID = "my-vnf-id";
 
  80     private java.net.http.HttpClient javaClient;
 
  82     private HttpResponse<String> javaResp;
 
  84     private InvocationCallback<Response> callback;
 
  86     private CompletableFuture<HttpResponse<String>> javaFuture;
 
  87     private VfModuleDelete oper;
 
  89     public VfModuleDeleteTest() {
 
  90         super(DEFAULT_ACTOR, VfModuleDelete.NAME);
 
  94     public static void setUpBeforeClass() throws Exception {
 
  99     public static void tearDownAfterClass() {
 
 107     public void setUp() throws Exception {
 
 112         configureResponse(coder.encode(response));
 
 114         oper = new MyOperation(params, config);
 
 118      * Tests "success" case with simulator.
 
 121     public void testSuccess() throws Exception {
 
 122         SoParams opParams = SoParams.builder().clientName(MY_CLIENT).path("serviceInstances/v7")
 
 123                         .pathGet("orchestrationRequests/v5/").maxGets(2).build();
 
 124         config = new SoConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory());
 
 126         params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor).build();
 
 127         oper = new VfModuleDelete(params, config);
 
 129         outcome = oper.start().get();
 
 130         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
 
 131         assertTrue(outcome.getResponse() instanceof SoResponse);
 
 135     public void testConstructor() {
 
 136         assertEquals(DEFAULT_ACTOR, oper.getActorName());
 
 137         assertEquals(VfModuleDelete.NAME, oper.getName());
 
 139         // verify that target validation is done
 
 140         params = params.toBuilder().target(null).build();
 
 141         assertThatIllegalArgumentException().isThrownBy(() -> new VfModuleDelete(params, config))
 
 142                         .withMessageContaining("Target information");
 
 146     public void testStartPreprocessorAsync() throws Exception {
 
 147         // insert CQ data so it's there for the check
 
 148         context.setProperty(AaiCqResponse.CONTEXT_KEY, makeCqResponse());
 
 150         AtomicBoolean guardStarted = new AtomicBoolean();
 
 152         oper = new MyOperation(params, config) {
 
 154             protected CompletableFuture<OperationOutcome> startGuardAsync() {
 
 155                 guardStarted.set(true);
 
 156                 return super.startGuardAsync();
 
 160         CompletableFuture<OperationOutcome> future3 = oper.startPreprocessorAsync();
 
 161         assertNotNull(future3);
 
 162         assertTrue(guardStarted.get());
 
 166     public void testStartGuardAsync() throws Exception {
 
 167         // remove CQ data so it's forced to query
 
 168         context.removeProperty(AaiCqResponse.CONTEXT_KEY);
 
 170         CompletableFuture<OperationOutcome> future2 = oper.startPreprocessorAsync();
 
 171         assertTrue(executor.runAll(100));
 
 172         assertFalse(future2.isDone());
 
 174         provideCqResponse(makeCqResponse());
 
 175         assertTrue(executor.runAll(100));
 
 176         assertTrue(future2.isDone());
 
 177         assertEquals(PolicyResult.SUCCESS, future2.get().getResult());
 
 181     public void testMakeGuardPayload() {
 
 182         final int origCount = 30;
 
 183         oper.setVfCount(origCount);
 
 185         CompletableFuture<OperationOutcome> future2 = oper.startPreprocessorAsync();
 
 186         assertTrue(executor.runAll(100));
 
 187         assertTrue(future2.isDone());
 
 189         // get the payload from the request
 
 190         ArgumentCaptor<ControlLoopOperationParams> captor = ArgumentCaptor.forClass(ControlLoopOperationParams.class);
 
 191         verify(guardOperator).buildOperation(captor.capture());
 
 193         Map<String, Object> payload = captor.getValue().getPayload();
 
 194         assertNotNull(payload);
 
 196         Integer newCount = (Integer) payload.get(VfModuleDelete.PAYLOAD_KEY_VF_COUNT);
 
 197         assertNotNull(newCount);
 
 198         assertEquals(origCount - 1, newCount.intValue());
 
 202     public void testStartOperationAsync_testSuccessfulCompletion() throws Exception {
 
 203         final int origCount = 30;
 
 204         oper.setVfCount(origCount);
 
 206         // use a real executor
 
 207         params = params.toBuilder().executor(ForkJoinPool.commonPool()).build();
 
 209         oper = new MyOperation(params, config) {
 
 211             public long getWaitMsGet() {
 
 216         CompletableFuture<OperationOutcome> future2 = oper.start();
 
 218         outcome = future2.get(5, TimeUnit.SECONDS);
 
 219         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
 
 221         SoResponse resp = outcome.getResponse();
 
 223         assertEquals(REQ_ID.toString(), resp.getRequestReferences().getRequestId());
 
 225         assertEquals(origCount - 1, oper.getVfCount());
 
 229      * Tests startOperationAsync() when "get" operations are required.
 
 232     public void testStartOperationAsyncWithGets() throws Exception {
 
 234         // indicate that the response was incomplete
 
 235         configureResponse(coder.encode(response).replace("COMPLETE", "incomplete"));
 
 237         when(rawResponse.getStatus()).thenReturn(500, 500, 500, 200, 200);
 
 238         when(client.get(any(), any(), any())).thenAnswer(provideResponse(rawResponse));
 
 240         // use a real executor
 
 241         params = params.toBuilder().executor(ForkJoinPool.commonPool()).build();
 
 243         oper = new MyOperation(params, config) {
 
 245             public long getWaitMsGet() {
 
 250         CompletableFuture<OperationOutcome> future2 = oper.start();
 
 252         outcome = future2.get(5, TimeUnit.SECONDS);
 
 253         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
 
 257     public void testMakeRequest() throws CoderException {
 
 258         Pair<String, SoRequest> pair = oper.makeRequest();
 
 260         assertEquals("/my-service-instance-id/vnfs/my-vnf-id/vfModules/null", pair.getLeft());
 
 262         verifyRequest("VfModuleDelete.json", pair.getRight());
 
 266     public void testDelete() throws Exception {
 
 267         SoRequest req = new SoRequest();
 
 268         req.setRequestId(REQ_ID);
 
 270         Map<String, Object> headers = Map.of("key-A", "value-A");
 
 272         String reqText = oper.prettyPrint(req);
 
 274         final CompletableFuture<Response> delFuture =
 
 275                         oper.delete("my-uri", headers, MediaType.APPLICATION_JSON, reqText, callback);
 
 277         ArgumentCaptor<HttpRequest> reqCaptor = ArgumentCaptor.forClass(HttpRequest.class);
 
 278         verify(javaClient).sendAsync(reqCaptor.capture(), any());
 
 280         HttpRequest req2 = reqCaptor.getValue();
 
 281         assertEquals("http://my-host:6969/my-uri", req2.uri().toString());
 
 282         assertEquals("DELETE", req2.method());
 
 284         HttpHeaders headers2 = req2.headers();
 
 285         assertEquals("value-A", headers2.firstValue("key-A").orElse("missing-key"));
 
 286         assertEquals(MediaType.APPLICATION_JSON, headers2.firstValue("Content-type").orElse("missing-key"));
 
 288         assertTrue(delFuture.isDone());
 
 289         Response resp = delFuture.get();
 
 291         verify(callback).completed(resp);
 
 293         assertEquals(200, resp.getStatus());
 
 295         SoResponse resp2 = resp.readEntity(SoResponse.class);
 
 296         assertEquals(SoOperation.COMPLETE, resp2.getRequest().getRequestStatus().getRequestState());
 
 300      * Tests delete() when an exception is thrown in the future.
 
 303     @SuppressWarnings("unchecked")
 
 304     public void testDeleteException() throws Exception {
 
 305         Throwable thrown = new IllegalStateException(EXPECTED_EXCEPTION);
 
 307         // need a new future, with an exception
 
 308         javaFuture = CompletableFuture.failedFuture(thrown);
 
 309         when(javaClient.sendAsync(any(), any(BodyHandlers.ofString().getClass()))).thenReturn(javaFuture);
 
 311         SoRequest req = new SoRequest();
 
 312         req.setRequestId(REQ_ID);
 
 314         String reqText = oper.prettyPrint(req);
 
 316         CompletableFuture<Response> delFuture =
 
 317                         oper.delete("/my-uri", Map.of(), MediaType.APPLICATION_JSON, reqText, callback);
 
 319         assertTrue(delFuture.isCompletedExceptionally());
 
 321         ArgumentCaptor<Throwable> thrownCaptor = ArgumentCaptor.forClass(Throwable.class);
 
 322         verify(callback).failed(thrownCaptor.capture());
 
 323         assertSame(thrown, thrownCaptor.getValue().getCause());
 
 327      * Tests addAuthHeader() when there is a username, but no password.
 
 330     public void testAddAuthHeader() {
 
 331         Builder builder = mock(Builder.class);
 
 332         when(client.getUserName()).thenReturn("the-user");
 
 333         when(client.getPassword()).thenReturn("the-password");
 
 334         oper.addAuthHeader(builder);
 
 336         ArgumentCaptor<String> keyCaptor = ArgumentCaptor.forClass(String.class);
 
 337         ArgumentCaptor<String> valueCaptor = ArgumentCaptor.forClass(String.class);
 
 339         verify(builder).header(keyCaptor.capture(), valueCaptor.capture());
 
 341         assertEquals("Authorization", keyCaptor.getValue());
 
 343         String encoded = Base64.getEncoder().encodeToString("the-user:the-password".getBytes(StandardCharsets.UTF_8));
 
 344         assertEquals("Basic " + encoded, valueCaptor.getValue());
 
 348      * Tests addAuthHeader() when there is no username.
 
 351     public void testAddAuthHeaderNoUser() {
 
 352         Builder builder = mock(Builder.class);
 
 353         when(client.getPassword()).thenReturn("world");
 
 354         oper.addAuthHeader(builder);
 
 355         verify(builder, never()).header(any(), any());
 
 357         // repeat with empty username
 
 358         when(client.getUserName()).thenReturn("");
 
 359         oper.addAuthHeader(builder);
 
 360         verify(builder, never()).header(any(), any());
 
 364      * Tests addAuthHeader() when there is a username, but no password.
 
 367     public void testAddAuthHeaderUserOnly() {
 
 368         Builder builder = mock(Builder.class);
 
 369         when(client.getUserName()).thenReturn("my-user");
 
 370         oper.addAuthHeader(builder);
 
 372         ArgumentCaptor<String> keyCaptor = ArgumentCaptor.forClass(String.class);
 
 373         ArgumentCaptor<String> valueCaptor = ArgumentCaptor.forClass(String.class);
 
 375         verify(builder).header(keyCaptor.capture(), valueCaptor.capture());
 
 377         assertEquals("Authorization", keyCaptor.getValue());
 
 379         String encoded = Base64.getEncoder().encodeToString("my-user:".getBytes(StandardCharsets.UTF_8));
 
 380         assertEquals("Basic " + encoded, valueCaptor.getValue());
 
 384     public void testMakeHttpClient() {
 
 385         // must use a real operation to invoke this method
 
 386         assertNotNull(new VfModuleDelete(params, config).makeHttpClient());
 
 391     protected void makeContext() {
 
 394         AaiCqResponse cq = mock(AaiCqResponse.class);
 
 396         GenericVnf vnf = new GenericVnf();
 
 397         when(cq.getGenericVnfByVfModuleModelInvariantId(MODEL_INVAR_ID)).thenReturn(vnf);
 
 398         vnf.setVnfId(VNF_ID);
 
 400         ServiceInstance instance = new ServiceInstance();
 
 401         when(cq.getServiceInstance()).thenReturn(instance);
 
 402         instance.setServiceInstanceId(SVC_INSTANCE_ID);
 
 404         when(cq.getDefaultTenant()).thenReturn(new Tenant());
 
 405         when(cq.getDefaultCloudRegion()).thenReturn(new CloudRegion());
 
 407         ModelVer modelVers = new ModelVer();
 
 408         when(cq.getModelVerByVersionId(any())).thenReturn(modelVers);
 
 409         modelVers.setModelName(MODEL_NAME2);
 
 410         modelVers.setModelVersion(MODEL_VERS2);
 
 412         params.getContext().setProperty(AaiCqResponse.CONTEXT_KEY, cq);
 
 415     private void initHostPort() {
 
 416         when(client.getBaseUrl()).thenReturn("http://my-host:6969/");
 
 419     @SuppressWarnings("unchecked")
 
 420     private void configureResponse(String responseText) throws CoderException {
 
 421         // indicate that the response was completed
 
 422         when(javaResp.statusCode()).thenReturn(200);
 
 423         when(javaResp.body()).thenReturn(responseText);
 
 425         javaFuture = CompletableFuture.completedFuture(javaResp);
 
 426         when(javaClient.sendAsync(any(), any(BodyHandlers.ofString().getClass()))).thenReturn(javaFuture);
 
 429     private class MyOperation extends VfModuleDelete {
 
 431         public MyOperation(ControlLoopOperationParams params, HttpConfig config) {
 
 432             super(params, config);
 
 436         protected java.net.http.HttpClient makeHttpClient() {