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