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