aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/StepsTenantIsolation.java
blob: 1a2ca4840de444215b58c523db64bd7d04383082 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
package org.openecomp.sdc.be.components.distribution.engine;

import com.att.aft.dme2.api.DME2Exception;
import com.att.aft.dme2.iterator.DME2EndpointIterator;
import com.att.nsa.apiClient.credentials.ApiCredential;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import fj.data.Either;
import org.apache.commons.lang.NotImplementedException;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.http.HttpStatus;
import org.junit.Assert;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao;
import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.http.client.api.HttpResponse;

import static java.util.Objects.isNull;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class StepsTenantIsolation {

    // Notification Fields
    private String operationalEnvironmentId = "28122015552391";
    private String operationalEnvironmentName = "Operational Environment Name";
    private String operationalEnvironmentType;
    private String tenantContext ;
    private String workloadContext;
    private String action;

    @Mock
    private DmaapConsumer dmaapConsumer;
    @Mock
    private OperationalEnvironmentDao operationalEnvironmentDao;
    @Mock
    private DME2EndpointIteratorCreator epIterCreator;
    @Mock
    private ComponentsUtils componentsUtils;
    @Mock
    private AaiRequestHandler aaiRequestHandler;
    @Mock
    private CambriaHandler cambriaHandler;
    @InjectMocks
    @Spy
    private EnvironmentsEngine envEngine;

    private boolean isSuccessful;
    private boolean cassandraUp;

    @Before
    public void beforeScenario() {
        MockitoAnnotations.initMocks(this);
        when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED))
                .thenReturn(Either.right(CassandraOperationStatus.NOT_FOUND));
        doNothing().when(envEngine).createUebTopicsForEnvironments();
        envEngine.init();
    }

    // ############################# Given - Start #############################
    @Given("^Dmaap consumer recieved notification with fields (.*)$")
    public void dmaap_consumer_recieved_notification_with_fields(String notificationFields) throws Throwable {
        Gson gson = new GsonBuilder().create();
        IDmaapNotificationData notification = gson.fromJson(notificationFields, DmaapNotificationDataImpl.class);
        if (!isNull(notification.getOperationalEnvironmentType())) {
            this.operationalEnvironmentType = notification.getOperationalEnvironmentType().getEventTypenName();
        }
        if( !isEmpty(notification.getOperationalEnvironmentId()) ){
            this.operationalEnvironmentId = notification.getOperationalEnvironmentId();
        }
        if( !isNull(notification.getAction()) ){
            this.action = notification.getAction().getActionName();
        }

    }

    @Given("^Cassandra service status is (.*)$")
    public void cassandra_service_status_is(String status) throws Throwable {
        switch (status) {
        case "UP":
            this.cassandraUp = true;
            break;
        case "DOWN":
            when(operationalEnvironmentDao.get(operationalEnvironmentId))
                    .thenReturn(Either.right(CassandraOperationStatus.GENERAL_ERROR));
            when(operationalEnvironmentDao.save(Mockito.any(OperationalEnvironmentEntry.class)))
                    .thenReturn(CassandraOperationStatus.GENERAL_ERROR);
            break;
        default:
            throw new NotImplementedException();
        }
    }

    @Given("^Record status is (.*)$")
    public void record_status_is(String status) throws Throwable {
        if (!cassandraUp) {
            return;
        }
        Either<OperationalEnvironmentEntry, CassandraOperationStatus> eitherResult;
        final OperationalEnvironmentEntry entryMock = Mockito.mock(OperationalEnvironmentEntry.class);
        switch (status) {
        case "FOUND_IN_PROGRESS":
            when(entryMock.getStatus()).thenReturn(EnvironmentStatusEnum.IN_PROGRESS.getName());
            eitherResult = Either.left(entryMock);
            break;
        case "FOUND_COMPLETED":
            when(entryMock.getStatus()).thenReturn(EnvironmentStatusEnum.COMPLETED.getName());
            eitherResult = Either.left(entryMock);
            break;
        case "FOUND_FAILED":
            when(entryMock.getStatus()).thenReturn(EnvironmentStatusEnum.FAILED.getName());
            eitherResult = Either.left(entryMock);
            break;
        case "NOT_FOUND":
            eitherResult = Either.right(CassandraOperationStatus.NOT_FOUND);
            break;
        default:
            throw new NotImplementedException();
        }

        when(operationalEnvironmentDao.get(operationalEnvironmentId)).thenReturn(eitherResult);
        when(operationalEnvironmentDao.save(Mockito.any(OperationalEnvironmentEntry.class)))
                .thenReturn(CassandraOperationStatus.OK);
    }

    @Given("^AAI service status is (.*) and Tenant returned is (.*) and worload returned is (.*)$")
    public void aai_service_status_is(String aaiServiceStatus, String tenant, String workload) throws Throwable {
        this.tenantContext = tenant;
        this.workloadContext = workload;
        HttpResponse<String> resp = Mockito.mock(HttpResponse.class);
        when(aaiRequestHandler.getOperationalEnvById(operationalEnvironmentId)).thenReturn(resp);
        switch (aaiServiceStatus) {
        case "UP":
            when(resp.getStatusCode()).thenReturn(HttpStatus.SC_OK);
            String aaiResponseTemplate =
                    //@formatter:off
                    "{\r\n"
                    + "     \"operational-environment-id\": \"%s\",\r\n"
                    + "     \"operational-environment-name\": \"%s\",\r\n"
                    + "     \"operational-environment-type\": \"%s\",\r\n"
                    + "     \"operational-environment-status\": \"IN-PROGRESS\",\r\n"
                    + "     \"tenant-context\": \"%s\",\r\n"
                    + "     \"workload-context\": \"%s\"\r\n"
                    + "    }";
                    //@formatter:on
            when(resp.getResponse()).thenReturn(String.format(aaiResponseTemplate, operationalEnvironmentId,
                    operationalEnvironmentName, operationalEnvironmentType, tenantContext, workloadContext));

            break;
        case "DOWN":
            when(resp.getStatusCode()).thenReturn(HttpStatus.SC_REQUEST_TIMEOUT);
            break;
        default:
            throw new NotImplementedException();
        }
    }

    @Given("^AFT_DME service status is (.*)$")
    public void aft_dme_service_status_is(String aftDmeStatus) throws Throwable {
        switch (aftDmeStatus) {
        case "UP":
            DME2EndpointIterator mockItr = Mockito.mock(DME2EndpointIterator.class);
            when(mockItr.hasNext()).thenReturn(false);
            when(epIterCreator.create(Mockito.anyString())).thenReturn(mockItr);
            break;
        case "DOWN":
            when(epIterCreator.create(Mockito.anyString()))
                    .thenThrow(new DME2Exception("dummyCode", new NotImplementedException()));
            break;
        default:
            throw new NotImplementedException();
        }
    }

    @SuppressWarnings("unchecked")
    @Given("^UEB service status is (.*)$")
    public void ueb_service_status_is(String status) throws Throwable {

        Either<ApiCredential, CambriaErrorResponse> response;
        switch (status) {
        case "UP":
            ApiCredential apiCredential = Mockito.mock(ApiCredential.class);
            when(apiCredential.getApiKey()).thenReturn("MockAPIKey");
            when(apiCredential.getApiSecret()).thenReturn("MockSecretKey");
            response = Either.left(apiCredential);
            break;
        case "DOWN":
            CambriaErrorResponse cambriaError = Mockito.mock(CambriaErrorResponse.class);
            response = Either.right(cambriaError);
            break;
        default:
            throw new NotImplementedException();
        }
        when(cambriaHandler.createUebKeys(Mockito.anyList())).thenReturn(response);
    }
    // ############################# Given - End #############################

    // ############################# When - Start #############################

    @When("^handle message is activated$")
    public void handle_message_is_activated() throws Throwable {
        this.isSuccessful = envEngine.handleMessage(buildNotification());
    }
    // ############################# When - End #############################

    // ############################# Then - Start #############################
    @SuppressWarnings("unchecked")
    @Then("^handle message activates validation of eventType (.*)$")
    public void handle_message_activates_validation_of_eventType(boolean isValidated) throws Throwable {
        verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isValidated)))
                .validateEnvironmentType(Mockito.any(Wrapper.class), Mockito.any(IDmaapNotificationData.class),
                        Mockito.any(IDmaapAuditNotificationData.class));
    }

    @SuppressWarnings("unchecked")
    @Then("^trying to write message to audit log and table (.*)$")
    public void trying_to_write_message_to_audit_log_and_table(boolean isUnsupportedTypeEventRecorded) throws Throwable {
        int count = isUnsupportedTypeEventRecorded ? 2 : 1;
        verify(componentsUtils, Mockito.atLeast(count))
                .auditEnvironmentEngine(Mockito.any(AuditingActionEnum.class), Mockito.eq(operationalEnvironmentId),
                        Mockito.any(String.class), Mockito.any(String.class), Mockito.eq(operationalEnvironmentName), Mockito.eq(tenantContext));
    }

    @SuppressWarnings("unchecked")
    @Then("^handle message activates validation of action (.*)$")
    public void handle_message_activates_validation_of_action(boolean isValidated) throws Throwable {
        verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isValidated)))
                .validateActionType(Mockito.any(Wrapper.class), Mockito.any(IDmaapNotificationData.class));
    }

    @SuppressWarnings("unchecked")
    @Then("^handle message activates validation of state (.*)$")
    public void handle_message_activates_validation_of_state(boolean isValidated) throws Throwable {
        verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isValidated)))
                .validateState(Mockito.any(Wrapper.class), Mockito.any(IDmaapNotificationData.class));
    }

    @SuppressWarnings("unchecked")
    @Then("^trying to save in-progress record (.*)$")
    public void trying_to_save_in_progress_record(boolean isActivated) throws Throwable {
        verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated)))
                .saveEntryWithInProgressStatus(Mockito.any(Wrapper.class), Mockito.any(Wrapper.class), Mockito.any(IDmaapNotificationData.class));
    }

    @SuppressWarnings("unchecked")
    @Then("^trying to get environment info from A&AI API (.*)$")
    public void trying_to_get_environment_info_from_AAI_AP(boolean isActivated) throws Throwable {
        verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated)))
                .retrieveOpEnvInfoFromAAI(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class));
    }

    @SuppressWarnings("unchecked")
    @Then("^trying to retrieve Ueb Addresses From AftDme (.*)$")
    public void trying_to_retrieve_ueb_addresses_from_AftDme(boolean isActivated) throws Throwable {
        verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated))).discoverUebHosts(
                Mockito.anyString(), Mockito.anyString());

    }

    @SuppressWarnings("unchecked")
    @Then("^trying to create Ueb keys (.*)$")
    public void trying_to_create_ueb_keys(boolean isActivated) throws Throwable {
        verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated)))
                .createUebKeys(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class));
    }

    @Then("^trying to create Ueb Topics (.*)$")
    public void trying_to_create_ueb_topics(boolean isActivated) throws Throwable {
        verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated)))
                .createUebTopicsForEnvironment(Mockito.any(OperationalEnvironmentEntry.class));
    }

    @Then("^handle message finished successfully (.*)$")
    public void handle_message_finished_successfully(boolean isSuccessfull) throws Throwable {
        Assert.assertTrue(this.isSuccessful == isSuccessfull);
    }

    // ############################# Then - End #############################

    private String buildNotification() {
        String notificationTemplate = "{ \"operationalEnvironmentId\": \"%s\",\r\n"
                + "             \"operationalEnvironmentName\": \"%s\",\r\n"
                + "             \"operationalEnvironmentType\": \"%s\",\r\n" + "             \"tenantContext\": \"%s\",\r\n"
                + "             \"workloadContext\": \"%s\",\r\n" + "             \"action\": \"%s\"}";

        String notification = String.format(notificationTemplate, operationalEnvironmentId, operationalEnvironmentName,
                operationalEnvironmentType, tenantContext, workloadContext, action);
        return notification;
    }

    private int getNumberOfCallsToValidate(boolean isValidated) {
        return isValidated ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO;
    }

}