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