Fix path issues
[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.Before;
43 import org.junit.Test;
44 import org.mockito.ArgumentCaptor;
45 import org.mockito.Captor;
46 import org.mockito.Mock;
47 import org.onap.policy.aai.AaiConstants;
48 import org.onap.policy.aai.AaiCqResponse;
49 import org.onap.policy.common.endpoints.http.client.HttpClientFactory;
50 import org.onap.policy.common.utils.coder.StandardCoder;
51 import org.onap.policy.common.utils.coder.StandardCoderObject;
52 import org.onap.policy.controlloop.actorserviceprovider.Operation;
53 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
54 import org.onap.policy.controlloop.actorserviceprovider.Util;
55 import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperator;
56 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
57 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpParams;
58 import org.onap.policy.controlloop.actorserviceprovider.spi.Actor;
59 import org.onap.policy.controlloop.policy.PolicyResult;
60
61 public class AaiCustomQueryOperationTest extends BasicAaiOperation<Map<String, String>> {
62     private static final StandardCoder coder = new StandardCoder();
63
64     private static final String MY_LINK = "my-link";
65     private static final String MY_VSERVER = "my-verserver-name";
66
67     @Captor
68     private ArgumentCaptor<Entity<Map<String, String>>> entityCaptor;
69
70     @Mock
71     private Actor tenantActor;
72
73     private AaiCustomQueryOperation oper;
74
75     public AaiCustomQueryOperationTest() {
76         super(AaiConstants.ACTOR_NAME, AaiCustomQueryOperation.NAME);
77     }
78
79     /**
80      * Sets up.
81      */
82     @Before
83     public void setUp() throws Exception {
84         super.setUpBasic();
85
86         params.getContext().getEnrichment().put(AaiCustomQueryOperation.VSERVER_VSERVER_NAME, MY_VSERVER);
87
88         MyTenantOperator tenantOperator = new MyTenantOperator();
89
90         when(service.getActor(AaiConstants.ACTOR_NAME)).thenReturn(tenantActor);
91         when(tenantActor.getOperator(AaiGetOperation.TENANT)).thenReturn(tenantOperator);
92
93         oper = new AaiCustomQueryOperation(params, config);
94     }
95
96     @Test
97     public void testAaiCustomQueryOperation() {
98         assertEquals(AaiConstants.ACTOR_NAME, oper.getActorName());
99         assertEquals(AaiCustomQueryOperation.NAME, oper.getName());
100         assertEquals(MY_VSERVER, oper.getVserver());
101
102         // verify that it works with an empty target entity
103         params = params.toBuilder().targetEntity("").build();
104         assertThatCode(() -> new AaiCustomQueryOperation(params, config)).doesNotThrowAnyException();
105
106         // try without enrichment data
107         params.getContext().getEnrichment().remove(AaiCustomQueryOperation.VSERVER_VSERVER_NAME);
108         assertThatIllegalArgumentException().isThrownBy(() -> new AaiCustomQueryOperation(params, config))
109                         .withMessage("missing " + AaiCustomQueryOperation.VSERVER_VSERVER_NAME + " in enrichment data");
110     }
111
112     @Test
113     @SuppressWarnings("unchecked")
114     public void testStartOperationAsync_testStartPreprocessorAsync_testMakeRequest_testPostProcess() throws Exception {
115         // need two responses
116         when(rawResponse.readEntity(String.class)).thenReturn(makeTenantReply()).thenReturn(makeCqReply());
117         when(webAsync.get(any(InvocationCallback.class))).thenAnswer(provideResponse(rawResponse));
118         when(webAsync.put(any(), any(InvocationCallback.class))).thenAnswer(provideResponse(rawResponse, 1));
119
120         CompletableFuture<OperationOutcome> future2 = oper.start();
121
122         assertEquals(PolicyResult.SUCCESS, getResult(future2));
123
124         // tenant response should have been cached within the context
125         assertNotNull(context.getProperty(AaiGetOperation.getTenantKey(MY_VSERVER)));
126
127         // custom query response should have been cached within the context
128         AaiCqResponse cqData = context.getProperty(AaiCqResponse.CONTEXT_KEY);
129         assertNotNull(cqData);
130     }
131
132     /**
133      * Tests when preprocessor step is not needed.
134      */
135     @Test
136     @SuppressWarnings("unchecked")
137     public void testStartOperationAsync_testStartPreprocessorAsyncNotNeeded() throws Exception {
138         // pre-load the tenant data
139         final StandardCoderObject data = preloadTenantData();
140
141         // only need one response
142         when(rawResponse.readEntity(String.class)).thenReturn(makeCqReply());
143         when(webAsync.put(any(), any(InvocationCallback.class))).thenAnswer(provideResponse(rawResponse, 1));
144
145         CompletableFuture<OperationOutcome> future2 = oper.start();
146
147         assertEquals(PolicyResult.SUCCESS, getResult(future2));
148
149         // should not have replaced tenant response
150         assertSame(data, context.getProperty(AaiGetOperation.getTenantKey(MY_VSERVER)));
151
152         // custom query response should have been cached within the context
153         AaiCqResponse cqData = context.getProperty(AaiCqResponse.CONTEXT_KEY);
154         assertNotNull(cqData);
155     }
156
157     @Test
158     public void testMakeHeaders() {
159         verifyHeaders(oper.makeHeaders());
160     }
161
162     @Test
163     @SuppressWarnings("unchecked")
164     public void testMakeRequest() throws Exception {
165         // preload
166         preloadTenantData();
167
168         when(rawResponse.readEntity(String.class)).thenReturn(makeCqReply());
169         when(webAsync.put(any(), any(InvocationCallback.class))).thenAnswer(provideResponse(rawResponse, 1));
170
171         oper.start();
172         executor.runAll(100);
173
174         verify(webAsync).put(entityCaptor.capture(), any(InvocationCallback.class));
175
176         // sort the request fields so they match the order in cq.json
177         Map<String, String> request = new TreeMap<>(entityCaptor.getValue().getEntity());
178
179         verifyRequest("cq.json", request);
180     }
181
182     @Test
183     @SuppressWarnings("unchecked")
184     public void testMakeRequestNoResourceLink() throws Exception {
185         // pre-load EMPTY tenant data
186         preloadTenantData(new StandardCoderObject());
187
188         when(rawResponse.readEntity(String.class)).thenReturn(makeCqReply());
189         when(webAsync.put(any(), any(InvocationCallback.class))).thenAnswer(provideResponse(rawResponse, 1));
190
191         CompletableFuture<OperationOutcome> future2 = oper.start();
192
193         assertEquals(PolicyResult.FAILURE_EXCEPTION, getResult(future2));
194     }
195
196     private String makeTenantReply() throws Exception {
197         Map<String, String> links = Map.of(AaiCustomQueryOperation.RESOURCE_LINK, MY_LINK);
198         List<Map<String, String>> data = Arrays.asList(links);
199
200         Map<String, Object> reply = Map.of(AaiCustomQueryOperation.RESULT_DATA, data);
201         return coder.encode(reply);
202     }
203
204     private String makeCqReply() {
205         return "{}";
206     }
207
208     private StandardCoderObject preloadTenantData() throws Exception {
209         StandardCoderObject data = coder.decode(makeTenantReply(), StandardCoderObject.class);
210         preloadTenantData(data);
211         return data;
212     }
213
214     private void preloadTenantData(StandardCoderObject data) {
215         context.setProperty(AaiGetOperation.getTenantKey(MY_VSERVER), data);
216     }
217
218     private PolicyResult getResult(CompletableFuture<OperationOutcome> future2)
219                     throws InterruptedException, ExecutionException, TimeoutException {
220
221         executor.runAll(100);
222         assertTrue(future2.isDone());
223
224         return future2.get().getResult();
225     }
226
227     protected class MyTenantOperator extends HttpOperator {
228         public MyTenantOperator() {
229             super(AaiConstants.ACTOR_NAME, AaiGetOperation.TENANT);
230
231             HttpParams http = HttpParams.builder().clientName(MY_CLIENT).path(PATH).timeoutSec(1).build();
232
233             configure(Util.translateToMap(AaiGetOperation.TENANT, http));
234             start();
235         }
236
237         @Override
238         public Operation buildOperation(ControlLoopOperationParams params) {
239             return new AaiGetOperation(params, getCurrentConfig());
240         }
241
242         @Override
243         protected HttpClientFactory getClientFactory() {
244             return factory;
245         }
246     }
247 }