f1225373e5166ce28eb4abd68626ef2df62c92ed
[policy/models.git] / models-interactions / model-actors / actor.aai / src / test / java / org / onap / policy / controlloop / actor / aai / AaiCustomQueryOperationTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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=========================================================
19  */
20
21 package org.onap.policy.controlloop.actor.aai;
22
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;
35
36 import java.util.Arrays;
37 import java.util.List;
38 import java.util.Map;
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;
65
66 public class AaiCustomQueryOperationTest extends BasicAaiOperation {
67     private static final StandardCoder coder = new StandardCoder();
68
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";
72
73     @Mock
74     private Actor tenantActor;
75
76     private AaiCustomQueryOperation oper;
77
78     public AaiCustomQueryOperationTest() {
79         super(AaiConstants.ACTOR_NAME, AaiCustomQueryOperation.NAME);
80     }
81
82     @BeforeClass
83     public static void setUpBeforeClass() throws Exception {
84         initBeforeClass();
85     }
86
87     @AfterClass
88     public static void tearDownAfterClass() {
89         destroyAfterClass();
90     }
91
92     /**
93      * Sets up.
94      */
95     @Before
96     public void setUp() throws Exception {
97         super.setUpBasic();
98
99         params.getContext().getEnrichment().put(AaiCustomQueryOperation.VSERVER_VSERVER_NAME, MY_VSERVER);
100
101         MyTenantOperator tenantOperator = new MyTenantOperator();
102
103         when(service.getActor(AaiConstants.ACTOR_NAME)).thenReturn(tenantActor);
104         when(tenantActor.getOperator(AaiGetTenantOperation.NAME)).thenReturn(tenantOperator);
105
106         oper = new AaiCustomQueryOperation(params, config);
107     }
108
109     /**
110      * Tests "success" case with simulator.
111      */
112     @Test
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());
116
117         params = params.toBuilder().targetEntity(SIM_VSERVER).retry(0).timeoutSec(5).executor(blockingExecutor)
118                         .preprocessed(true).build();
119         oper = new AaiCustomQueryOperation(params, config);
120
121         oper.setProperty(OperationProperties.AAI_VSERVER_LINK, MY_LINK);
122
123         outcome = oper.start().get();
124         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
125
126         String resp = outcome.getResponse();
127         assertThat(resp).isNotNull().contains("relationship-list");
128     }
129
130     @Test
131     public void testConstructor() {
132         assertEquals(AaiConstants.ACTOR_NAME, oper.getActorName());
133         assertEquals(AaiCustomQueryOperation.NAME, oper.getName());
134
135         // verify that it works with an empty target entity
136         params = params.toBuilder().targetEntity("").build();
137         assertThatCode(() -> new AaiCustomQueryOperation(params, config)).doesNotThrowAnyException();
138     }
139
140     @Test
141     public void testGetVserver() {
142         assertEquals(MY_VSERVER, oper.getVserver());
143
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");
148     }
149
150     @Test
151     public void testGetPropertyNames() {
152         assertThat(oper.getPropertyNames()).isEqualTo(List.of(OperationProperties.AAI_VSERVER_LINK));
153     }
154
155     @Test
156     public void testGenerateSubRequestId() {
157         oper.generateSubRequestId(3);
158         assertEquals("3", oper.getSubRequestId());
159     }
160
161     /**
162      * Tests startPreprocessorAsync(), when preprocessing is disabled.
163      */
164     @Test
165     public void testStartPreprocessorAsyncDisabled() {
166         params = params.toBuilder().preprocessed(true).build();
167         assertNull(new AaiCustomQueryOperation(params, config).startPreprocessorAsync());
168     }
169
170     @Test
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));
177
178         CompletableFuture<OperationOutcome> future2 = oper.start();
179
180         assertEquals(PolicyResult.SUCCESS, getResult(future2));
181
182         // tenant response should have been cached within the context
183         assertNotNull(context.getProperty(AaiGetTenantOperation.getKey(MY_VSERVER)));
184
185         // custom query response should have been cached within the context
186         AaiCqResponse cqData = context.getProperty(AaiCqResponse.CONTEXT_KEY);
187         assertNotNull(cqData);
188
189         assertEquals("1", future2.get().getSubRequestId());
190     }
191
192     /**
193      * Tests when preprocessor step is not needed.
194      */
195     @Test
196     @SuppressWarnings("unchecked")
197     public void testStartOperationAsync_testStartPreprocessorAsyncNotNeeded() throws Exception {
198         // pre-load the tenant data
199         final StandardCoderObject data = preloadTenantData();
200
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));
204
205         CompletableFuture<OperationOutcome> future2 = oper.start();
206
207         assertEquals(PolicyResult.SUCCESS, getResult(future2));
208
209         // should not have replaced tenant response
210         assertSame(data, context.getProperty(AaiGetTenantOperation.getKey(MY_VSERVER)));
211
212         // custom query response should have been cached within the context
213         AaiCqResponse cqData = context.getProperty(AaiCqResponse.CONTEXT_KEY);
214         assertNotNull(cqData);
215     }
216
217     @Test
218     public void testMakeHeaders() {
219         verifyHeaders(oper.makeHeaders());
220     }
221
222     @Test
223     @SuppressWarnings("unchecked")
224     public void testMakeRequest_testGetVserverLink() throws Exception {
225         // preload
226         preloadTenantData();
227
228         when(rawResponse.readEntity(String.class)).thenReturn(makeCqReply());
229         when(webAsync.put(any(), any(InvocationCallback.class))).thenAnswer(provideResponse(rawResponse, 1));
230
231         oper.start();
232         executor.runAll(100);
233
234         verify(webAsync).put(requestCaptor.capture(), any(InvocationCallback.class));
235
236         String reqText = requestCaptor.getValue().getEntity();
237         Map<String, String> reqMap = coder.decode(reqText, Map.class);
238
239         // sort the request fields so they match the order in cq.json
240         Map<String, String> request = new TreeMap<>(reqMap);
241
242         verifyRequest("cq.json", request);
243     }
244
245     @Test
246     public void testGetVserverLinkViaProperty() throws Exception {
247         oper.setProperty(OperationProperties.AAI_VSERVER_LINK, MY_LINK);
248         assertEquals(MY_LINK, oper.getVserverLink());
249     }
250
251     @Test
252     public void testGetVserverLinkNoTenantData() throws Exception {
253         assertThatIllegalStateException().isThrownBy(() -> oper.getVserverLink())
254                         .withMessage("cannot perform custom query - cannot determine resource-link");
255     }
256
257     @Test
258     public void testGetVserverLinkNoResourceLink() throws Exception {
259         // pre-load EMPTY tenant data
260         preloadTenantData(new StandardCoderObject());
261
262         assertThatIllegalArgumentException().isThrownBy(() -> oper.getVserverLink())
263                         .withMessage("cannot perform custom query - no resource-link");
264     }
265
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);
269
270         Map<String, Object> reply = Map.of(AaiCustomQueryOperation.RESULT_DATA, data);
271         return coder.encode(reply);
272     }
273
274     private String makeCqReply() {
275         return "{}";
276     }
277
278     private StandardCoderObject preloadTenantData() throws Exception {
279         StandardCoderObject data = coder.decode(makeTenantReply(), StandardCoderObject.class);
280         preloadTenantData(data);
281         return data;
282     }
283
284     private void preloadTenantData(StandardCoderObject data) {
285         context.setProperty(AaiGetTenantOperation.getKey(MY_VSERVER), data);
286         context.setProperty(AaiGetTenantOperation.getKey(SIM_VSERVER), data);
287     }
288
289     private PolicyResult getResult(CompletableFuture<OperationOutcome> future2)
290                     throws InterruptedException, ExecutionException, TimeoutException {
291
292         executor.runAll(100);
293         assertTrue(future2.isDone());
294
295         return future2.get().getResult();
296     }
297
298     protected class MyTenantOperator extends HttpOperator {
299         public MyTenantOperator() {
300             super(AaiConstants.ACTOR_NAME, AaiGetTenantOperation.NAME);
301
302             HttpParams http = HttpParams.builder().clientName(MY_CLIENT).path(PATH).timeoutSec(1).build();
303
304             configure(Util.translateToMap(AaiGetTenantOperation.NAME, http));
305             start();
306         }
307
308         @Override
309         public HttpOperation<?> buildOperation(ControlLoopOperationParams params) {
310             return new AaiGetTenantOperation(params, getCurrentConfig());
311         }
312
313         @Override
314         protected HttpClientFactory getClientFactory() {
315             return factory;
316         }
317     }
318 }