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 public void testConstructor() {
142 assertEquals(DEFAULT_ACTOR, oper.getActorName());
143 assertEquals(VfModuleDelete.NAME, oper.getName());
145 // verify that target validation is done
146 params = params.toBuilder().target(null).build();
147 assertThatIllegalArgumentException().isThrownBy(() -> new MyOperation(params, config))
148 .withMessageContaining("Target information");
152 public void testGetPropertyNames() {
154 assertThat(oper.getPropertyNames()).isEqualTo(
156 OperationProperties.AAI_MODEL_SERVICE,
157 OperationProperties.AAI_MODEL_VNF,
158 OperationProperties.AAI_MODEL_CLOUD_REGION,
159 OperationProperties.AAI_MODEL_TENANT,
160 OperationProperties.DATA_VF_COUNT));
165 public void testStartPreprocessorAsync() throws Exception {
166 // insert CQ data so it's there for the check
167 context.setProperty(AaiCqResponse.CONTEXT_KEY, makeCqResponse());
169 AtomicBoolean guardStarted = new AtomicBoolean();
171 oper = new MyOperation(params, config) {
173 protected CompletableFuture<OperationOutcome> startGuardAsync() {
174 guardStarted.set(true);
175 return super.startGuardAsync();
179 CompletableFuture<OperationOutcome> future3 = oper.startPreprocessorAsync();
180 assertNotNull(future3);
181 assertTrue(guardStarted.get());
185 * Tests startPreprocessorAsync(), when preprocessing is disabled.
188 public void testStartPreprocessorAsyncDisabled() {
189 params = params.toBuilder().preprocessed(true).build();
190 assertNull(new MyOperation(params, config).startPreprocessorAsync());
194 public void testStartGuardAsync() throws Exception {
195 // remove CQ data so it's forced to query
196 context.removeProperty(AaiCqResponse.CONTEXT_KEY);
198 CompletableFuture<OperationOutcome> future2 = oper.startPreprocessorAsync();
199 assertTrue(executor.runAll(100));
200 assertFalse(future2.isDone());
202 provideCqResponse(makeCqResponse());
203 assertTrue(executor.runAll(100));
204 assertTrue(future2.isDone());
205 assertEquals(PolicyResult.SUCCESS, future2.get().getResult());
209 public void testMakeGuardPayload() {
210 final int origCount = 30;
211 oper.setVfCount(origCount);
213 CompletableFuture<OperationOutcome> future2 = oper.startPreprocessorAsync();
214 assertTrue(executor.runAll(100));
215 assertTrue(future2.isDone());
217 // get the payload from the request
218 ArgumentCaptor<ControlLoopOperationParams> captor = ArgumentCaptor.forClass(ControlLoopOperationParams.class);
219 verify(guardOperator).buildOperation(captor.capture());
221 Map<String, Object> payload = captor.getValue().getPayload();
222 assertNotNull(payload);
224 Integer newCount = (Integer) payload.get(VfModuleDelete.PAYLOAD_KEY_VF_COUNT);
225 assertNotNull(newCount);
226 assertEquals(origCount - 1, newCount.intValue());
230 public void testStartOperationAsync_testSuccessfulCompletion() throws Exception {
231 final int origCount = 30;
232 oper.setVfCount(origCount);
234 // use a real executor
235 params = params.toBuilder().executor(ForkJoinPool.commonPool()).build();
237 oper = new MyOperation(params, config) {
239 public long getPollWaitMs() {
244 CompletableFuture<OperationOutcome> future2 = oper.start();
246 outcome = future2.get(5, TimeUnit.SECONDS);
247 assertEquals(PolicyResult.SUCCESS, outcome.getResult());
249 SoResponse resp = outcome.getResponse();
251 assertEquals(REQ_ID.toString(), resp.getRequestReferences().getRequestId());
253 assertEquals(origCount - 1, oper.getVfCount());
257 * Tests startOperationAsync() when polling is required.
260 public void testStartOperationAsyncWithPolling() throws Exception {
262 // indicate that the response was incomplete
263 configureResponse(coder.encode(response).replace("COMPLETE", "incomplete"));
265 when(rawResponse.getStatus()).thenReturn(500, 500, 500, 200, 200);
266 when(client.get(any(), any(), any())).thenAnswer(provideResponse(rawResponse));
268 // use a real executor
269 params = params.toBuilder().executor(ForkJoinPool.commonPool()).build();
271 oper = new MyOperation(params, config) {
273 public long getPollWaitMs() {
278 CompletableFuture<OperationOutcome> future2 = oper.start();
280 outcome = future2.get(5, TimeUnit.SECONDS);
281 assertEquals(PolicyResult.SUCCESS, outcome.getResult());
285 public void testMakeRequest() throws CoderException {
286 Pair<String, SoRequest> pair = oper.makeRequest();
288 assertEquals("/my-service-instance-id/vnfs/my-vnf-id/vfModules/null", pair.getLeft());
290 verifyRequest("VfModuleDelete.json", pair.getRight());
294 public void testDelete() throws Exception {
295 SoRequest req = new SoRequest();
296 req.setRequestId(REQ_ID);
298 Map<String, Object> headers = Map.of("key-A", "value-A");
300 String reqText = oper.prettyPrint(req);
302 final CompletableFuture<Response> delFuture =
303 oper.delete("my-uri", headers, MediaType.APPLICATION_JSON, reqText, callback);
305 ArgumentCaptor<HttpRequest> reqCaptor = ArgumentCaptor.forClass(HttpRequest.class);
306 verify(javaClient).sendAsync(reqCaptor.capture(), any());
308 HttpRequest req2 = reqCaptor.getValue();
309 assertEquals("http://my-host:6969/my-uri", req2.uri().toString());
310 assertEquals("DELETE", req2.method());
312 HttpHeaders headers2 = req2.headers();
313 assertEquals("value-A", headers2.firstValue("key-A").orElse("missing-key"));
314 assertEquals(MediaType.APPLICATION_JSON, headers2.firstValue("Content-type").orElse("missing-key"));
316 assertTrue(delFuture.isDone());
317 Response resp = delFuture.get();
319 verify(callback).completed(resp);
321 assertEquals(200, resp.getStatus());
323 SoResponse resp2 = resp.readEntity(SoResponse.class);
324 assertEquals(SoOperation.COMPLETE, resp2.getRequest().getRequestStatus().getRequestState());
328 * Tests delete() when an exception is thrown in the future.
331 @SuppressWarnings("unchecked")
332 public void testDeleteException() throws Exception {
333 Throwable thrown = new IllegalStateException(EXPECTED_EXCEPTION);
335 // need a new future, with an exception
336 javaFuture = CompletableFuture.failedFuture(thrown);
337 when(javaClient.sendAsync(any(), any(BodyHandlers.ofString().getClass()))).thenReturn(javaFuture);
339 SoRequest req = new SoRequest();
340 req.setRequestId(REQ_ID);
342 String reqText = oper.prettyPrint(req);
344 CompletableFuture<Response> delFuture =
345 oper.delete("/my-uri", Map.of(), MediaType.APPLICATION_JSON, reqText, callback);
347 assertTrue(delFuture.isCompletedExceptionally());
349 ArgumentCaptor<Throwable> thrownCaptor = ArgumentCaptor.forClass(Throwable.class);
350 verify(callback).failed(thrownCaptor.capture());
351 assertSame(thrown, thrownCaptor.getValue().getCause());
355 * Tests addAuthHeader() when there is a username, but no password.
358 public void testAddAuthHeader() {
359 Builder builder = mock(Builder.class);
360 when(client.getUserName()).thenReturn("the-user");
361 when(client.getPassword()).thenReturn("the-password");
362 oper.addAuthHeader(builder);
364 ArgumentCaptor<String> keyCaptor = ArgumentCaptor.forClass(String.class);
365 ArgumentCaptor<String> valueCaptor = ArgumentCaptor.forClass(String.class);
367 verify(builder).header(keyCaptor.capture(), valueCaptor.capture());
369 assertEquals("Authorization", keyCaptor.getValue());
371 String encoded = Base64.getEncoder().encodeToString("the-user:the-password".getBytes(StandardCharsets.UTF_8));
372 assertEquals("Basic " + encoded, valueCaptor.getValue());
376 * Tests addAuthHeader() when there is no username.
379 public void testAddAuthHeaderNoUser() {
380 Builder builder = mock(Builder.class);
381 when(client.getPassword()).thenReturn("world");
382 oper.addAuthHeader(builder);
383 verify(builder, never()).header(any(), any());
385 // repeat with empty username
386 when(client.getUserName()).thenReturn("");
387 oper.addAuthHeader(builder);
388 verify(builder, never()).header(any(), any());
392 * Tests addAuthHeader() when there is a username, but no password.
395 public void testAddAuthHeaderUserOnly() {
396 Builder builder = mock(Builder.class);
397 when(client.getUserName()).thenReturn("my-user");
398 oper.addAuthHeader(builder);
400 ArgumentCaptor<String> keyCaptor = ArgumentCaptor.forClass(String.class);
401 ArgumentCaptor<String> valueCaptor = ArgumentCaptor.forClass(String.class);
403 verify(builder).header(keyCaptor.capture(), valueCaptor.capture());
405 assertEquals("Authorization", keyCaptor.getValue());
407 String encoded = Base64.getEncoder().encodeToString("my-user:".getBytes(StandardCharsets.UTF_8));
408 assertEquals("Basic " + encoded, valueCaptor.getValue());
412 public void testMakeHttpClient() {
413 // must use a real operation to invoke this method
414 assertNotNull(new MyOperation(params, config).makeHttpClient());
419 protected void makeContext() {
422 AaiCqResponse cq = mock(AaiCqResponse.class);
424 GenericVnf vnf = new GenericVnf();
425 when(cq.getGenericVnfByVfModuleModelInvariantId(MODEL_INVAR_ID)).thenReturn(vnf);
426 vnf.setVnfId(VNF_ID);
428 ServiceInstance instance = new ServiceInstance();
429 when(cq.getServiceInstance()).thenReturn(instance);
430 instance.setServiceInstanceId(SVC_INSTANCE_ID);
432 when(cq.getDefaultTenant()).thenReturn(new Tenant());
433 when(cq.getDefaultCloudRegion()).thenReturn(new CloudRegion());
435 ModelVer modelVers = new ModelVer();
436 when(cq.getModelVerByVersionId(any())).thenReturn(modelVers);
437 modelVers.setModelName(MODEL_NAME2);
438 modelVers.setModelVersion(MODEL_VERS2);
440 params.getContext().setProperty(AaiCqResponse.CONTEXT_KEY, cq);
443 private void initHostPort() {
444 when(client.getBaseUrl()).thenReturn("http://my-host:6969/");
447 @SuppressWarnings("unchecked")
448 private void configureResponse(String responseText) throws CoderException {
449 // indicate that the response was completed
450 when(javaResp.statusCode()).thenReturn(200);
451 when(javaResp.body()).thenReturn(responseText);
453 javaFuture = CompletableFuture.completedFuture(javaResp);
454 when(javaClient.sendAsync(any(), any(BodyHandlers.ofString().getClass()))).thenReturn(javaFuture);
457 private class MyOperation extends VfModuleDelete {
459 public MyOperation(ControlLoopOperationParams params, HttpPollingConfig config) {
460 super(params, config);
464 protected java.net.http.HttpClient makeHttpClient() {