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