Improve testing stability
[sdc.git] / catalog-be / src / test / java / org / openecomp / sdc / be / components / distribution / engine / EnvironmentsEngineTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019 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.openecomp.sdc.be.components.distribution.engine;
22
23 import fj.data.Either;
24 import mockit.Deencapsulation;
25 import org.apache.http.HttpStatus;
26 import org.junit.Before;
27 import org.junit.Test;
28 import org.mockito.InjectMocks;
29 import org.mockito.Mock;
30 import org.mockito.Mockito;
31 import org.mockito.MockitoAnnotations;
32 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
33 import org.openecomp.sdc.be.config.Configuration;
34 import org.openecomp.sdc.be.config.ConfigurationManager;
35 import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
36 import org.openecomp.sdc.be.config.DmaapConsumerConfiguration;
37 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
38 import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao;
39 import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum;
40 import org.openecomp.sdc.be.info.OperationalEnvInfo;
41 import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
42 import org.openecomp.sdc.common.datastructure.Wrapper;
43 import org.openecomp.sdc.common.http.client.api.HttpResponse;
44
45 import java.io.IOException;
46 import java.util.ArrayList;
47 import java.util.Arrays;
48 import java.util.Collections;
49 import java.util.HashSet;
50 import java.util.List;
51 import java.util.Map;
52 import org.openecomp.sdc.common.impl.ExternalConfiguration;
53 import org.openecomp.sdc.common.impl.FSConfigurationSource;
54 import com.att.nsa.apiClient.credentials.ApiCredential;
55 import static org.assertj.core.api.Assertions.assertThat;
56 import static org.assertj.core.api.Assertions.assertThatThrownBy;
57 import static org.junit.Assert.assertEquals;
58 import static org.junit.Assert.assertTrue;
59 import static org.mockito.Mockito.any;
60 import static org.mockito.Mockito.when;
61
62 public class EnvironmentsEngineTest {
63
64     @InjectMocks
65     private EnvironmentsEngine envEngine;
66     @Mock
67     private OperationalEnvironmentDao operationalEnvironmentDao;
68     @Mock
69     private ConfigurationManager configurationManager;
70     @Mock
71     private DistributionEngineConfiguration distributionEngineConfiguration;
72     @Mock
73     private AaiRequestHandler aaiRequestHandler;
74     @Mock 
75     private CambriaHandler cambriaHandler;
76
77     @Before
78     public void preStart() {
79         MockitoAnnotations.openMocks(this);
80         new ConfigurationManager(new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"));
81     }
82
83     @Test
84     public void testInit() {
85         envEngine.setConfigurationManager(configurationManager);
86         Configuration config = Mockito.mock(Configuration.class);
87         DmaapConsumerConfiguration dmaapConf = Mockito.mock(DmaapConsumerConfiguration.class);
88         List<OperationalEnvironmentEntry> entryList = Arrays.asList(createOpEnvEntry("Env1"), createOpEnvEntry("Env2"));
89         Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> successEither = Either.left(entryList);
90         when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED)).thenReturn(successEither);
91         when(configurationManager.getDistributionEngineConfiguration()).thenReturn(distributionEngineConfiguration);
92         when(distributionEngineConfiguration.getEnvironments()).thenReturn(Collections.singletonList("Env Loaded From Configuration"));
93         when(distributionEngineConfiguration.getUebPublicKey()).thenReturn("Dummy Public Key");
94         when(distributionEngineConfiguration.getUebSecretKey()).thenReturn("Dummy Private Key");
95         when(distributionEngineConfiguration.getUebServers()).thenReturn(
96                 Arrays.asList("uebsb91kcdc.it.com:3904", "uebsb92kcdc.it.com:3904", "uebsb91kcdc.it.com:3904"));
97         when(configurationManager.getConfiguration()).thenReturn(config);
98         when(config.getDmaapConsumerConfiguration()).thenReturn(dmaapConf);
99         when(dmaapConf.isActive()).thenReturn(false);
100         ApiCredential apiCredential = new ApiCredential("apiKey", "apiSecret");
101         when(cambriaHandler.createUebKeys(any())).thenReturn(Either.left(apiCredential));
102         envEngine.init();
103         
104         Map<String, OperationalEnvironmentEntry> mapEnvs = envEngine.getEnvironments();
105         assertEquals("unexpected size of map",3, mapEnvs.size());
106     }
107
108
109     @Test
110     public void testGetFullOperationalEnvByIdSuccess() {
111         String json = getFullOperationalEnvJson();
112
113         HttpResponse restResponse = new HttpResponse(json, HttpStatus.SC_OK, "Successfully completed");
114         when(aaiRequestHandler.getOperationalEnvById(Mockito.anyString())).thenReturn(restResponse);
115
116         Either<OperationalEnvInfo, Integer> response = envEngine.getOperationalEnvById("DummyId");
117         assertTrue("The operational environment request ran as not expected", response.isLeft());
118
119         OperationalEnvInfo operationalEnvInfo = response.left().value();
120
121         assertEquals("The operational environment json is not as expected", operationalEnvInfo.toString(), json);
122     }
123
124     @Test
125     public void testGetPartialOperationalEnvByIdSuccess() {
126         String json = getPartialOperationalEnvJson();
127
128         HttpResponse<String> restResponse = new HttpResponse<String>(json, HttpStatus.SC_OK, "Successfully completed");
129         when(aaiRequestHandler.getOperationalEnvById(Mockito.anyString())).thenReturn(restResponse);
130
131         Either<OperationalEnvInfo, Integer> response = envEngine.getOperationalEnvById("DummyId");
132         assertTrue("The operational environment request ran as not expected", response.isLeft());
133
134         OperationalEnvInfo operationalEnvInfo = response.left().value();
135
136         assertEquals("The operational environment json is not as expected", operationalEnvInfo.toString(), json);
137     }
138
139
140     @Test
141     public void testGetOperationalEnvByIdFailedByJsonConvert() {
142         String jsonCorrupted = getCorruptedOperationalEnvJson();
143
144         HttpResponse<String> restResponse = new HttpResponse<String>(jsonCorrupted, HttpStatus.SC_OK, "Successfully Completed");
145         when(aaiRequestHandler.getOperationalEnvById(Mockito.anyString())).thenReturn(restResponse);
146
147         Either<OperationalEnvInfo, Integer> response = envEngine.getOperationalEnvById("DummyId");
148         assertTrue("The operational environment request ran as not expected", response.isRight());
149         assertEquals("The operational environment request status code is not as expected", (Integer)HttpStatus.SC_INTERNAL_SERVER_ERROR, response.right().value());
150     }
151
152     @Test
153     public void testGetOperationalEnvByIdFailed404() {
154         String json = getFullOperationalEnvJson();
155         HttpResponse<String> restResponse = new HttpResponse<String>(json, HttpStatus.SC_NOT_FOUND, "Not Found");
156         when(aaiRequestHandler.getOperationalEnvById(Mockito.anyString())).thenReturn(restResponse);
157
158         Either<OperationalEnvInfo, Integer> response = envEngine.getOperationalEnvById("DummyId");
159         assertTrue("The operational environment request ran as not expected", response.isRight());
160         assertEquals("The operational environment request status code is not as expected", (Integer)HttpStatus.SC_NOT_FOUND, response.right().value());
161     }
162
163
164     @Test(expected = IOException.class)
165     public void testCorruptedOperationalEnvJson() throws IOException {
166         String jsonCorrupted = getCorruptedOperationalEnvJson();
167         OperationalEnvInfo.createFromJson(jsonCorrupted);
168     }
169
170     @Test
171     public void getEnvironmentById() {
172         OperationalEnvironmentEntry oe = new OperationalEnvironmentEntry();
173         oe.setEnvironmentId("mock");
174         envEngine.addToMap(oe);
175         assertTrue(envEngine.isInMap("mock"));
176         assertTrue(envEngine.isInMap(oe));
177         OperationalEnvironmentEntry returnedOe = envEngine.getEnvironmentById("mock");
178         assertTrue(oe == returnedOe);
179     }
180
181     @Test
182     public void getEnvironmentByDmaapUebAddressNoProperEnvironment() {
183         OperationalEnvironmentEntry opEnvEntry = createOpEnvEntry("1");
184         opEnvEntry.setDmaapUebAddress(new HashSet<>());
185         envEngine.addToMap(opEnvEntry);
186         assertThatThrownBy(() -> {
187             envEngine.getEnvironmentByDmaapUebAddress(Arrays.asList("11", "22"));})
188                 .isInstanceOf(ComponentException.class);
189     }
190
191     @Test
192     public void getEnvironmentByDmaapUebAddressListWithEmptyList() {
193         OperationalEnvironmentEntry opEnvEntry = createOpEnvEntry("1");
194         opEnvEntry.setDmaapUebAddress(new HashSet<>(Arrays.asList("11","22")));
195         OperationalEnvironmentEntry opEnvEntry2 = createOpEnvEntry("2");
196         opEnvEntry2.setDmaapUebAddress(new HashSet<>(Arrays.asList("33","44","55")));
197         envEngine.addToMap(opEnvEntry);
198         envEngine.addToMap(opEnvEntry2);
199         assertThatThrownBy(() -> {
200             envEngine.getEnvironmentByDmaapUebAddress(new ArrayList<>());})
201                 .isInstanceOf(ComponentException.class);
202     }
203
204     @Test
205     public void getEnvironmentByDmaapUebAddressList() {
206         OperationalEnvironmentEntry opEnvEntry = createOpEnvEntry("1");
207         opEnvEntry.setDmaapUebAddress(new HashSet<>(Arrays.asList("11","22")));
208         OperationalEnvironmentEntry opEnvEntry2 = createOpEnvEntry("2");
209         opEnvEntry2.setDmaapUebAddress(new HashSet<>(Arrays.asList("33","44","55")));
210         envEngine.addToMap(opEnvEntry);
211         envEngine.addToMap(opEnvEntry2);
212         assertThat(envEngine.getEnvironmentByDmaapUebAddress(Arrays.asList("77","22"))
213                 .getEnvironmentId()).isEqualTo("1");
214
215         assertThat(envEngine.getEnvironmentByDmaapUebAddress(Arrays.asList("77","55"))
216                 .getEnvironmentId()).isEqualTo("2");
217
218         assertThat(envEngine.getEnvironmentByDmaapUebAddress(Arrays.asList("11","44"))
219                 .getEnvironmentId()).isEqualTo("1");
220     }
221
222
223
224
225     private String getCorruptedOperationalEnvJson() {
226         return "{\"OPERATIONAL-environment-name\":\"Op Env Name\","
227                 + "\"OPERATIONAL-environment-type\":\"VNF\","
228                 + "\"OPERATIONAL-environment-status\":\"Activate\","
229                 + "\"tenant-context\":\"Test\"}";
230     }
231
232     private String getPartialOperationalEnvJson() {
233         return "{" +
234                 "\"operational-environment-id\":\"UUID of Operational Environment\"," +
235                 "\"operational-environment-name\":\"Op Env Name\"," +
236                 "\"operational-environment-type\":\"VNF\"," +
237                 "\"operational-environment-status\":\"Activate\"," +
238                 "\"tenant-context\":\"Test\"," +
239                 "\"workload-context\":\"VNF_Development\"," +
240                 "\"resource-version\":\"1505228226913\"," +
241                 "\"relationship-list\":{" +
242                 "\"relationship\":[]" +
243                 "}" +
244                 "}";
245     }
246
247     private String getFullOperationalEnvJson() {
248         return  "{" +
249                 "\"operational-environment-id\":\"OEid1\"," +
250                 "\"operational-environment-name\":\"OEname1\"," +
251                 "\"operational-environment-type\":\"OEtype1\"," +
252                 "\"operational-environment-status\":\"OEstatus1\"," +
253                 "\"tenant-context\":\"OEtenantcontext1\"," +
254                 "\"workload-context\":\"OEworkloadcontext1\"," +
255                 "\"resource-version\":\"1511363173278\"," +
256                 "\"relationship-list\":{" +
257                 "\"relationship\":[" +
258                 "{" +
259                 "\"related-to\":\"operational-environment\"," +
260                 "\"relationship-label\":\"managedBy\"," +
261                 "\"related-link\":\"/aai/v12/cloud-infrastructure/operational-environments/operational-environment/OEid3\"," +
262                 "\"relationship-data\":[" +
263                 "{" +
264                 "\"relationship-key\":\"operational-environment.operational-environment-id\"," +
265                 "\"relationship-value\":\"OEid3\"" +
266                 "}" +
267                 "]," +
268                 "\"related-to-property\":[" +
269                 "{" +
270                 "\"property-key\":\"operational-environment.operational-environment-name\"," +
271                 "\"property-value\":\"OEname3\"" +
272                 "}]}]}}";
273     }
274
275     private OperationalEnvironmentEntry createOpEnvEntry(String name) {
276         OperationalEnvironmentEntry entry = new OperationalEnvironmentEntry();
277         entry.setEnvironmentId(name);
278         return entry;
279     }
280
281     public void testHandleMessageLogic() throws Exception {
282         String notification = "";
283         boolean result;
284
285         // default test
286         result = envEngine.handleMessageLogic(notification);
287     }
288
289     @Test
290     public void testValidateNotification() throws Exception {
291         Wrapper<Boolean> errorWrapper = new Wrapper<>();
292         errorWrapper.setInnerElement(true);
293         IDmaapNotificationData notificationData = Mockito.mock(IDmaapNotificationData.class);
294         IDmaapAuditNotificationData auditNotificationData = Mockito.mock(IDmaapAuditNotificationData.class);
295
296         // default test
297         Deencapsulation.invoke(envEngine, "validateNotification", errorWrapper, notificationData,
298                 auditNotificationData);
299     }
300
301     @Test
302     public void testSaveEntryWithFailedStatus() throws Exception {
303         Wrapper<Boolean> errorWrapper = new Wrapper<>();
304         OperationalEnvironmentEntry opEnvEntry = new OperationalEnvironmentEntry();
305
306         // default test
307         Deencapsulation.invoke(envEngine, "saveEntryWithFailedStatus", errorWrapper, opEnvEntry);
308     }
309
310     @Test
311     public void testRetrieveUebAddressesFromAftDme() throws Exception {
312         Wrapper<Boolean> errorWrapper = new Wrapper<>();
313         OperationalEnvironmentEntry opEnvEntry = new OperationalEnvironmentEntry();
314
315         // default test
316         Deencapsulation.invoke(envEngine, "retrieveUebAddressesFromAftDme", errorWrapper, opEnvEntry);
317     }
318
319     @Test
320     public void testRetrieveOpEnvInfoFromAAI() throws Exception {
321         Wrapper<Boolean> errorWrapper = new Wrapper<>();
322         OperationalEnvironmentEntry opEnvEntry = new OperationalEnvironmentEntry();
323         opEnvEntry.setEnvironmentId("mock");
324         Mockito.when(aaiRequestHandler.getOperationalEnvById(Mockito.nullable(String.class))).thenReturn(new HttpResponse<String>("{}", 200));
325         // default test
326         Deencapsulation.invoke(envEngine, "retrieveOpEnvInfoFromAAI", new Wrapper<>(), opEnvEntry);
327     }
328
329     @Test
330     public void testRetrieveOpEnvInfoFromAAIError() throws Exception {
331         Wrapper<Boolean> errorWrapper = new Wrapper<>();
332         OperationalEnvironmentEntry opEnvEntry = new OperationalEnvironmentEntry();
333         opEnvEntry.setEnvironmentId("mock");
334         Mockito.when(aaiRequestHandler.getOperationalEnvById(Mockito.nullable(String.class))).thenReturn(new HttpResponse<String>("{}", 500));
335         // default test
336         Deencapsulation.invoke(envEngine, "retrieveOpEnvInfoFromAAI", new Wrapper<>(), opEnvEntry);
337     }
338
339     @Test
340     public void testSaveEntryWithInProgressStatus() throws Exception {
341         Wrapper<Boolean> errorWrapper = new Wrapper<>();
342         Wrapper<OperationalEnvironmentEntry> opEnvEntryWrapper = new Wrapper<>();
343         IDmaapNotificationData notificationData = Mockito.mock(IDmaapNotificationData.class);
344
345         Deencapsulation.invoke(envEngine, "saveEntryWithInProgressStatus", errorWrapper, opEnvEntryWrapper,
346                 notificationData);
347     }
348
349     @Test
350     public void testValidateStateGeneralError() throws Exception {
351         Wrapper<Boolean> errorWrapper = null;
352         IDmaapNotificationData notificationData = Mockito.mock(IDmaapNotificationData.class);
353
354         Mockito.when(operationalEnvironmentDao.get(Mockito.nullable(String.class)))
355                 .thenReturn(Either.right(CassandraOperationStatus.GENERAL_ERROR));
356
357         Deencapsulation.invoke(envEngine, "validateState", new Wrapper<>(), notificationData);
358     }
359
360     @Test
361     public void testValidateState() throws Exception {
362         Wrapper<Boolean> errorWrapper = null;
363         IDmaapNotificationData notificationData = Mockito.mock(IDmaapNotificationData.class);
364
365         OperationalEnvironmentEntry a = new OperationalEnvironmentEntry();
366         a.setStatus(EnvironmentStatusEnum.IN_PROGRESS.getName());
367         Mockito.when(operationalEnvironmentDao.get(Mockito.nullable(String.class))).thenReturn(Either.left(a));
368
369         Deencapsulation.invoke(envEngine, "validateState", new Wrapper<>(), notificationData);
370     }
371
372     @Test
373     public void testValidateActionType() throws Exception {
374         Wrapper<Boolean> errorWrapper = new Wrapper<>();
375         IDmaapNotificationData notificationData = Mockito.mock(IDmaapNotificationData.class);
376         Mockito.when(notificationData.getAction()).thenReturn(IDmaapNotificationData.DmaapActionEnum.DELETE);
377
378         Deencapsulation.invoke(envEngine, "validateActionType", errorWrapper, notificationData);
379     }
380
381     @Test
382     public void testValidateActionType2() throws Exception {
383         Wrapper<Boolean> errorWrapper = new Wrapper<>();
384         IDmaapNotificationData notificationData = Mockito.mock(IDmaapNotificationData.class);
385         Mockito.when(notificationData.getAction()).thenReturn(IDmaapNotificationData.DmaapActionEnum.CREATE);
386
387         Deencapsulation.invoke(envEngine, "validateActionType", errorWrapper, notificationData);
388     }
389
390     @Test
391     public void testValidateEnvironmentType() throws Exception {
392         Wrapper<Boolean> errorWrapper = new Wrapper<>();
393         IDmaapNotificationData notificationData = Mockito.mock(IDmaapNotificationData.class);
394         IDmaapAuditNotificationData auditNotificationData = Mockito.mock(IDmaapAuditNotificationData.class);
395         Mockito.when(auditNotificationData.getOperationalEnvironmentName()).thenReturn("mock");
396         Mockito.when(notificationData.getOperationalEnvironmentType()).thenReturn(IDmaapNotificationData.OperationaEnvironmentTypeEnum.ECOMP);
397
398         // default test
399         Deencapsulation.invoke(envEngine, "validateEnvironmentType", errorWrapper, notificationData,
400                 auditNotificationData);
401     }
402
403     @Test
404     public void testMap2OpEnvKey() throws Exception {
405         OperationalEnvironmentEntry entry = new OperationalEnvironmentEntry();
406         String result;
407
408         // default test
409         result = Deencapsulation.invoke(envEngine, "map2OpEnvKey", entry);
410     }
411 }