Set sub request ID before start callback
[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.assertThatCode;
24 import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertNotNull;
27 import static org.junit.Assert.assertSame;
28 import static org.junit.Assert.assertTrue;
29 import static org.mockito.ArgumentMatchers.any;
30 import static org.mockito.Mockito.verify;
31 import static org.mockito.Mockito.when;
32
33 import java.util.Arrays;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.TreeMap;
37 import java.util.concurrent.CompletableFuture;
38 import java.util.concurrent.ExecutionException;
39 import java.util.concurrent.TimeoutException;
40 import javax.ws.rs.client.Entity;
41 import javax.ws.rs.client.InvocationCallback;
42 import org.junit.AfterClass;
43 import org.junit.Before;
44 import org.junit.BeforeClass;
45 import org.junit.Test;
46 import org.mockito.ArgumentCaptor;
47 import org.mockito.Captor;
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.Operation;
56 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
57 import org.onap.policy.controlloop.actorserviceprovider.Util;
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<Map<String, String>> {
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     @Captor
73     private ArgumentCaptor<Entity<Map<String, String>>> entityCaptor;
74
75     @Mock
76     private Actor tenantActor;
77
78     private AaiCustomQueryOperation oper;
79
80     public AaiCustomQueryOperationTest() {
81         super(AaiConstants.ACTOR_NAME, AaiCustomQueryOperation.NAME);
82     }
83
84     @BeforeClass
85     public static void setUpBeforeClass() throws Exception {
86         initBeforeClass();
87     }
88
89     @AfterClass
90     public static void tearDownAfterClass() {
91         destroyAfterClass();
92     }
93
94     /**
95      * Sets up.
96      */
97     @Before
98     public void setUp() throws Exception {
99         super.setUpBasic();
100
101         params.getContext().getEnrichment().put(AaiCustomQueryOperation.VSERVER_VSERVER_NAME, MY_VSERVER);
102
103         MyTenantOperator tenantOperator = new MyTenantOperator();
104
105         when(service.getActor(AaiConstants.ACTOR_NAME)).thenReturn(tenantActor);
106         when(tenantActor.getOperator(AaiGetOperation.TENANT)).thenReturn(tenantOperator);
107
108         oper = new AaiCustomQueryOperation(params, config);
109     }
110
111     /**
112      * Tests "success" case with simulator.
113      */
114     @Test
115     public void testSuccess() throws Exception {
116         HttpParams opParams = HttpParams.builder().clientName(MY_CLIENT).path("v16/query").build();
117         config = new HttpConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory());
118
119         preloadTenantData();
120
121         params = params.toBuilder().targetEntity(SIM_VSERVER).retry(0).timeoutSec(5).executor(blockingExecutor).build();
122         oper = new AaiCustomQueryOperation(params, config);
123
124         outcome = oper.start().get();
125         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
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 testGenerateSubRequestId() {
146         oper.generateSubRequestId(3);
147         assertEquals("3", oper.getSubRequestId());
148     }
149
150     @Test
151     @SuppressWarnings("unchecked")
152     public void testStartOperationAsync_testStartPreprocessorAsync_testMakeRequest_testPostProcess() throws Exception {
153         // need two responses
154         when(rawResponse.readEntity(String.class)).thenReturn(makeTenantReply()).thenReturn(makeCqReply());
155         when(webAsync.get(any(InvocationCallback.class))).thenAnswer(provideResponse(rawResponse));
156         when(webAsync.put(any(), any(InvocationCallback.class))).thenAnswer(provideResponse(rawResponse, 1));
157
158         CompletableFuture<OperationOutcome> future2 = oper.start();
159
160         assertEquals(PolicyResult.SUCCESS, getResult(future2));
161
162         // tenant response should have been cached within the context
163         assertNotNull(context.getProperty(AaiGetOperation.getTenantKey(MY_VSERVER)));
164
165         // custom query response should have been cached within the context
166         AaiCqResponse cqData = context.getProperty(AaiCqResponse.CONTEXT_KEY);
167         assertNotNull(cqData);
168
169         assertEquals("1", future2.get().getSubRequestId());
170     }
171
172     /**
173      * Tests when preprocessor step is not needed.
174      */
175     @Test
176     @SuppressWarnings("unchecked")
177     public void testStartOperationAsync_testStartPreprocessorAsyncNotNeeded() throws Exception {
178         // pre-load the tenant data
179         final StandardCoderObject data = preloadTenantData();
180
181         // only need one response
182         when(rawResponse.readEntity(String.class)).thenReturn(makeCqReply());
183         when(webAsync.put(any(), any(InvocationCallback.class))).thenAnswer(provideResponse(rawResponse, 1));
184
185         CompletableFuture<OperationOutcome> future2 = oper.start();
186
187         assertEquals(PolicyResult.SUCCESS, getResult(future2));
188
189         // should not have replaced tenant response
190         assertSame(data, context.getProperty(AaiGetOperation.getTenantKey(MY_VSERVER)));
191
192         // custom query response should have been cached within the context
193         AaiCqResponse cqData = context.getProperty(AaiCqResponse.CONTEXT_KEY);
194         assertNotNull(cqData);
195     }
196
197     @Test
198     public void testMakeHeaders() {
199         verifyHeaders(oper.makeHeaders());
200     }
201
202     @Test
203     @SuppressWarnings("unchecked")
204     public void testMakeRequest() throws Exception {
205         // preload
206         preloadTenantData();
207
208         when(rawResponse.readEntity(String.class)).thenReturn(makeCqReply());
209         when(webAsync.put(any(), any(InvocationCallback.class))).thenAnswer(provideResponse(rawResponse, 1));
210
211         oper.start();
212         executor.runAll(100);
213
214         verify(webAsync).put(entityCaptor.capture(), any(InvocationCallback.class));
215
216         // sort the request fields so they match the order in cq.json
217         Map<String, String> request = new TreeMap<>(entityCaptor.getValue().getEntity());
218
219         verifyRequest("cq.json", request);
220     }
221
222     @Test
223     @SuppressWarnings("unchecked")
224     public void testMakeRequestNoResourceLink() throws Exception {
225         // pre-load EMPTY tenant data
226         preloadTenantData(new StandardCoderObject());
227
228         when(rawResponse.readEntity(String.class)).thenReturn(makeCqReply());
229         when(webAsync.put(any(), any(InvocationCallback.class))).thenAnswer(provideResponse(rawResponse, 1));
230
231         CompletableFuture<OperationOutcome> future2 = oper.start();
232
233         assertEquals(PolicyResult.FAILURE_EXCEPTION, getResult(future2));
234     }
235
236     private String makeTenantReply() throws Exception {
237         Map<String, String> links = Map.of(AaiCustomQueryOperation.RESOURCE_LINK, MY_LINK);
238         List<Map<String, String>> data = Arrays.asList(links);
239
240         Map<String, Object> reply = Map.of(AaiCustomQueryOperation.RESULT_DATA, data);
241         return coder.encode(reply);
242     }
243
244     private String makeCqReply() {
245         return "{}";
246     }
247
248     private StandardCoderObject preloadTenantData() throws Exception {
249         StandardCoderObject data = coder.decode(makeTenantReply(), StandardCoderObject.class);
250         preloadTenantData(data);
251         return data;
252     }
253
254     private void preloadTenantData(StandardCoderObject data) {
255         context.setProperty(AaiGetOperation.getTenantKey(MY_VSERVER), data);
256         context.setProperty(AaiGetOperation.getTenantKey(SIM_VSERVER), data);
257     }
258
259     private PolicyResult getResult(CompletableFuture<OperationOutcome> future2)
260                     throws InterruptedException, ExecutionException, TimeoutException {
261
262         executor.runAll(100);
263         assertTrue(future2.isDone());
264
265         return future2.get().getResult();
266     }
267
268     protected class MyTenantOperator extends HttpOperator {
269         public MyTenantOperator() {
270             super(AaiConstants.ACTOR_NAME, AaiGetOperation.TENANT);
271
272             HttpParams http = HttpParams.builder().clientName(MY_CLIENT).path(PATH).timeoutSec(1).build();
273
274             configure(Util.translateToMap(AaiGetOperation.TENANT, http));
275             start();
276         }
277
278         @Override
279         public Operation buildOperation(ControlLoopOperationParams params) {
280             return new AaiGetOperation(params, getCurrentConfig());
281         }
282
283         @Override
284         protected HttpClientFactory getClientFactory() {
285             return factory;
286         }
287     }
288 }