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