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