Add Modify NSSI operation in SO actor
[policy/models.git] / models-interactions / model-actors / actor.so / src / test / java / org / onap / policy / controlloop / actor / so / VfModuleCreateTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2020 Wipro Limited.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.controlloop.actor.so;
23
24 import static org.assertj.core.api.Assertions.assertThat;
25 import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertFalse;
28 import static org.junit.Assert.assertNotNull;
29 import static org.junit.Assert.assertNull;
30 import static org.junit.Assert.assertTrue;
31 import static org.mockito.ArgumentMatchers.any;
32 import static org.mockito.Mockito.mock;
33 import static org.mockito.Mockito.verify;
34 import static org.mockito.Mockito.when;
35
36 import java.util.List;
37 import java.util.Map;
38 import java.util.concurrent.CompletableFuture;
39 import java.util.concurrent.ForkJoinPool;
40 import java.util.concurrent.TimeUnit;
41 import java.util.concurrent.atomic.AtomicBoolean;
42 import org.apache.commons.lang3.tuple.Pair;
43 import org.junit.AfterClass;
44 import org.junit.Before;
45 import org.junit.BeforeClass;
46 import org.junit.Test;
47 import org.mockito.ArgumentCaptor;
48 import org.onap.aai.domain.yang.CloudRegion;
49 import org.onap.aai.domain.yang.GenericVnf;
50 import org.onap.aai.domain.yang.ModelVer;
51 import org.onap.aai.domain.yang.ServiceInstance;
52 import org.onap.aai.domain.yang.Tenant;
53 import org.onap.policy.aai.AaiCqResponse;
54 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
55 import org.onap.policy.common.utils.coder.CoderException;
56 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
57 import org.onap.policy.controlloop.actorserviceprovider.OperationProperties;
58 import org.onap.policy.controlloop.actorserviceprovider.OperationResult;
59 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
60 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpPollingConfig;
61 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpPollingParams;
62 import org.onap.policy.so.SoRequest;
63 import org.onap.policy.so.SoResponse;
64
65 public class VfModuleCreateTest extends BasicSoOperation {
66
67
68     private static final String MODEL_NAME2 = "my-model-name-B";
69     private static final String MODEL_VERS2 = "my-model-version-B";
70     private static final String SVC_INSTANCE_ID = "my-service-instance-id";
71     private static final String VNF_ID = "my-vnf-id";
72
73     private VfModuleCreate oper;
74
75     public VfModuleCreateTest() {
76         super(DEFAULT_ACTOR, VfModuleCreate.NAME);
77     }
78
79     @BeforeClass
80     public static void setUpBeforeClass() throws Exception {
81         initBeforeClass();
82     }
83
84     @AfterClass
85     public static void tearDownAfterClass() {
86         destroyAfterClass();
87     }
88
89     @Override
90     @Before
91     public void setUp() throws Exception {
92         super.setUp();
93         oper = new VfModuleCreate(params, config);
94     }
95
96     /**
97      * Tests "success" case with simulator.
98      */
99     @Test
100     public void testSuccess() throws Exception {
101         HttpPollingParams opParams = HttpPollingParams.builder().clientName(MY_CLIENT)
102                         .path("serviceInstantiation/v7/serviceInstances").pollPath("orchestrationRequests/v5/")
103                         .maxPolls(2).build();
104         config = new HttpPollingConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory());
105
106         params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor).build();
107
108         oper = new VfModuleCreate(params, config);
109
110         outcome = oper.start().get();
111         assertEquals(OperationResult.SUCCESS, outcome.getResult());
112         assertTrue(outcome.getResponse() instanceof SoResponse);
113     }
114
115     /**
116      * Tests "success" case with simulator, using properties instead of custom query data.
117      */
118     @Test
119     public void testSuccessViaProperties() throws Exception {
120         HttpPollingParams opParams = HttpPollingParams.builder().clientName(MY_CLIENT)
121                         .path("serviceInstantiation/v7/serviceInstances").pollPath("orchestrationRequests/v5/")
122                         .maxPolls(2).build();
123         config = new HttpPollingConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory());
124
125         params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor).preprocessed(true).build();
126         params.getContext().removeProperty(AaiCqResponse.CONTEXT_KEY);
127
128         oper = new VfModuleCreate(params, config);
129
130         // set the properties
131         ServiceInstance instance = new ServiceInstance();
132         instance.setServiceInstanceId(SVC_INSTANCE_ID);
133         oper.setProperty(OperationProperties.AAI_SERVICE, instance);
134
135         ModelVer modelVers = new ModelVer();
136         modelVers.setModelName(MODEL_NAME2);
137         modelVers.setModelVersion(MODEL_VERS2);
138
139         oper.setProperty(OperationProperties.AAI_SERVICE_MODEL, modelVers);
140         oper.setProperty(OperationProperties.AAI_VNF_MODEL, modelVers);
141
142         GenericVnf vnf = new GenericVnf();
143         vnf.setVnfId(VNF_ID);
144         oper.setProperty(OperationProperties.AAI_VNF, vnf);
145
146         oper.setProperty(OperationProperties.AAI_DEFAULT_CLOUD_REGION, new CloudRegion());
147         oper.setProperty(OperationProperties.AAI_DEFAULT_TENANT, new Tenant());
148
149         oper.setProperty(OperationProperties.DATA_VF_COUNT, VF_COUNT);
150
151         // run the operation
152         outcome = oper.start().get();
153         assertEquals(OperationResult.SUCCESS, outcome.getResult());
154         assertTrue(outcome.getResponse() instanceof SoResponse);
155
156         int count = oper.getProperty(OperationProperties.DATA_VF_COUNT);
157         assertEquals(VF_COUNT + 1, count);
158     }
159
160     @Test
161     public void testConstructor() {
162         assertEquals(DEFAULT_ACTOR, oper.getActorName());
163         assertEquals(VfModuleCreate.NAME, oper.getName());
164         assertTrue(oper.isUsePolling());
165
166         // verify that target validation is done
167         params = params.toBuilder().targetType(null).build();
168         assertThatIllegalArgumentException().isThrownBy(() -> new VfModuleCreate(params, config))
169                         .withMessageContaining("Target information");
170     }
171
172     @Test
173     public void testGetPropertyNames() {
174         // @formatter:off
175         assertThat(oper.getPropertyNames()).isEqualTo(
176                         List.of(
177                             OperationProperties.AAI_SERVICE,
178                             OperationProperties.AAI_SERVICE_MODEL,
179                             OperationProperties.AAI_VNF,
180                             OperationProperties.AAI_VNF_MODEL,
181                             OperationProperties.AAI_DEFAULT_CLOUD_REGION,
182                             OperationProperties.AAI_DEFAULT_TENANT,
183                             OperationProperties.DATA_VF_COUNT));
184         // @formatter:on
185     }
186
187     @Test
188     public void testStartPreprocessorAsync() throws Exception {
189         // insert CQ data so it's there for the check
190         context.setProperty(AaiCqResponse.CONTEXT_KEY, makeCqResponse());
191
192         AtomicBoolean guardStarted = new AtomicBoolean();
193
194         oper = new VfModuleCreate(params, config) {
195             @Override
196             protected CompletableFuture<OperationOutcome> startGuardAsync() {
197                 guardStarted.set(true);
198                 return super.startGuardAsync();
199             }
200         };
201
202         CompletableFuture<OperationOutcome> future3 = oper.startPreprocessorAsync();
203         assertNotNull(future3);
204         assertTrue(guardStarted.get());
205     }
206
207     /**
208      * Tests startPreprocessorAsync(), when preprocessing is disabled.
209      */
210     @Test
211     public void testStartPreprocessorAsyncDisabled() {
212         params = params.toBuilder().preprocessed(true).build();
213         assertNull(new VfModuleCreate(params, config).startPreprocessorAsync());
214     }
215
216     @Test
217     public void testStartGuardAsync() throws Exception {
218         // remove CQ data so it's forced to query
219         context.removeProperty(AaiCqResponse.CONTEXT_KEY);
220
221         CompletableFuture<OperationOutcome> future2 = oper.startPreprocessorAsync();
222         assertTrue(executor.runAll(100));
223         assertFalse(future2.isDone());
224
225         provideCqResponse(makeCqResponse());
226         assertTrue(executor.runAll(100));
227         assertTrue(future2.isDone());
228         assertEquals(OperationResult.SUCCESS, future2.get().getResult());
229     }
230
231     @Test
232     public void testMakeGuardPayload() {
233         final int origCount = 30;
234         oper.setVfCount(origCount);
235
236         CompletableFuture<OperationOutcome> future2 = oper.startPreprocessorAsync();
237         assertTrue(executor.runAll(100));
238         assertTrue(future2.isDone());
239
240         // get the payload from the request
241         ArgumentCaptor<ControlLoopOperationParams> captor = ArgumentCaptor.forClass(ControlLoopOperationParams.class);
242         verify(guardOperator).buildOperation(captor.capture());
243
244         Map<String, Object> payload = captor.getValue().getPayload();
245         assertNotNull(payload);
246
247         Integer newCount = (Integer) payload.get(VfModuleCreate.PAYLOAD_KEY_VF_COUNT);
248         assertNotNull(newCount);
249         assertEquals(origCount + 1, newCount.intValue());
250     }
251
252     @Test
253     public void testStartOperationAsync_testSuccessfulCompletion() throws Exception {
254         final int origCount = 30;
255         oper.setVfCount(origCount);
256
257         when(client.post(any(), any(), any(), any())).thenAnswer(provideResponse(rawResponse));
258
259         // use a real executor
260         params = params.toBuilder().executor(ForkJoinPool.commonPool()).build();
261
262         oper = new VfModuleCreate(params, config) {
263             @Override
264             protected long getPollWaitMs() {
265                 return 1;
266             }
267         };
268
269         CompletableFuture<OperationOutcome> future2 = oper.start();
270
271         outcome = future2.get(5, TimeUnit.SECONDS);
272         assertEquals(OperationResult.SUCCESS, outcome.getResult());
273
274         SoResponse resp = outcome.getResponse();
275         assertNotNull(resp);
276         assertEquals(REQ_ID.toString(), resp.getRequestReferences().getRequestId());
277
278         assertEquals(origCount + 1, oper.getVfCount());
279     }
280
281     /**
282      * Tests startOperationAsync() when polling is required.
283      */
284     @Test
285     public void testStartOperationAsyncWithPolling() throws Exception {
286         when(rawResponse.getStatus()).thenReturn(500, 500, 500, 500, 200, 200);
287
288         when(client.post(any(), any(), any(), any())).thenAnswer(provideResponse(rawResponse));
289         when(client.get(any(), any(), any())).thenAnswer(provideResponse(rawResponse));
290
291         // use a real executor
292         params = params.toBuilder().executor(ForkJoinPool.commonPool()).build();
293
294         oper = new VfModuleCreate(params, config) {
295             @Override
296             public long getPollWaitMs() {
297                 return 1;
298             }
299         };
300
301         CompletableFuture<OperationOutcome> future2 = oper.start();
302
303         outcome = future2.get(5, TimeUnit.SECONDS);
304         assertEquals(OperationResult.SUCCESS, outcome.getResult());
305     }
306
307     @Test
308     public void testMakeRequest() throws CoderException {
309         Pair<String, SoRequest> pair = oper.makeRequest();
310
311         // @formatter:off
312         assertEquals(
313             "/my-service-instance-id/vnfs/my-vnf-id/vfModules/scaleOut",
314             pair.getLeft());
315         // @formatter:on
316
317         verifyRequest("vfModuleCreate.json", pair.getRight());
318     }
319
320
321     @Override
322     protected void makeContext() {
323         super.makeContext();
324
325         AaiCqResponse cq = mock(AaiCqResponse.class);
326
327         GenericVnf vnf = new GenericVnf();
328         when(cq.getGenericVnfByVfModuleModelInvariantId(MODEL_INVAR_ID)).thenReturn(vnf);
329         vnf.setVnfId(VNF_ID);
330
331         ServiceInstance instance = new ServiceInstance();
332         when(cq.getServiceInstance()).thenReturn(instance);
333         instance.setServiceInstanceId(SVC_INSTANCE_ID);
334
335         when(cq.getDefaultTenant()).thenReturn(new Tenant());
336         when(cq.getDefaultCloudRegion()).thenReturn(new CloudRegion());
337
338         ModelVer modelVers = new ModelVer();
339         when(cq.getModelVerByVersionId(any())).thenReturn(modelVers);
340         modelVers.setModelName(MODEL_NAME2);
341         modelVers.setModelVersion(MODEL_VERS2);
342
343         params.getContext().setProperty(AaiCqResponse.CONTEXT_KEY, cq);
344     }
345 }