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