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