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