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