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.assertSame;
29 import static org.junit.Assert.assertTrue;
30 import static org.mockito.ArgumentMatchers.any;
31 import static org.mockito.Mockito.mock;
32 import static org.mockito.Mockito.never;
33 import static org.mockito.Mockito.verify;
34 import static org.mockito.Mockito.when;
36 import java.net.http.HttpHeaders;
37 import java.net.http.HttpRequest;
38 import java.net.http.HttpRequest.Builder;
39 import java.net.http.HttpResponse;
40 import java.net.http.HttpResponse.BodyHandlers;
41 import java.nio.charset.StandardCharsets;
42 import java.util.Base64;
43 import java.util.List;
45 import java.util.concurrent.CompletableFuture;
46 import java.util.concurrent.ForkJoinPool;
47 import java.util.concurrent.TimeUnit;
48 import java.util.concurrent.atomic.AtomicBoolean;
49 import javax.ws.rs.client.InvocationCallback;
50 import javax.ws.rs.core.MediaType;
51 import javax.ws.rs.core.Response;
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.mockito.ArgumentCaptor;
58 import org.mockito.Mock;
59 import org.onap.aai.domain.yang.CloudRegion;
60 import org.onap.aai.domain.yang.GenericVnf;
61 import org.onap.aai.domain.yang.ModelVer;
62 import org.onap.aai.domain.yang.ServiceInstance;
63 import org.onap.aai.domain.yang.Tenant;
64 import org.onap.policy.aai.AaiCqResponse;
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.parameters.ControlLoopOperationParams;
70 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpPollingConfig;
71 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpPollingParams;
72 import org.onap.policy.controlloop.policy.PolicyResult;
73 import org.onap.policy.so.SoRequest;
74 import org.onap.policy.so.SoResponse;
76 public class VfModuleDeleteTest extends BasicSoOperation {
77 private static final String EXPECTED_EXCEPTION = "expected exception";
78 private static final String MODEL_NAME2 = "my-model-name-B";
79 private static final String MODEL_VERS2 = "my-model-version-B";
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 public VfModuleDeleteTest() {
94 super(DEFAULT_ACTOR, VfModuleDelete.NAME);
98 public static void setUpBeforeClass() throws Exception {
103 public static void tearDownAfterClass() {
111 public void setUp() throws Exception {
116 configureResponse(coder.encode(response));
118 oper = new MyOperation(params, config);
122 * Tests "success" case with simulator.
125 public void testSuccess() throws Exception {
126 HttpPollingParams opParams = HttpPollingParams.builder().clientName(MY_CLIENT).path("serviceInstances/v7")
127 .pollPath("orchestrationRequests/v5/").maxPolls(2).build();
128 config = new HttpPollingConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory());
130 params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor).build();
132 oper = new VfModuleDelete(params, config);
134 outcome = oper.start().get();
135 assertEquals(PolicyResult.SUCCESS, outcome.getResult());
136 assertTrue(outcome.getResponse() instanceof SoResponse);
140 public void testConstructor() {
141 assertEquals(DEFAULT_ACTOR, oper.getActorName());
142 assertEquals(VfModuleDelete.NAME, oper.getName());
144 // verify that target validation is done
145 params = params.toBuilder().target(null).build();
146 assertThatIllegalArgumentException().isThrownBy(() -> new MyOperation(params, config))
147 .withMessageContaining("Target information");
151 public void testGetPropertyNames() {
153 assertThat(oper.getPropertyNames()).isEqualTo(
155 OperationProperties.AAI_MODEL_SERVICE,
156 OperationProperties.AAI_MODEL_VNF,
157 OperationProperties.AAI_MODEL_CLOUD_REGION,
158 OperationProperties.AAI_MODEL_TENANT,
159 OperationProperties.DATA_VF_COUNT));
164 public void testStartPreprocessorAsync() throws Exception {
165 // insert CQ data so it's there for the check
166 context.setProperty(AaiCqResponse.CONTEXT_KEY, makeCqResponse());
168 AtomicBoolean guardStarted = new AtomicBoolean();
170 oper = new MyOperation(params, config) {
172 protected CompletableFuture<OperationOutcome> startGuardAsync() {
173 guardStarted.set(true);
174 return super.startGuardAsync();
178 CompletableFuture<OperationOutcome> future3 = oper.startPreprocessorAsync();
179 assertNotNull(future3);
180 assertTrue(guardStarted.get());
184 public void testStartGuardAsync() throws Exception {
185 // remove CQ data so it's forced to query
186 context.removeProperty(AaiCqResponse.CONTEXT_KEY);
188 CompletableFuture<OperationOutcome> future2 = oper.startPreprocessorAsync();
189 assertTrue(executor.runAll(100));
190 assertFalse(future2.isDone());
192 provideCqResponse(makeCqResponse());
193 assertTrue(executor.runAll(100));
194 assertTrue(future2.isDone());
195 assertEquals(PolicyResult.SUCCESS, future2.get().getResult());
199 public void testMakeGuardPayload() {
200 final int origCount = 30;
201 oper.setVfCount(origCount);
203 CompletableFuture<OperationOutcome> future2 = oper.startPreprocessorAsync();
204 assertTrue(executor.runAll(100));
205 assertTrue(future2.isDone());
207 // get the payload from the request
208 ArgumentCaptor<ControlLoopOperationParams> captor = ArgumentCaptor.forClass(ControlLoopOperationParams.class);
209 verify(guardOperator).buildOperation(captor.capture());
211 Map<String, Object> payload = captor.getValue().getPayload();
212 assertNotNull(payload);
214 Integer newCount = (Integer) payload.get(VfModuleDelete.PAYLOAD_KEY_VF_COUNT);
215 assertNotNull(newCount);
216 assertEquals(origCount - 1, newCount.intValue());
220 public void testStartOperationAsync_testSuccessfulCompletion() throws Exception {
221 final int origCount = 30;
222 oper.setVfCount(origCount);
224 // use a real executor
225 params = params.toBuilder().executor(ForkJoinPool.commonPool()).build();
227 oper = new MyOperation(params, config) {
229 public long getPollWaitMs() {
234 CompletableFuture<OperationOutcome> future2 = oper.start();
236 outcome = future2.get(5, TimeUnit.SECONDS);
237 assertEquals(PolicyResult.SUCCESS, outcome.getResult());
239 SoResponse resp = outcome.getResponse();
241 assertEquals(REQ_ID.toString(), resp.getRequestReferences().getRequestId());
243 assertEquals(origCount - 1, oper.getVfCount());
247 * Tests startOperationAsync() when polling is required.
250 public void testStartOperationAsyncWithPolling() throws Exception {
252 // indicate that the response was incomplete
253 configureResponse(coder.encode(response).replace("COMPLETE", "incomplete"));
255 when(rawResponse.getStatus()).thenReturn(500, 500, 500, 200, 200);
256 when(client.get(any(), any(), any())).thenAnswer(provideResponse(rawResponse));
258 // use a real executor
259 params = params.toBuilder().executor(ForkJoinPool.commonPool()).build();
261 oper = new MyOperation(params, config) {
263 public long getPollWaitMs() {
268 CompletableFuture<OperationOutcome> future2 = oper.start();
270 outcome = future2.get(5, TimeUnit.SECONDS);
271 assertEquals(PolicyResult.SUCCESS, outcome.getResult());
275 public void testMakeRequest() throws CoderException {
276 Pair<String, SoRequest> pair = oper.makeRequest();
278 assertEquals("/my-service-instance-id/vnfs/my-vnf-id/vfModules/null", pair.getLeft());
280 verifyRequest("VfModuleDelete.json", pair.getRight());
284 public void testDelete() throws Exception {
285 SoRequest req = new SoRequest();
286 req.setRequestId(REQ_ID);
288 Map<String, Object> headers = Map.of("key-A", "value-A");
290 String reqText = oper.prettyPrint(req);
292 final CompletableFuture<Response> delFuture =
293 oper.delete("my-uri", headers, MediaType.APPLICATION_JSON, reqText, callback);
295 ArgumentCaptor<HttpRequest> reqCaptor = ArgumentCaptor.forClass(HttpRequest.class);
296 verify(javaClient).sendAsync(reqCaptor.capture(), any());
298 HttpRequest req2 = reqCaptor.getValue();
299 assertEquals("http://my-host:6969/my-uri", req2.uri().toString());
300 assertEquals("DELETE", req2.method());
302 HttpHeaders headers2 = req2.headers();
303 assertEquals("value-A", headers2.firstValue("key-A").orElse("missing-key"));
304 assertEquals(MediaType.APPLICATION_JSON, headers2.firstValue("Content-type").orElse("missing-key"));
306 assertTrue(delFuture.isDone());
307 Response resp = delFuture.get();
309 verify(callback).completed(resp);
311 assertEquals(200, resp.getStatus());
313 SoResponse resp2 = resp.readEntity(SoResponse.class);
314 assertEquals(SoOperation.COMPLETE, resp2.getRequest().getRequestStatus().getRequestState());
318 * Tests delete() when an exception is thrown in the future.
321 @SuppressWarnings("unchecked")
322 public void testDeleteException() throws Exception {
323 Throwable thrown = new IllegalStateException(EXPECTED_EXCEPTION);
325 // need a new future, with an exception
326 javaFuture = CompletableFuture.failedFuture(thrown);
327 when(javaClient.sendAsync(any(), any(BodyHandlers.ofString().getClass()))).thenReturn(javaFuture);
329 SoRequest req = new SoRequest();
330 req.setRequestId(REQ_ID);
332 String reqText = oper.prettyPrint(req);
334 CompletableFuture<Response> delFuture =
335 oper.delete("/my-uri", Map.of(), MediaType.APPLICATION_JSON, reqText, callback);
337 assertTrue(delFuture.isCompletedExceptionally());
339 ArgumentCaptor<Throwable> thrownCaptor = ArgumentCaptor.forClass(Throwable.class);
340 verify(callback).failed(thrownCaptor.capture());
341 assertSame(thrown, thrownCaptor.getValue().getCause());
345 * Tests addAuthHeader() when there is a username, but no password.
348 public void testAddAuthHeader() {
349 Builder builder = mock(Builder.class);
350 when(client.getUserName()).thenReturn("the-user");
351 when(client.getPassword()).thenReturn("the-password");
352 oper.addAuthHeader(builder);
354 ArgumentCaptor<String> keyCaptor = ArgumentCaptor.forClass(String.class);
355 ArgumentCaptor<String> valueCaptor = ArgumentCaptor.forClass(String.class);
357 verify(builder).header(keyCaptor.capture(), valueCaptor.capture());
359 assertEquals("Authorization", keyCaptor.getValue());
361 String encoded = Base64.getEncoder().encodeToString("the-user:the-password".getBytes(StandardCharsets.UTF_8));
362 assertEquals("Basic " + encoded, valueCaptor.getValue());
366 * Tests addAuthHeader() when there is no username.
369 public void testAddAuthHeaderNoUser() {
370 Builder builder = mock(Builder.class);
371 when(client.getPassword()).thenReturn("world");
372 oper.addAuthHeader(builder);
373 verify(builder, never()).header(any(), any());
375 // repeat with empty username
376 when(client.getUserName()).thenReturn("");
377 oper.addAuthHeader(builder);
378 verify(builder, never()).header(any(), any());
382 * Tests addAuthHeader() when there is a username, but no password.
385 public void testAddAuthHeaderUserOnly() {
386 Builder builder = mock(Builder.class);
387 when(client.getUserName()).thenReturn("my-user");
388 oper.addAuthHeader(builder);
390 ArgumentCaptor<String> keyCaptor = ArgumentCaptor.forClass(String.class);
391 ArgumentCaptor<String> valueCaptor = ArgumentCaptor.forClass(String.class);
393 verify(builder).header(keyCaptor.capture(), valueCaptor.capture());
395 assertEquals("Authorization", keyCaptor.getValue());
397 String encoded = Base64.getEncoder().encodeToString("my-user:".getBytes(StandardCharsets.UTF_8));
398 assertEquals("Basic " + encoded, valueCaptor.getValue());
402 public void testMakeHttpClient() {
403 // must use a real operation to invoke this method
404 assertNotNull(new MyOperation(params, config).makeHttpClient());
409 protected void makeContext() {
412 AaiCqResponse cq = mock(AaiCqResponse.class);
414 GenericVnf vnf = new GenericVnf();
415 when(cq.getGenericVnfByVfModuleModelInvariantId(MODEL_INVAR_ID)).thenReturn(vnf);
416 vnf.setVnfId(VNF_ID);
418 ServiceInstance instance = new ServiceInstance();
419 when(cq.getServiceInstance()).thenReturn(instance);
420 instance.setServiceInstanceId(SVC_INSTANCE_ID);
422 when(cq.getDefaultTenant()).thenReturn(new Tenant());
423 when(cq.getDefaultCloudRegion()).thenReturn(new CloudRegion());
425 ModelVer modelVers = new ModelVer();
426 when(cq.getModelVerByVersionId(any())).thenReturn(modelVers);
427 modelVers.setModelName(MODEL_NAME2);
428 modelVers.setModelVersion(MODEL_VERS2);
430 params.getContext().setProperty(AaiCqResponse.CONTEXT_KEY, cq);
433 private void initHostPort() {
434 when(client.getBaseUrl()).thenReturn("http://my-host:6969/");
437 @SuppressWarnings("unchecked")
438 private void configureResponse(String responseText) throws CoderException {
439 // indicate that the response was completed
440 when(javaResp.statusCode()).thenReturn(200);
441 when(javaResp.body()).thenReturn(responseText);
443 javaFuture = CompletableFuture.completedFuture(javaResp);
444 when(javaClient.sendAsync(any(), any(BodyHandlers.ofString().getClass()))).thenReturn(javaFuture);
447 private class MyOperation extends VfModuleDelete {
449 public MyOperation(ControlLoopOperationParams params, HttpPollingConfig config) {
450 super(params, config);
454 protected java.net.http.HttpClient makeHttpClient() {