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