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