476e6432df8827a76946910c8c40918e15fe4a6f
[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.junit.Assert.assertEquals;
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.verify;
33 import static org.mockito.Mockito.when;
34
35 import java.util.Arrays;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.TreeMap;
39 import java.util.concurrent.CompletableFuture;
40 import java.util.concurrent.ExecutionException;
41 import java.util.concurrent.TimeoutException;
42 import javax.ws.rs.client.InvocationCallback;
43 import org.junit.AfterClass;
44 import org.junit.Before;
45 import org.junit.BeforeClass;
46 import org.junit.Test;
47 import org.mockito.Mock;
48 import org.onap.policy.aai.AaiConstants;
49 import org.onap.policy.aai.AaiCqResponse;
50 import org.onap.policy.common.endpoints.http.client.HttpClientFactory;
51 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
52 import org.onap.policy.common.utils.coder.StandardCoder;
53 import org.onap.policy.common.utils.coder.StandardCoderObject;
54 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
55 import org.onap.policy.controlloop.actorserviceprovider.OperationProperties;
56 import org.onap.policy.controlloop.actorserviceprovider.Util;
57 import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperation;
58 import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperator;
59 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
60 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig;
61 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpParams;
62 import org.onap.policy.controlloop.actorserviceprovider.spi.Actor;
63 import org.onap.policy.controlloop.policy.PolicyResult;
64
65 public class AaiCustomQueryOperationTest extends BasicAaiOperation {
66     private static final StandardCoder coder = new StandardCoder();
67
68     private static final String MY_LINK = "my-link";
69     private static final String MY_VSERVER = "my-vserver-name";
70     private static final String SIM_VSERVER = "OzVServer";
71
72     @Mock
73     private Actor tenantActor;
74
75     private AaiCustomQueryOperation oper;
76
77     public AaiCustomQueryOperationTest() {
78         super(AaiConstants.ACTOR_NAME, AaiCustomQueryOperation.NAME);
79     }
80
81     @BeforeClass
82     public static void setUpBeforeClass() throws Exception {
83         initBeforeClass();
84     }
85
86     @AfterClass
87     public static void tearDownAfterClass() {
88         destroyAfterClass();
89     }
90
91     /**
92      * Sets up.
93      */
94     @Before
95     public void setUp() throws Exception {
96         super.setUpBasic();
97
98         params.getContext().getEnrichment().put(AaiCustomQueryOperation.VSERVER_VSERVER_NAME, MY_VSERVER);
99
100         MyTenantOperator tenantOperator = new MyTenantOperator();
101
102         when(service.getActor(AaiConstants.ACTOR_NAME)).thenReturn(tenantActor);
103         when(tenantActor.getOperator(AaiGetTenantOperation.NAME)).thenReturn(tenantOperator);
104
105         oper = new AaiCustomQueryOperation(params, config);
106     }
107
108     /**
109      * Tests "success" case with simulator.
110      */
111     @Test
112     public void testSuccess() throws Exception {
113         HttpParams opParams = HttpParams.builder().clientName(MY_CLIENT).path("v16/query").build();
114         config = new HttpConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory());
115
116         preloadTenantData();
117
118         params = params.toBuilder().targetEntity(SIM_VSERVER).retry(0).timeoutSec(5).executor(blockingExecutor).build();
119         oper = new AaiCustomQueryOperation(params, config);
120
121         outcome = oper.start().get();
122         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
123
124         String resp = outcome.getResponse();
125         assertThat(resp).isNotNull().contains("relationship-list");
126     }
127
128     @Test
129     public void testConstructor() {
130         assertEquals(AaiConstants.ACTOR_NAME, oper.getActorName());
131         assertEquals(AaiCustomQueryOperation.NAME, oper.getName());
132         assertEquals(MY_VSERVER, oper.getVserver());
133
134         // verify that it works with an empty target entity
135         params = params.toBuilder().targetEntity("").build();
136         assertThatCode(() -> new AaiCustomQueryOperation(params, config)).doesNotThrowAnyException();
137
138         // try without enrichment data
139         params.getContext().getEnrichment().remove(AaiCustomQueryOperation.VSERVER_VSERVER_NAME);
140         assertThatIllegalArgumentException().isThrownBy(() -> new AaiCustomQueryOperation(params, config))
141                         .withMessage("missing " + AaiCustomQueryOperation.VSERVER_VSERVER_NAME + " in enrichment data");
142     }
143
144     @Test
145     public void testGetPropertyNames() {
146         assertThat(oper.getPropertyNames()).isEqualTo(List.of(OperationProperties.AAI_VSERVER_LINK));
147     }
148
149     @Test
150     public void testGenerateSubRequestId() {
151         oper.generateSubRequestId(3);
152         assertEquals("3", oper.getSubRequestId());
153     }
154
155     /**
156      * Tests startPreprocessorAsync(), when preprocessing is disabled.
157      */
158     @Test
159     public void testStartPreprocessorAsyncDisabled() {
160         params = params.toBuilder().preprocessed(true).build();
161         assertNull(new AaiCustomQueryOperation(params, config).startPreprocessorAsync());
162     }
163
164     @Test
165     @SuppressWarnings("unchecked")
166     public void testStartOperationAsync_testStartPreprocessorAsync_testMakeRequest_testPostProcess() throws Exception {
167         // need two responses
168         when(rawResponse.readEntity(String.class)).thenReturn(makeTenantReply()).thenReturn(makeCqReply());
169         when(webAsync.get(any(InvocationCallback.class))).thenAnswer(provideResponse(rawResponse));
170         when(webAsync.put(any(), any(InvocationCallback.class))).thenAnswer(provideResponse(rawResponse, 1));
171
172         CompletableFuture<OperationOutcome> future2 = oper.start();
173
174         assertEquals(PolicyResult.SUCCESS, getResult(future2));
175
176         // tenant response should have been cached within the context
177         assertNotNull(context.getProperty(AaiGetTenantOperation.getKey(MY_VSERVER)));
178
179         // custom query response should have been cached within the context
180         AaiCqResponse cqData = context.getProperty(AaiCqResponse.CONTEXT_KEY);
181         assertNotNull(cqData);
182
183         assertEquals("1", future2.get().getSubRequestId());
184     }
185
186     /**
187      * Tests when preprocessor step is not needed.
188      */
189     @Test
190     @SuppressWarnings("unchecked")
191     public void testStartOperationAsync_testStartPreprocessorAsyncNotNeeded() throws Exception {
192         // pre-load the tenant data
193         final StandardCoderObject data = preloadTenantData();
194
195         // only need one response
196         when(rawResponse.readEntity(String.class)).thenReturn(makeCqReply());
197         when(webAsync.put(any(), any(InvocationCallback.class))).thenAnswer(provideResponse(rawResponse, 1));
198
199         CompletableFuture<OperationOutcome> future2 = oper.start();
200
201         assertEquals(PolicyResult.SUCCESS, getResult(future2));
202
203         // should not have replaced tenant response
204         assertSame(data, context.getProperty(AaiGetTenantOperation.getKey(MY_VSERVER)));
205
206         // custom query response should have been cached within the context
207         AaiCqResponse cqData = context.getProperty(AaiCqResponse.CONTEXT_KEY);
208         assertNotNull(cqData);
209     }
210
211     @Test
212     public void testMakeHeaders() {
213         verifyHeaders(oper.makeHeaders());
214     }
215
216     @Test
217     @SuppressWarnings("unchecked")
218     public void testMakeRequest() throws Exception {
219         // preload
220         preloadTenantData();
221
222         when(rawResponse.readEntity(String.class)).thenReturn(makeCqReply());
223         when(webAsync.put(any(), any(InvocationCallback.class))).thenAnswer(provideResponse(rawResponse, 1));
224
225         oper.start();
226         executor.runAll(100);
227
228         verify(webAsync).put(requestCaptor.capture(), any(InvocationCallback.class));
229
230         String reqText = requestCaptor.getValue().getEntity();
231         Map<String, String> reqMap = coder.decode(reqText, Map.class);
232
233         // sort the request fields so they match the order in cq.json
234         Map<String, String> request = new TreeMap<>(reqMap);
235
236         verifyRequest("cq.json", request);
237     }
238
239     @Test
240     @SuppressWarnings("unchecked")
241     public void testMakeRequestNoResourceLink() throws Exception {
242         // pre-load EMPTY tenant data
243         preloadTenantData(new StandardCoderObject());
244
245         when(rawResponse.readEntity(String.class)).thenReturn(makeCqReply());
246         when(webAsync.put(any(), any(InvocationCallback.class))).thenAnswer(provideResponse(rawResponse, 1));
247
248         CompletableFuture<OperationOutcome> future2 = oper.start();
249
250         assertEquals(PolicyResult.FAILURE_EXCEPTION, getResult(future2));
251     }
252
253     private String makeTenantReply() throws Exception {
254         Map<String, String> links = Map.of(AaiCustomQueryOperation.RESOURCE_LINK, MY_LINK);
255         List<Map<String, String>> data = Arrays.asList(links);
256
257         Map<String, Object> reply = Map.of(AaiCustomQueryOperation.RESULT_DATA, data);
258         return coder.encode(reply);
259     }
260
261     private String makeCqReply() {
262         return "{}";
263     }
264
265     private StandardCoderObject preloadTenantData() throws Exception {
266         StandardCoderObject data = coder.decode(makeTenantReply(), StandardCoderObject.class);
267         preloadTenantData(data);
268         return data;
269     }
270
271     private void preloadTenantData(StandardCoderObject data) {
272         context.setProperty(AaiGetTenantOperation.getKey(MY_VSERVER), data);
273         context.setProperty(AaiGetTenantOperation.getKey(SIM_VSERVER), data);
274     }
275
276     private PolicyResult getResult(CompletableFuture<OperationOutcome> future2)
277                     throws InterruptedException, ExecutionException, TimeoutException {
278
279         executor.runAll(100);
280         assertTrue(future2.isDone());
281
282         return future2.get().getResult();
283     }
284
285     protected class MyTenantOperator extends HttpOperator {
286         public MyTenantOperator() {
287             super(AaiConstants.ACTOR_NAME, AaiGetTenantOperation.NAME);
288
289             HttpParams http = HttpParams.builder().clientName(MY_CLIENT).path(PATH).timeoutSec(1).build();
290
291             configure(Util.translateToMap(AaiGetTenantOperation.NAME, http));
292             start();
293         }
294
295         @Override
296         public HttpOperation<?> buildOperation(ControlLoopOperationParams params) {
297             return new AaiGetTenantOperation(params, getCurrentConfig());
298         }
299
300         @Override
301         protected HttpClientFactory getClientFactory() {
302             return factory;
303         }
304     }
305 }