Prepare for Junit5
[sdc.git] / catalog-be / src / test / java / org / openecomp / sdc / be / components / distribution / engine / StepsTenantIsolation.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 com.att.aft.dme2.api.DME2Exception;
24 import com.att.aft.dme2.iterator.DME2EndpointIterator;
25 import com.att.nsa.apiClient.credentials.ApiCredential;
26 import com.google.gson.Gson;
27 import com.google.gson.GsonBuilder;
28 import io.cucumber.java.Before;
29 import io.cucumber.java.en.Given;
30 import io.cucumber.java.en.Then;
31 import io.cucumber.java.en.When;
32 import fj.data.Either;
33 import org.apache.commons.lang.NotImplementedException;
34 import org.apache.commons.lang.math.NumberUtils;
35 import org.apache.http.HttpStatus;
36 import org.junit.Assert;
37 import org.mockito.InjectMocks;
38 import org.mockito.Mock;
39 import org.mockito.Mockito;
40 import org.mockito.MockitoAnnotations;
41 import org.mockito.Spy;
42 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
43 import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao;
44 import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum;
45 import org.openecomp.sdc.be.impl.ComponentsUtils;
46 import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
47 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
48 import org.openecomp.sdc.common.datastructure.Wrapper;
49 import org.openecomp.sdc.common.http.client.api.HttpResponse;
50
51 import static java.util.Objects.isNull;
52 import static org.apache.commons.lang3.StringUtils.isEmpty;
53 import static org.mockito.Mockito.doNothing;
54 import static org.mockito.Mockito.verify;
55 import static org.mockito.Mockito.when;
56
57 public class StepsTenantIsolation {
58
59     // Notification Fields
60     private String operationalEnvironmentId = "28122015552391";
61     private String operationalEnvironmentName = "Operational Environment Name";
62     private String operationalEnvironmentType;
63     private String tenantContext ;
64     private String workloadContext;
65     private String action;
66
67     @Mock
68     private DmaapConsumer dmaapConsumer;
69     @Mock
70     private OperationalEnvironmentDao operationalEnvironmentDao;
71     @Mock
72     private DME2EndpointIteratorCreator epIterCreator;
73     @Mock
74     private ComponentsUtils componentsUtils;
75     @Mock
76     private AaiRequestHandler aaiRequestHandler;
77     @Mock
78     private CambriaHandler cambriaHandler;
79     @InjectMocks
80     @Spy
81     private EnvironmentsEngine envEngine;
82
83     private boolean isSuccessful;
84     private boolean cassandraUp;
85
86     @Before
87     public void beforeScenario() {
88         MockitoAnnotations.initMocks(this);
89         when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED))
90                 .thenReturn(Either.right(CassandraOperationStatus.NOT_FOUND));
91         doNothing().when(envEngine).createUebTopicsForEnvironments();
92         envEngine.init();
93     }
94
95     // ############################# Given - Start #############################
96     @Given("^Dmaap consumer recieved notification with fields (.*)$")
97     public void dmaap_consumer_recieved_notification_with_fields(String notificationFields) throws Throwable {
98         Gson gson = new GsonBuilder().create();
99         IDmaapNotificationData notification = gson.fromJson(notificationFields, DmaapNotificationDataImpl.class);
100         if (!isNull(notification.getOperationalEnvironmentType())) {
101             this.operationalEnvironmentType = notification.getOperationalEnvironmentType().getEventTypenName();
102         }
103         if( !isEmpty(notification.getOperationalEnvironmentId()) ){
104             this.operationalEnvironmentId = notification.getOperationalEnvironmentId();
105         }
106         if( !isNull(notification.getAction()) ){
107             this.action = notification.getAction().getActionName();
108         }
109
110     }
111
112     @Given("^Cassandra service status is (.*)$")
113     public void cassandra_service_status_is(String status) throws Throwable {
114         switch (status) {
115         case "UP":
116             this.cassandraUp = true;
117             break;
118         case "DOWN":
119             when(operationalEnvironmentDao.get(operationalEnvironmentId))
120                     .thenReturn(Either.right(CassandraOperationStatus.GENERAL_ERROR));
121             when(operationalEnvironmentDao.save(Mockito.any(OperationalEnvironmentEntry.class)))
122                     .thenReturn(CassandraOperationStatus.GENERAL_ERROR);
123             break;
124         default:
125             throw new NotImplementedException();
126         }
127     }
128
129     @Given("^Record status is (.*)$")
130     public void record_status_is(String status) throws Throwable {
131         if (!cassandraUp) {
132             return;
133         }
134         Either<OperationalEnvironmentEntry, CassandraOperationStatus> eitherResult;
135         final OperationalEnvironmentEntry entryMock = Mockito.mock(OperationalEnvironmentEntry.class);
136         switch (status) {
137         case "FOUND_IN_PROGRESS":
138             when(entryMock.getStatus()).thenReturn(EnvironmentStatusEnum.IN_PROGRESS.getName());
139             eitherResult = Either.left(entryMock);
140             break;
141         case "FOUND_COMPLETED":
142             when(entryMock.getStatus()).thenReturn(EnvironmentStatusEnum.COMPLETED.getName());
143             eitherResult = Either.left(entryMock);
144             break;
145         case "FOUND_FAILED":
146             when(entryMock.getStatus()).thenReturn(EnvironmentStatusEnum.FAILED.getName());
147             eitherResult = Either.left(entryMock);
148             break;
149         case "NOT_FOUND":
150             eitherResult = Either.right(CassandraOperationStatus.NOT_FOUND);
151             break;
152         default:
153             throw new NotImplementedException();
154         }
155
156         when(operationalEnvironmentDao.get(operationalEnvironmentId)).thenReturn(eitherResult);
157         when(operationalEnvironmentDao.save(Mockito.any(OperationalEnvironmentEntry.class)))
158                 .thenReturn(CassandraOperationStatus.OK);
159     }
160
161     @Given("^AAI service status is (.*) and Tenant returned is (.*) and worload returned is (.*)$")
162     public void aai_service_status_is(String aaiServiceStatus, String tenant, String workload) throws Throwable {
163         this.tenantContext = tenant;
164         this.workloadContext = workload;
165         HttpResponse<String> resp = Mockito.mock(HttpResponse.class);
166         when(aaiRequestHandler.getOperationalEnvById(operationalEnvironmentId)).thenReturn(resp);
167         switch (aaiServiceStatus) {
168         case "UP":
169             when(resp.getStatusCode()).thenReturn(HttpStatus.SC_OK);
170             String aaiResponseTemplate =
171                     //@formatter:off
172                     "{\r\n"
173                     + "     \"operational-environment-id\": \"%s\",\r\n"
174                     + "     \"operational-environment-name\": \"%s\",\r\n"
175                     + "     \"operational-environment-type\": \"%s\",\r\n"
176                     + "     \"operational-environment-status\": \"IN-PROGRESS\",\r\n"
177                     + "     \"tenant-context\": \"%s\",\r\n"
178                     + "     \"workload-context\": \"%s\"\r\n"
179                     + "    }";
180                     //@formatter:on
181             when(resp.getResponse()).thenReturn(String.format(aaiResponseTemplate, operationalEnvironmentId,
182                     operationalEnvironmentName, operationalEnvironmentType, tenantContext, workloadContext));
183
184             break;
185         case "DOWN":
186             when(resp.getStatusCode()).thenReturn(HttpStatus.SC_REQUEST_TIMEOUT);
187             break;
188         default:
189             throw new NotImplementedException();
190         }
191     }
192
193     @Given("^AFT_DME service status is (.*)$")
194     public void aft_dme_service_status_is(String aftDmeStatus) throws Throwable {
195         switch (aftDmeStatus) {
196         case "UP":
197             DME2EndpointIterator mockItr = Mockito.mock(DME2EndpointIterator.class);
198             when(mockItr.hasNext()).thenReturn(false);
199             when(epIterCreator.create(Mockito.anyString())).thenReturn(mockItr);
200             break;
201         case "DOWN":
202             when(epIterCreator.create(Mockito.anyString()))
203                     .thenThrow(new DME2Exception("dummyCode", new NotImplementedException()));
204             break;
205         default:
206             throw new NotImplementedException();
207         }
208     }
209
210     @SuppressWarnings("unchecked")
211     @Given("^UEB service status is (.*)$")
212     public void ueb_service_status_is(String status) throws Throwable {
213
214         Either<ApiCredential, CambriaErrorResponse> response;
215         switch (status) {
216         case "UP":
217             ApiCredential apiCredential = Mockito.mock(ApiCredential.class);
218             when(apiCredential.getApiKey()).thenReturn("MockAPIKey");
219             when(apiCredential.getApiSecret()).thenReturn("MockSecretKey");
220             response = Either.left(apiCredential);
221             break;
222         case "DOWN":
223             CambriaErrorResponse cambriaError = Mockito.mock(CambriaErrorResponse.class);
224             response = Either.right(cambriaError);
225             break;
226         default:
227             throw new NotImplementedException();
228         }
229         when(cambriaHandler.createUebKeys(Mockito.anyList())).thenReturn(response);
230     }
231     // ############################# Given - End #############################
232
233     // ############################# When - Start #############################
234
235     @When("^handle message is activated$")
236     public void handle_message_is_activated() throws Throwable {
237         this.isSuccessful = envEngine.handleMessage(buildNotification());
238     }
239     // ############################# When - End #############################
240
241     // ############################# Then - Start #############################
242     @SuppressWarnings("unchecked")
243     @Then("^handle message activates validation of eventType (.*)$")
244     public void handle_message_activates_validation_of_eventType(boolean isValidated) throws Throwable {
245         verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isValidated)))
246                 .validateEnvironmentType(Mockito.any(Wrapper.class), Mockito.any(IDmaapNotificationData.class),
247                         Mockito.any(IDmaapAuditNotificationData.class));
248     }
249
250     @SuppressWarnings("unchecked")
251     @Then("^trying to write message to audit log and table (.*)$")
252     public void trying_to_write_message_to_audit_log_and_table(boolean isUnsupportedTypeEventRecorded) throws Throwable {
253         int count = isUnsupportedTypeEventRecorded ? 2 : 1;
254         verify(componentsUtils, Mockito.atLeast(count))
255                 .auditEnvironmentEngine(Mockito.any(AuditingActionEnum.class), Mockito.eq(operationalEnvironmentId),
256                         Mockito.any(String.class), Mockito.any(String.class), Mockito.eq(operationalEnvironmentName), Mockito.eq(tenantContext));
257     }
258
259     @SuppressWarnings("unchecked")
260     @Then("^handle message activates validation of action (.*)$")
261     public void handle_message_activates_validation_of_action(boolean isValidated) throws Throwable {
262         verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isValidated)))
263                 .validateActionType(Mockito.any(Wrapper.class), Mockito.any(IDmaapNotificationData.class));
264     }
265
266     @SuppressWarnings("unchecked")
267     @Then("^handle message activates validation of state (.*)$")
268     public void handle_message_activates_validation_of_state(boolean isValidated) throws Throwable {
269         verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isValidated)))
270                 .validateState(Mockito.any(Wrapper.class), Mockito.any(IDmaapNotificationData.class));
271     }
272
273     @SuppressWarnings("unchecked")
274     @Then("^trying to save in-progress record (.*)$")
275     public void trying_to_save_in_progress_record(boolean isActivated) throws Throwable {
276         verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated)))
277                 .saveEntryWithInProgressStatus(Mockito.any(Wrapper.class), Mockito.any(Wrapper.class), Mockito.any(IDmaapNotificationData.class));
278     }
279
280     @SuppressWarnings("unchecked")
281     @Then("^trying to get environment info from A&AI API (.*)$")
282     public void trying_to_get_environment_info_from_AAI_AP(boolean isActivated) throws Throwable {
283         verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated)))
284                 .retrieveOpEnvInfoFromAAI(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class));
285     }
286
287     @SuppressWarnings("unchecked")
288     @Then("^trying to retrieve Ueb Addresses From AftDme (.*)$")
289     public void trying_to_retrieve_ueb_addresses_from_AftDme(boolean isActivated) throws Throwable {
290         verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated))).discoverUebHosts(
291                 Mockito.anyString());
292
293     }
294
295     @SuppressWarnings("unchecked")
296     @Then("^trying to create Ueb keys (.*)$")
297     public void trying_to_create_ueb_keys(boolean isActivated) throws Throwable {
298         verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated)))
299                 .createUebKeys(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class));
300     }
301
302     @Then("^trying to create Ueb Topics (.*)$")
303     public void trying_to_create_ueb_topics(boolean isActivated) throws Throwable {
304         verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated)))
305                 .createUebTopicsForEnvironment(Mockito.any(OperationalEnvironmentEntry.class));
306     }
307
308     @Then("^handle message finished successfully (.*)$")
309     public void handle_message_finished_successfully(boolean isSuccessfull) throws Throwable {
310         Assert.assertEquals(this.isSuccessful, isSuccessfull);
311     }
312
313     // ############################# Then - End #############################
314
315     private String buildNotification() {
316         String notificationTemplate = "{ \"operationalEnvironmentId\": \"%s\",\r\n"
317                 + "             \"operationalEnvironmentName\": \"%s\",\r\n"
318                 + "             \"operationalEnvironmentType\": \"%s\",\r\n" + "             \"tenantContext\": \"%s\",\r\n"
319                 + "             \"workloadContext\": \"%s\",\r\n" + "             \"action\": \"%s\"}";
320
321         return String.format(notificationTemplate, operationalEnvironmentId, operationalEnvironmentName,
322                 operationalEnvironmentType, tenantContext, workloadContext, action);
323     }
324
325     private int getNumberOfCallsToValidate(boolean isValidated) {
326         return isValidated ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO;
327     }
328
329 }