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.aai;
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.assertj.core.api.Assertions.assertThatCode;
25 import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
26 import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
27 import static org.junit.Assert.assertEquals;
28 import static org.junit.Assert.assertNotNull;
29 import static org.junit.Assert.assertNull;
30 import static org.junit.Assert.assertSame;
31 import static org.junit.Assert.assertTrue;
32 import static org.mockito.ArgumentMatchers.any;
33 import static org.mockito.Mockito.verify;
34 import static org.mockito.Mockito.when;
36 import java.util.Arrays;
37 import java.util.List;
39 import java.util.TreeMap;
40 import java.util.concurrent.CompletableFuture;
41 import java.util.concurrent.ExecutionException;
42 import java.util.concurrent.TimeoutException;
43 import javax.ws.rs.client.InvocationCallback;
44 import org.junit.AfterClass;
45 import org.junit.Before;
46 import org.junit.BeforeClass;
47 import org.junit.Test;
48 import org.mockito.Mock;
49 import org.onap.policy.aai.AaiConstants;
50 import org.onap.policy.aai.AaiCqResponse;
51 import org.onap.policy.common.endpoints.http.client.HttpClientFactory;
52 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
53 import org.onap.policy.common.utils.coder.StandardCoder;
54 import org.onap.policy.common.utils.coder.StandardCoderObject;
55 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
56 import org.onap.policy.controlloop.actorserviceprovider.OperationProperties;
57 import org.onap.policy.controlloop.actorserviceprovider.Util;
58 import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperation;
59 import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperator;
60 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
61 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig;
62 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpParams;
63 import org.onap.policy.controlloop.actorserviceprovider.spi.Actor;
64 import org.onap.policy.controlloop.policy.PolicyResult;
66 public class AaiCustomQueryOperationTest extends BasicAaiOperation {
67 private static final StandardCoder coder = new StandardCoder();
69 private static final String MY_LINK = "my-link";
70 private static final String MY_VSERVER = "my-vserver-name";
71 private static final String SIM_VSERVER = "OzVServer";
74 private Actor tenantActor;
76 private AaiCustomQueryOperation oper;
78 public AaiCustomQueryOperationTest() {
79 super(AaiConstants.ACTOR_NAME, AaiCustomQueryOperation.NAME);
83 public static void setUpBeforeClass() throws Exception {
88 public static void tearDownAfterClass() {
96 public void setUp() throws Exception {
99 params.getContext().getEnrichment().put(AaiCustomQueryOperation.VSERVER_VSERVER_NAME, MY_VSERVER);
101 MyTenantOperator tenantOperator = new MyTenantOperator();
103 when(service.getActor(AaiConstants.ACTOR_NAME)).thenReturn(tenantActor);
104 when(tenantActor.getOperator(AaiGetTenantOperation.NAME)).thenReturn(tenantOperator);
106 oper = new AaiCustomQueryOperation(params, config);
110 * Tests "success" case with simulator.
113 public void testSuccess() throws Exception {
114 HttpParams opParams = HttpParams.builder().clientName(MY_CLIENT).path("v16/query").build();
115 config = new HttpConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory());
117 params = params.toBuilder().targetEntity(SIM_VSERVER).retry(0).timeoutSec(5).executor(blockingExecutor)
118 .preprocessed(true).build();
119 oper = new AaiCustomQueryOperation(params, config);
121 oper.setProperty(OperationProperties.AAI_VSERVER_LINK, MY_LINK);
123 outcome = oper.start().get();
124 assertEquals(PolicyResult.SUCCESS, outcome.getResult());
126 String resp = outcome.getResponse();
127 assertThat(resp).isNotNull().contains("relationship-list");
131 public void testConstructor() {
132 assertEquals(AaiConstants.ACTOR_NAME, oper.getActorName());
133 assertEquals(AaiCustomQueryOperation.NAME, oper.getName());
135 // verify that it works with an empty target entity
136 params = params.toBuilder().targetEntity("").build();
137 assertThatCode(() -> new AaiCustomQueryOperation(params, config)).doesNotThrowAnyException();
141 public void testGetVserver() {
142 assertEquals(MY_VSERVER, oper.getVserver());
144 // try without enrichment data
145 params.getContext().getEnrichment().remove(AaiCustomQueryOperation.VSERVER_VSERVER_NAME);
146 assertThatIllegalArgumentException().isThrownBy(() -> oper.getVserver())
147 .withMessage("missing " + AaiCustomQueryOperation.VSERVER_VSERVER_NAME + " in enrichment data");
151 public void testGetPropertyNames() {
152 assertThat(oper.getPropertyNames()).isEqualTo(List.of(OperationProperties.AAI_VSERVER_LINK));
156 public void testGenerateSubRequestId() {
157 oper.generateSubRequestId(3);
158 assertEquals("3", oper.getSubRequestId());
162 * Tests startPreprocessorAsync(), when preprocessing is disabled.
165 public void testStartPreprocessorAsyncDisabled() {
166 params = params.toBuilder().preprocessed(true).build();
167 assertNull(new AaiCustomQueryOperation(params, config).startPreprocessorAsync());
171 @SuppressWarnings("unchecked")
172 public void testStartOperationAsync_testStartPreprocessorAsync_testMakeRequest_testPostProcess() throws Exception {
173 // need two responses
174 when(rawResponse.readEntity(String.class)).thenReturn(makeTenantReply()).thenReturn(makeCqReply());
175 when(webAsync.get(any(InvocationCallback.class))).thenAnswer(provideResponse(rawResponse));
176 when(webAsync.put(any(), any(InvocationCallback.class))).thenAnswer(provideResponse(rawResponse, 1));
178 CompletableFuture<OperationOutcome> future2 = oper.start();
180 assertEquals(PolicyResult.SUCCESS, getResult(future2));
182 // tenant response should have been cached within the context
183 assertNotNull(context.getProperty(AaiGetTenantOperation.getKey(MY_VSERVER)));
185 // custom query response should have been cached within the context
186 AaiCqResponse cqData = context.getProperty(AaiCqResponse.CONTEXT_KEY);
187 assertNotNull(cqData);
189 assertEquals("1", future2.get().getSubRequestId());
193 * Tests when preprocessor step is not needed.
196 @SuppressWarnings("unchecked")
197 public void testStartOperationAsync_testStartPreprocessorAsyncNotNeeded() throws Exception {
198 // pre-load the tenant data
199 final StandardCoderObject data = preloadTenantData();
201 // only need one response
202 when(rawResponse.readEntity(String.class)).thenReturn(makeCqReply());
203 when(webAsync.put(any(), any(InvocationCallback.class))).thenAnswer(provideResponse(rawResponse, 1));
205 CompletableFuture<OperationOutcome> future2 = oper.start();
207 assertEquals(PolicyResult.SUCCESS, getResult(future2));
209 // should not have replaced tenant response
210 assertSame(data, context.getProperty(AaiGetTenantOperation.getKey(MY_VSERVER)));
212 // custom query response should have been cached within the context
213 AaiCqResponse cqData = context.getProperty(AaiCqResponse.CONTEXT_KEY);
214 assertNotNull(cqData);
218 public void testMakeHeaders() {
219 verifyHeaders(oper.makeHeaders());
223 @SuppressWarnings("unchecked")
224 public void testMakeRequest_testGetVserverLink() throws Exception {
228 when(rawResponse.readEntity(String.class)).thenReturn(makeCqReply());
229 when(webAsync.put(any(), any(InvocationCallback.class))).thenAnswer(provideResponse(rawResponse, 1));
232 executor.runAll(100);
234 verify(webAsync).put(requestCaptor.capture(), any(InvocationCallback.class));
236 String reqText = requestCaptor.getValue().getEntity();
237 Map<String, String> reqMap = coder.decode(reqText, Map.class);
239 // sort the request fields so they match the order in cq.json
240 Map<String, String> request = new TreeMap<>(reqMap);
242 verifyRequest("cq.json", request);
246 public void testGetVserverLinkViaProperty() throws Exception {
247 oper.setProperty(OperationProperties.AAI_VSERVER_LINK, MY_LINK);
248 assertEquals(MY_LINK, oper.getVserverLink());
252 public void testGetVserverLinkNoTenantData() throws Exception {
253 assertThatIllegalStateException().isThrownBy(() -> oper.getVserverLink())
254 .withMessage("cannot perform custom query - cannot determine resource-link");
258 public void testGetVserverLinkNoResourceLink() throws Exception {
259 // pre-load EMPTY tenant data
260 preloadTenantData(new StandardCoderObject());
262 assertThatIllegalArgumentException().isThrownBy(() -> oper.getVserverLink())
263 .withMessage("cannot perform custom query - no resource-link");
266 private String makeTenantReply() throws Exception {
267 Map<String, String> links = Map.of(AaiCustomQueryOperation.RESOURCE_LINK, MY_LINK);
268 List<Map<String, String>> data = Arrays.asList(links);
270 Map<String, Object> reply = Map.of(AaiCustomQueryOperation.RESULT_DATA, data);
271 return coder.encode(reply);
274 private String makeCqReply() {
278 private StandardCoderObject preloadTenantData() throws Exception {
279 StandardCoderObject data = coder.decode(makeTenantReply(), StandardCoderObject.class);
280 preloadTenantData(data);
284 private void preloadTenantData(StandardCoderObject data) {
285 context.setProperty(AaiGetTenantOperation.getKey(MY_VSERVER), data);
286 context.setProperty(AaiGetTenantOperation.getKey(SIM_VSERVER), data);
289 private PolicyResult getResult(CompletableFuture<OperationOutcome> future2)
290 throws InterruptedException, ExecutionException, TimeoutException {
292 executor.runAll(100);
293 assertTrue(future2.isDone());
295 return future2.get().getResult();
298 protected class MyTenantOperator extends HttpOperator {
299 public MyTenantOperator() {
300 super(AaiConstants.ACTOR_NAME, AaiGetTenantOperation.NAME);
302 HttpParams http = HttpParams.builder().clientName(MY_CLIENT).path(PATH).timeoutSec(1).build();
304 configure(Util.translateToMap(AaiGetTenantOperation.NAME, http));
309 public HttpOperation<?> buildOperation(ControlLoopOperationParams params) {
310 return new AaiGetTenantOperation(params, getCurrentConfig());
314 protected HttpClientFactory getClientFactory() {