Add property lists to Actors
[policy/models.git] / models-interactions / model-actors / actor.so / src / test / java / org / onap / policy / controlloop / actor / so / SoOperationTest.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.so;
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.assertFalse;
27 import static org.junit.Assert.assertNotNull;
28 import static org.junit.Assert.assertNull;
29 import static org.junit.Assert.assertSame;
30 import static org.junit.Assert.assertTrue;
31 import static org.mockito.Mockito.mock;
32 import static org.mockito.Mockito.when;
33
34 import java.time.LocalDateTime;
35 import java.time.Month;
36 import java.util.Collections;
37 import java.util.List;
38 import java.util.concurrent.CompletableFuture;
39 import java.util.function.Consumer;
40 import java.util.function.Supplier;
41 import org.junit.Before;
42 import org.junit.Test;
43 import org.onap.aai.domain.yang.CloudRegion;
44 import org.onap.aai.domain.yang.GenericVnf;
45 import org.onap.aai.domain.yang.ServiceInstance;
46 import org.onap.aai.domain.yang.Tenant;
47 import org.onap.policy.aai.AaiCqResponse;
48 import org.onap.policy.common.utils.coder.Coder;
49 import org.onap.policy.common.utils.coder.CoderException;
50 import org.onap.policy.controlloop.ControlLoopOperation;
51 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
52 import org.onap.policy.controlloop.policy.PolicyResult;
53 import org.onap.policy.so.SoModelInfo;
54 import org.onap.policy.so.SoRequest;
55 import org.onap.policy.so.SoRequestInfo;
56 import org.onap.policy.so.SoRequestStatus;
57 import org.onap.policy.so.SoResponse;
58
59 public class SoOperationTest extends BasicSoOperation {
60
61     private static final String VF_COUNT_KEY = SoConstants.VF_COUNT_PREFIX
62                     + "[my-model-customization-id][my-model-invariant-id][my-model-version-id]";
63
64     private static final List<String> PROP_NAMES = Collections.emptyList();
65
66     private SoOperation oper;
67
68     /**
69      * Sets up.
70      */
71     @Before
72     public void setUp() throws Exception {
73         super.setUp();
74
75         initConfig();
76
77         oper = new SoOperation(params, config, PROP_NAMES) {};
78     }
79
80     @Test
81     public void testConstructor() {
82         assertEquals(DEFAULT_ACTOR, oper.getActorName());
83         assertEquals(DEFAULT_OPERATION, oper.getName());
84         assertSame(config, oper.getConfig());
85         assertTrue(oper.isUsePolling());
86
87         // check when Target is null
88         params = params.toBuilder().target(null).build();
89         assertThatIllegalArgumentException().isThrownBy(() -> new SoOperation(params, config, PROP_NAMES) {})
90                         .withMessageContaining("Target information");
91     }
92
93     @Test
94     public void testValidateTarget() {
95         // check when various fields are null
96         verifyNotNull("modelCustomizationId", target::getModelCustomizationId, target::setModelCustomizationId);
97         verifyNotNull("modelInvariantId", target::getModelInvariantId, target::setModelInvariantId);
98         verifyNotNull("modelVersionId", target::getModelVersionId, target::setModelVersionId);
99
100         // verify it's still valid
101         assertThatCode(() -> new VfModuleCreate(params, config)).doesNotThrowAnyException();
102     }
103
104     private void verifyNotNull(String expectedText, Supplier<String> getter, Consumer<String> setter) {
105         String originalValue = getter.get();
106
107         // try with null
108         setter.accept(null);
109         assertThatIllegalArgumentException().isThrownBy(() -> new VfModuleCreate(params, config))
110                         .withMessageContaining(expectedText);
111
112         setter.accept(originalValue);
113     }
114
115     @Test
116     public void testStartPreprocessorAsync() {
117         assertNotNull(oper.startPreprocessorAsync());
118     }
119
120     @Test
121     public void testObtainVfCount_testGetVfCount_testSetVfCount() throws Exception {
122         // insert CQ data so it's there for the check
123         context.setProperty(AaiCqResponse.CONTEXT_KEY, makeCqResponse());
124
125         // shouldn't actually need to do anything
126         assertNull(oper.obtainVfCount());
127
128         // verify that the count was stored
129         Integer vfcount = context.getProperty(VF_COUNT_KEY);
130         assertEquals(VF_COUNT, vfcount);
131         assertEquals(VF_COUNT.intValue(), oper.getVfCount());
132
133         // change the count and then verify that it isn't overwritten by another call
134         oper.setVfCount(VF_COUNT + 1);
135
136         assertNull(oper.obtainVfCount());
137         vfcount = context.getProperty(VF_COUNT_KEY);
138         assertEquals(VF_COUNT + 1, vfcount.intValue());
139         assertEquals(VF_COUNT + 1, oper.getVfCount());
140     }
141
142     /**
143      * Tests obtainVfCount() when it actually has to query.
144      */
145     @Test
146     public void testObtainVfCountQuery() throws Exception {
147         CompletableFuture<OperationOutcome> future2 = oper.obtainVfCount();
148         assertNotNull(future2);
149         assertTrue(executor.runAll(100));
150
151         // not done yet
152         assertFalse(future2.isDone());
153
154         provideCqResponse(makeCqResponse());
155
156         assertTrue(executor.runAll(100));
157         assertTrue(future2.isDone());
158         assertEquals(PolicyResult.SUCCESS, future2.get().getResult());
159
160         // verify that the count was stored
161         Integer vfcount = context.getProperty(VF_COUNT_KEY);
162         assertEquals(VF_COUNT, vfcount);
163
164         // repeat - shouldn't need to do anything now
165         assertNull(oper.obtainVfCount());
166     }
167
168     @Test
169     public void testGetRequestState() {
170         SoResponse resp = new SoResponse();
171         assertNull(oper.getRequestState(resp));
172
173         SoRequest req = new SoRequest();
174         resp.setRequest(req);
175         assertNull(oper.getRequestState(resp));
176
177         SoRequestStatus status = new SoRequestStatus();
178         req.setRequestStatus(status);
179         assertNull(oper.getRequestState(resp));
180
181         status.setRequestState("my-state");
182         assertEquals("my-state", oper.getRequestState(resp));
183     }
184
185     @Test
186     public void testIsSuccess() {
187         // always true
188
189         assertTrue(oper.isSuccess(rawResponse, response));
190
191         when(rawResponse.getStatus()).thenReturn(500);
192         assertTrue(oper.isSuccess(rawResponse, response));
193     }
194
195     @Test
196     public void testSetOutcome() {
197         // success case
198         when(rawResponse.getStatus()).thenReturn(200);
199         assertSame(outcome, oper.setOutcome(outcome, PolicyResult.SUCCESS, rawResponse, response));
200
201         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
202         assertEquals("200 " + ControlLoopOperation.SUCCESS_MSG, outcome.getMessage());
203         assertSame(response, outcome.getResponse());
204
205         // failure case
206         when(rawResponse.getStatus()).thenReturn(500);
207         assertSame(outcome, oper.setOutcome(outcome, PolicyResult.FAILURE, rawResponse, response));
208
209         assertEquals(PolicyResult.FAILURE, outcome.getResult());
210         assertEquals("500 " + ControlLoopOperation.FAILED_MSG, outcome.getMessage());
211         assertSame(response, outcome.getResponse());
212     }
213
214     @Test
215     public void testPrepareSoModelInfo() throws CoderException {
216         verifyMissingModelInfo(target::getModelCustomizationId, target::setModelCustomizationId);
217         verifyMissingModelInfo(target::getModelInvariantId, target::setModelInvariantId);
218         verifyMissingModelInfo(target::getModelName, target::setModelName);
219         verifyMissingModelInfo(target::getModelVersion, target::setModelVersion);
220         verifyMissingModelInfo(target::getModelVersionId, target::setModelVersionId);
221
222         // valid data
223         SoModelInfo info = oper.prepareSoModelInfo();
224         verifyRequest("model.json", info);
225
226         // try with null target
227         params = params.toBuilder().target(null).build();
228         assertThatIllegalArgumentException().isThrownBy(() -> new SoOperation(params, config, PROP_NAMES) {})
229                         .withMessageContaining("missing Target");
230     }
231
232     private void verifyMissingModelInfo(Supplier<String> getter, Consumer<String> setter) {
233         String original = getter.get();
234
235         setter.accept(null);
236         assertThatIllegalArgumentException().isThrownBy(() -> oper.prepareSoModelInfo())
237                         .withMessage("missing VF Module model");
238
239         setter.accept(original);
240     }
241
242     @Test
243     public void testConstructRequestInfo() throws CoderException {
244         SoRequestInfo info = oper.constructRequestInfo();
245         verifyRequest("reqinfo.json", info);
246     }
247
248     @Test
249     public void testBuildRequestParameters() throws CoderException {
250         // valid data
251         verifyRequest("reqparams.json", oper.buildRequestParameters().get());
252
253         // invalid json
254         params.getPayload().put(SoOperation.REQ_PARAM_NM, "{invalid json");
255         assertThatIllegalArgumentException().isThrownBy(() -> oper.buildRequestParameters())
256                         .withMessage("invalid payload value: " + SoOperation.REQ_PARAM_NM);
257
258         // missing data
259         params.getPayload().remove(SoOperation.REQ_PARAM_NM);
260         assertTrue(oper.buildRequestParameters().isEmpty());
261
262         // null payload
263         params = params.toBuilder().payload(null).build();
264         oper = new SoOperation(params, config, PROP_NAMES) {};
265         assertTrue(oper.buildRequestParameters().isEmpty());
266     }
267
268     @Test
269     public void testBuildConfigurationParameters() {
270         // valid data
271         assertEquals(List.of(Collections.emptyMap()), oper.buildConfigurationParameters().get());
272
273         // invalid json
274         params.getPayload().put(SoOperation.CONFIG_PARAM_NM, "{invalid json");
275         assertThatIllegalArgumentException().isThrownBy(() -> oper.buildConfigurationParameters())
276                         .withMessage("invalid payload value: " + SoOperation.CONFIG_PARAM_NM);
277
278         // missing data
279         params.getPayload().remove(SoOperation.CONFIG_PARAM_NM);
280         assertTrue(oper.buildConfigurationParameters().isEmpty());
281
282         // null payload
283         params = params.toBuilder().payload(null).build();
284         oper = new SoOperation(params, config, PROP_NAMES) {};
285         assertTrue(oper.buildConfigurationParameters().isEmpty());
286     }
287
288     @Test
289     public void testGetVnfItem() {
290         // missing data
291         AaiCqResponse cq = mock(AaiCqResponse.class);
292         assertThatIllegalArgumentException().isThrownBy(() -> oper.getVnfItem(cq, oper.prepareSoModelInfo()))
293                         .withMessage("missing generic VNF");
294
295         // valid data
296         GenericVnf vnf = new GenericVnf();
297         when(cq.getGenericVnfByVfModuleModelInvariantId(MODEL_INVAR_ID)).thenReturn(vnf);
298         assertSame(vnf, oper.getVnfItem(cq, oper.prepareSoModelInfo()));
299     }
300
301     @Test
302     public void testGetServiceInstance() {
303         // missing data
304         AaiCqResponse cq = mock(AaiCqResponse.class);
305         assertThatIllegalArgumentException().isThrownBy(() -> oper.getServiceInstance(cq))
306                         .withMessage("missing VNF Service Item");
307
308         // valid data
309         ServiceInstance instance = new ServiceInstance();
310         when(cq.getServiceInstance()).thenReturn(instance);
311         assertSame(instance, oper.getServiceInstance(cq));
312     }
313
314     @Test
315     public void testGetDefaultTenant() {
316         // missing data
317         AaiCqResponse cq = mock(AaiCqResponse.class);
318         assertThatIllegalArgumentException().isThrownBy(() -> oper.getDefaultTenant(cq))
319                         .withMessage("missing Tenant Item");
320
321         // valid data
322         Tenant tenant = new Tenant();
323         when(cq.getDefaultTenant()).thenReturn(tenant);
324         assertSame(tenant, oper.getDefaultTenant(cq));
325     }
326
327     @Test
328     public void testGetDefaultCloudRegion() {
329         // missing data
330         AaiCqResponse cq = mock(AaiCqResponse.class);
331         assertThatIllegalArgumentException().isThrownBy(() -> oper.getDefaultCloudRegion(cq))
332                         .withMessage("missing Cloud Region");
333
334         // valid data
335         CloudRegion region = new CloudRegion();
336         when(cq.getDefaultCloudRegion()).thenReturn(region);
337         assertSame(region, oper.getDefaultCloudRegion(cq));
338     }
339
340     @Test
341     public void testGetCoder() throws CoderException {
342         Coder opcoder = oper.getCoder();
343
344         // ensure we can decode an SO timestamp
345         String json = "{'request':{'finishTime':'Fri, 15 May 2020 12:14:21 GMT'}}";
346         SoResponse resp = opcoder.decode(json.replace('\'', '"'), SoResponse.class);
347
348         LocalDateTime tfinish = resp.getRequest().getFinishTime();
349         assertNotNull(tfinish);
350         assertEquals(2020, tfinish.getYear());
351         assertEquals(Month.MAY, tfinish.getMonth());
352     }
353 }