Add subrequest ID to OperationOutcome
[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         assertEquals("1", future2.get().getSubRequestId());
132     }
133
134     /**
135      * Tests when preprocessor step is not needed.
136      */
137     @Test
138     @SuppressWarnings("unchecked")
139     public void testStartOperationAsync_testStartPreprocessorAsyncNotNeeded() throws Exception {
140         // pre-load the tenant data
141         final StandardCoderObject data = preloadTenantData();
142
143         // only need one response
144         when(rawResponse.readEntity(String.class)).thenReturn(makeCqReply());
145         when(webAsync.put(any(), any(InvocationCallback.class))).thenAnswer(provideResponse(rawResponse, 1));
146
147         CompletableFuture<OperationOutcome> future2 = oper.start();
148
149         assertEquals(PolicyResult.SUCCESS, getResult(future2));
150
151         // should not have replaced tenant response
152         assertSame(data, context.getProperty(AaiGetOperation.getTenantKey(MY_VSERVER)));
153
154         // custom query response should have been cached within the context
155         AaiCqResponse cqData = context.getProperty(AaiCqResponse.CONTEXT_KEY);
156         assertNotNull(cqData);
157     }
158
159     @Test
160     public void testMakeHeaders() {
161         verifyHeaders(oper.makeHeaders());
162     }
163
164     @Test
165     @SuppressWarnings("unchecked")
166     public void testMakeRequest() throws Exception {
167         // preload
168         preloadTenantData();
169
170         when(rawResponse.readEntity(String.class)).thenReturn(makeCqReply());
171         when(webAsync.put(any(), any(InvocationCallback.class))).thenAnswer(provideResponse(rawResponse, 1));
172
173         oper.start();
174         executor.runAll(100);
175
176         verify(webAsync).put(entityCaptor.capture(), any(InvocationCallback.class));
177
178         // sort the request fields so they match the order in cq.json
179         Map<String, String> request = new TreeMap<>(entityCaptor.getValue().getEntity());
180
181         verifyRequest("cq.json", request);
182     }
183
184     @Test
185     @SuppressWarnings("unchecked")
186     public void testMakeRequestNoResourceLink() throws Exception {
187         // pre-load EMPTY tenant data
188         preloadTenantData(new StandardCoderObject());
189
190         when(rawResponse.readEntity(String.class)).thenReturn(makeCqReply());
191         when(webAsync.put(any(), any(InvocationCallback.class))).thenAnswer(provideResponse(rawResponse, 1));
192
193         CompletableFuture<OperationOutcome> future2 = oper.start();
194
195         assertEquals(PolicyResult.FAILURE_EXCEPTION, getResult(future2));
196     }
197
198     private String makeTenantReply() throws Exception {
199         Map<String, String> links = Map.of(AaiCustomQueryOperation.RESOURCE_LINK, MY_LINK);
200         List<Map<String, String>> data = Arrays.asList(links);
201
202         Map<String, Object> reply = Map.of(AaiCustomQueryOperation.RESULT_DATA, data);
203         return coder.encode(reply);
204     }
205
206     private String makeCqReply() {
207         return "{}";
208     }
209
210     private StandardCoderObject preloadTenantData() throws Exception {
211         StandardCoderObject data = coder.decode(makeTenantReply(), StandardCoderObject.class);
212         preloadTenantData(data);
213         return data;
214     }
215
216     private void preloadTenantData(StandardCoderObject data) {
217         context.setProperty(AaiGetOperation.getTenantKey(MY_VSERVER), data);
218     }
219
220     private PolicyResult getResult(CompletableFuture<OperationOutcome> future2)
221                     throws InterruptedException, ExecutionException, TimeoutException {
222
223         executor.runAll(100);
224         assertTrue(future2.isDone());
225
226         return future2.get().getResult();
227     }
228
229     protected class MyTenantOperator extends HttpOperator {
230         public MyTenantOperator() {
231             super(AaiConstants.ACTOR_NAME, AaiGetOperation.TENANT);
232
233             HttpParams http = HttpParams.builder().clientName(MY_CLIENT).path(PATH).timeoutSec(1).build();
234
235             configure(Util.translateToMap(AaiGetOperation.TENANT, http));
236             start();
237         }
238
239         @Override
240         public Operation buildOperation(ControlLoopOperationParams params) {
241             return new AaiGetOperation(params, getCurrentConfig());
242         }
243
244         @Override
245         protected HttpClientFactory getClientFactory() {
246             return factory;
247         }
248     }
249 }