Change payload to Map<String,Object> so it's more versatile
[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         // put the count in the context so that it will skip the custom query
87         params.getContext().setProperty(SoConstants.CONTEXT_KEY_VF_COUNT, 20);
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         params.getContext().setProperty(SoConstants.CONTEXT_KEY_VF_COUNT, 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         params.getContext().setProperty(SoConstants.CONTEXT_KEY_VF_COUNT, 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(500, TimeUnit.SECONDS);
168         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
169
170         Integer newCount = (Integer) params.getContext().getProperty(SoConstants.CONTEXT_KEY_VF_COUNT);
171         assertEquals(origCount + 1, newCount.intValue());
172     }
173
174     /**
175      * Tests startOperationAsync() when "get" operations are required.
176      */
177     @Test
178     public void testStartOperationAsyncWithGets() throws Exception {
179         when(rawResponse.getStatus()).thenReturn(500, 500, 500, 500, 200, 200);
180
181         when(client.post(any(), any(), any(), any())).thenAnswer(provideResponse(rawResponse));
182         when(client.get(any(), any(), any())).thenAnswer(provideResponse(rawResponse));
183
184         // use a real executor
185         params = params.toBuilder().executor(ForkJoinPool.commonPool()).build();
186
187         oper = new VfModuleCreate(params, config) {
188             @Override
189             public long getWaitMsGet() {
190                 return 1;
191             }
192         };
193
194         CompletableFuture<OperationOutcome> future2 = oper.start();
195
196         outcome = future2.get(500, TimeUnit.SECONDS);
197         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
198     }
199
200     @Test
201     public void testMakeRequest() throws CoderException {
202         Pair<String, SoRequest> pair = oper.makeRequest();
203
204         // @formatter:off
205         assertEquals(
206             "/serviceInstantiation/v7/serviceInstances/my-service-instance-id/vnfs/my-vnf-id/vfModules/scaleOut",
207             pair.getLeft());
208         // @formatter:on
209
210         verifyRequest("vfModuleCreate.json", pair.getRight());
211     }
212
213
214     @Override
215     protected void makeContext() {
216         super.makeContext();
217
218         AaiCqResponse cq = mock(AaiCqResponse.class);
219
220         GenericVnf vnf = new GenericVnf();
221         when(cq.getGenericVnfByVfModuleModelInvariantId(MODEL_INVAR_ID)).thenReturn(vnf);
222         vnf.setVnfId(VNF_ID);
223
224         ServiceInstance instance = new ServiceInstance();
225         when(cq.getServiceInstance()).thenReturn(instance);
226         instance.setServiceInstanceId(SVC_INSTANCE_ID);
227
228         when(cq.getDefaultTenant()).thenReturn(new Tenant());
229         when(cq.getDefaultCloudRegion()).thenReturn(new CloudRegion());
230
231         ModelVer modelVers = new ModelVer();
232         when(cq.getModelVerByVersionId(any())).thenReturn(modelVers);
233         modelVers.setModelName(MODEL_NAME2);
234         modelVers.setModelVersion(MODEL_VERS2);
235
236         params.getContext().setProperty(AaiCqResponse.CONTEXT_KEY, cq);
237     }
238 }