aboutsummaryrefslogtreecommitdiffstats
path: root/src/test/java/org/onap/dcae/restapi/VesRestControllerTest.java
blob: 9b436871aa2a5289ccb1ee10976071b9db2db77e (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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
/*
 * ============LICENSE_START=======================================================
 * VES Collector
 * ================================================================================
 * Copyright (C) 2020-2021 Nokia. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.dcae.restapi;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.networknt.schema.JsonSchema;
import io.vavr.collection.HashMap;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.dcae.ApplicationSettings;
import org.onap.dcae.JSonSchemasSupplier;
import org.onap.dcae.common.EventSender;
import org.onap.dcae.common.EventTransformation;
import org.onap.dcae.common.HeaderUtils;
import org.onap.dcae.common.JsonDataLoader;
import org.onap.dcae.common.model.InternalException;
import org.onap.dcae.common.model.PayloadToLargeException;
import org.onap.dcae.common.publishing.DMaaPEventPublisher;
import org.onap.dcae.common.validator.StndDefinedDataValidator;
import org.slf4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.params.provider.Arguments.arguments;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;


@ExtendWith(MockitoExtension.class)
public class VesRestControllerTest {

    private static final String EVENT_TRANSFORM_FILE_PATH = "/eventTransform.json";
    private static final String ACCEPTED = "Successfully send event";
    private static final String VERSION_V7 = "v7";
    static final String VES_FAULT_TOPIC = "ves-fault";
    static final String VES_3_GPP_FAULT_SUPERVISION_TOPIC = "ves-3gpp-fault-supervision";

    private VesRestController vesRestController;

    @Mock
    private ApplicationSettings applicationSettings;

    @Mock
    private Logger logger;

    @Mock
    private Logger errorLogger;

    @Mock
    private HeaderUtils headerUtils;

    @Mock
    private DMaaPEventPublisher eventPublisher;

    @Mock
    private StndDefinedDataValidator stndDefinedDataValidator;

    @BeforeEach
    void setUp(){
        final HashMap<String, String> streamIds = HashMap.of(
                "fault", VES_FAULT_TOPIC,
                "3GPP-FaultSupervision", VES_3_GPP_FAULT_SUPERVISION_TOPIC
        );
        this.vesRestController = new VesRestController(applicationSettings, logger,
                errorLogger, new EventSender(eventPublisher, streamIds), headerUtils, stndDefinedDataValidator);
    }

    @Test
    void shouldReportThatApiVersionIsNotSupported() {
        // given
        when(applicationSettings.isVersionSupported("v20")).thenReturn(false);
        MockHttpServletRequest request = givenMockHttpServletRequest();

        // when
        final ResponseEntity<String> event = vesRestController.event("", "v20", request);

        // then
        assertThat(event.getStatusCodeValue()).isEqualTo(HttpStatus.BAD_REQUEST.value());
        assertThat(event.getBody()).isEqualTo("API version v20 is not supported");
        verifyThatEventWasNotSend();
    }

    @Test
    void shouldTransformEventAccordingToEventTransformFile() throws IOException {
        //given
        configureEventTransformations();
        configureHeadersForEventListener();

        MockHttpServletRequest request = givenMockHttpServletRequest();
        String validEvent = JsonDataLoader.loadContent("/ves7_valid_30_1_1_event.json");
        when(eventPublisher.sendEvent(any(), any())).thenReturn((HttpStatus.OK));

        //when
        final ResponseEntity<String> response = vesRestController.event(validEvent, VERSION_V7, request);

        //then
        assertThat(response.getStatusCodeValue()).isEqualTo(HttpStatus.OK.value());
        assertThat(response.getBody()).isEqualTo(ACCEPTED);
        verifyThatTransformedEventWasSend(eventPublisher, validEvent);
    }


    @Test
    void shouldSendBatchEvent() throws IOException {
        //given
        configureEventTransformations();
        configureHeadersForEventListener();

        MockHttpServletRequest request = givenMockHttpServletRequest();

        String validEvent = JsonDataLoader.loadContent("/ves7_batch_valid.json");
        when(eventPublisher.sendEvent(any(), any())).thenReturn(HttpStatus.OK);
        //when
        final ResponseEntity<String> response = vesRestController.events(validEvent, VERSION_V7, request);

        //then
        assertThat(response.getStatusCodeValue()).isEqualTo(HttpStatus.OK.value());
        assertThat(response.getBody()).isEqualTo(ACCEPTED);
        verify(eventPublisher, times(1)).sendEvent(any(),any());
    }

    @Test
    void shouldSendStndDomainEventIntoDomainStream() throws IOException {
        //given
        configureEventTransformations();
        configureHeadersForEventListener();

        MockHttpServletRequest request = givenMockHttpServletRequest();
        configureSchemasSupplierForStndDefineEvent();

        String validEvent = JsonDataLoader.loadContent("/ves_stdnDefined_valid.json");
        when(eventPublisher.sendEvent(any(), any())).thenReturn(HttpStatus.OK);

        //when
        final ResponseEntity<String> response = vesRestController.event(validEvent, VERSION_V7, request);

        //then
        assertThat(response.getStatusCodeValue()).isEqualTo(HttpStatus.OK.value());
        assertThat(response.getBody()).isEqualTo(ACCEPTED);
        verify(eventPublisher).sendEvent(any(),eq(VES_3_GPP_FAULT_SUPERVISION_TOPIC));
    }


    @Test
    void shouldReportThatStndDomainEventHasntGotNamespaceParameter() throws IOException {
        //given
        configureEventTransformations();
        configureHeadersForEventListener();

        MockHttpServletRequest request = givenMockHttpServletRequest();
        configureSchemasSupplierForStndDefineEvent();

        String validEvent = JsonDataLoader.loadContent("/ves_stdnDefined_missing_namespace_invalid.json");

        //when
        final ResponseEntity<String> response = vesRestController.event(validEvent, VERSION_V7, request);

        //then
        assertThat(response.getStatusCodeValue()).isEqualTo(HttpStatus.BAD_REQUEST.value());
        verifyErrorResponse(
                response,
                "SVC2006",
                "Mandatory input %1 %2 is missing from request",
                List.of("attribute", "event.commonEventHeader.stndDefinedNamespace")
        );
        verifyThatEventWasNotSend();
    }

    @Test
    void shouldReportThatStndDomainEventNamespaceParameterIsEmpty() throws IOException {
        //given
        configureEventTransformations();
        configureHeadersForEventListener();

        MockHttpServletRequest request = givenMockHttpServletRequest();
        configureSchemasSupplierForStndDefineEvent();

        String validEvent = JsonDataLoader.loadContent("/ves_stdnDefined_empty_namespace_invalid.json");

        //when
        final ResponseEntity<String> response = vesRestController.event(validEvent, VERSION_V7, request);

        //then
        assertThat(response.getStatusCodeValue()).isEqualTo(HttpStatus.BAD_REQUEST.value());
        verifyErrorResponse(
                response,
                "SVC2006",
                "Mandatory input %1 %2 is empty in request",
                List.of("attribute", "event.commonEventHeader.stndDefinedNamespace")
        );
        verifyThatEventWasNotSend();
    }

    @Test
    void shouldNotSendStndDomainEventWhenTopicCannotBeFoundInConfiguration() throws IOException {
        //given
        configureEventTransformations();
        configureHeadersForEventListener();

        MockHttpServletRequest request = givenMockHttpServletRequest();
        String validEvent = JsonDataLoader.loadContent("/ves_stdnDefined_valid_unknown_topic.json");

        //when
        final ResponseEntity<String> response = vesRestController.event(validEvent, VERSION_V7, request);

        //then
        assertThat(response.getStatusCodeValue()).isEqualTo(HttpStatus.BAD_REQUEST.value());
        verifyThatEventWasNotSend();
    }

    @Test
    void shouldExecuteStndDefinedValidationWhenFlagIsOnTrue() throws IOException {
        //given
        configureEventTransformations();
        configureHeadersForEventListener();

        MockHttpServletRequest request = givenMockHttpServletRequest();
        String validEvent = JsonDataLoader.loadContent("/ves7_batch_with_stndDefined_valid.json");
        when(applicationSettings.getExternalSchemaValidationCheckflag()).thenReturn(true);
        when(eventPublisher.sendEvent(any(), any())).thenReturn(HttpStatus.OK);
        //when
        final ResponseEntity<String> response = vesRestController.events(validEvent, VERSION_V7, request);

        //then
        assertThat(response.getStatusCodeValue()).isEqualTo(HttpStatus.OK.value());
        assertThat(response.getBody()).isEqualTo(ACCEPTED);
        verify(stndDefinedDataValidator, times(2)).validate(any());
    }

    @Test
    void shouldNotExecuteStndDefinedValidationWhenFlagIsOnFalse() throws IOException {
        //given
        configureEventTransformations();
        configureHeadersForEventListener();

        MockHttpServletRequest request = givenMockHttpServletRequest();
        String validEvent = JsonDataLoader.loadContent("/ves7_batch_with_stndDefined_valid.json");
        when(applicationSettings.getExternalSchemaValidationCheckflag()).thenReturn(false);
        when(eventPublisher.sendEvent(any(), any())).thenReturn(HttpStatus.OK);

        //when
        final ResponseEntity<String> response = vesRestController.events(validEvent, VERSION_V7, request);

        //then
        assertThat(response.getStatusCodeValue()).isEqualTo(HttpStatus.OK.value());
        assertThat(response.getBody()).isEqualTo(ACCEPTED);
        verify(stndDefinedDataValidator, times(0)).validate(any());
    }

    @Test
    void shouldReturn413WhenPayloadIsTooLarge() throws IOException {
        //given
        configureEventTransformations();
        configureHeadersForEventListener();

        MockHttpServletRequest request = givenMockHttpServletRequest();
        when(eventPublisher.sendEvent(any(), any())).thenThrow(new PayloadToLargeException());
        String validEvent = JsonDataLoader.loadContent("/ves7_valid_30_1_1_event.json");

        //when
        final ResponseEntity<String> response = vesRestController.event(validEvent, VERSION_V7, request);

        //then
        assertThat(response.getStatusCodeValue()).isEqualTo(HttpStatus.PAYLOAD_TOO_LARGE.value());
        verifyErrorResponse(
                response,
                "SVC2000",
                "The following service error occurred: %1. Error code is %2",
                List.of("Request Entity Too Large","413")
        );
    }

    @ParameterizedTest
    @MethodSource("errorsCodeAndResponseBody")
    void shouldMapErrorTo503AndReturnOriginalBody(ApiException apiException,String bodyVariable,String bodyVariable2) throws IOException {
        //given
        configureEventTransformations();
        configureHeadersForEventListener();

        MockHttpServletRequest request = givenMockHttpServletRequest();
        when(eventPublisher.sendEvent(any(), any())).thenThrow(new InternalException(apiException));
        String validEvent = JsonDataLoader.loadContent("/ves7_valid_30_1_1_event.json");

        //when
        final ResponseEntity<String> response = vesRestController.event(validEvent, VERSION_V7, request);

        //then
        assertThat(response.getStatusCodeValue()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE.value());
        verifyErrorResponse(
                response,
                "SVC2000",
                "The following service error occurred: %1. Error code is %2",
                List.of(bodyVariable,bodyVariable2)
        );
    }

    private static Stream<Arguments> errorsCodeAndResponseBody() {
        return Stream.of(
                arguments(ApiException.NOT_FOUND, "Not Found","404"),
                arguments(ApiException.REQUEST_TIMEOUT, "Request Timeout","408"),
                arguments(ApiException.TOO_MANY_REQUESTS, "Too Many Requests","429"),
                arguments(ApiException.INTERNAL_SERVER_ERROR, "Internal Server Error","500"),
                arguments(ApiException.BAD_GATEWAY, "Bad Gateway","502"),
                arguments(ApiException.SERVICE_UNAVAILABLE, "Service Unavailable","503"),
                arguments(ApiException.GATEWAY_TIMEOUT, "Gateway Timeout","504")
        );
    }

    private void verifyThatEventWasNotSend() {
        verify(eventPublisher, never()).sendEvent(any(), any());
    }

    private void configureSchemasSupplierForStndDefineEvent() {
        String collectorSchemaFile = "{\"v7\":\"./etc/CommonEventFormat_30.2_ONAP.json\"}";
        final io.vavr.collection.Map<String, JsonSchema> loadedJsonSchemas = new JSonSchemasSupplier().loadJsonSchemas(collectorSchemaFile);

        when(applicationSettings.eventSchemaValidationEnabled()).thenReturn(true);
        when(applicationSettings.jsonSchema(eq(VERSION_V7))).thenReturn(loadedJsonSchemas.get(VERSION_V7).get());
    }

    private void verifyErrorResponse(ResponseEntity<String> response, String messageId, String messageText, List<String> variables) throws com.fasterxml.jackson.core.JsonProcessingException {
        final Map<String, ?> errorDetails = fetchErrorDetails(response);
        assertThat((Map<String, String>)errorDetails).containsEntry("messageId", messageId);
        assertThat((Map<String, String>)errorDetails).containsEntry("text", messageText);
        assertThat((Map<String, List<String>>)errorDetails).containsEntry("variables",  variables);
    }

    private Map<String, ?> fetchErrorDetails(ResponseEntity<String> response) throws com.fasterxml.jackson.core.JsonProcessingException {
        final String body = response.getBody();
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Map<String, Map<String,String>>> map = mapper.readValue(body, Map.class);
        return map.get("requestError").get("ServiceException");
    }

    private void configureEventTransformations() throws IOException {
        final List<EventTransformation> eventTransformations = loadEventTransformations();
        when(applicationSettings.isVersionSupported(VERSION_V7)).thenReturn(true);
        when(applicationSettings.eventTransformingEnabled()).thenReturn(true);
        when(applicationSettings.getEventTransformations()).thenReturn((eventTransformations));
    }

    private void configureHeadersForEventListener() {
        when(headerUtils.getRestApiIdentify(anyString())).thenReturn("eventListener");
        when(applicationSettings.getApiVersionDescriptionFilepath()).thenReturn("etc/api_version_description.json");
    }

    private void verifyThatTransformedEventWasSend(DMaaPEventPublisher eventPublisher, String eventBeforeTransformation) {
        // event before transformation
        assertThat(eventBeforeTransformation).contains("\"version\": \"4.0.1\"");
        assertThat(eventBeforeTransformation).contains("\"faultFieldsVersion\": \"4.0\"");

        ArgumentCaptor<List> argument = ArgumentCaptor.forClass(List.class);
        ArgumentCaptor<String> domain = ArgumentCaptor.forClass(String.class);
        verify(eventPublisher).sendEvent(argument.capture(), domain.capture());

        final String transformedEvent = argument.getValue().toString();
        final String eventSentAtTopic = domain.getValue();

        // event after transformation
        assertThat(transformedEvent).contains("\"priority\":\"High\",\"version\":3,");
        assertThat(transformedEvent).contains(",\"faultFieldsVersion\":3,\"specificProblem");
        assertThat(eventSentAtTopic).isEqualTo(VES_FAULT_TOPIC);
    }

    @NotNull
    private MockHttpServletRequest givenMockHttpServletRequest() {
        MockHttpServletRequest request = new MockHttpServletRequest();
        request.setContentType("application/json");

        RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
        return request;
    }

    private List<EventTransformation> loadEventTransformations() throws IOException {
        Type EVENT_TRANSFORM_LIST_TYPE = new TypeToken<List<EventTransformation>>() {
        }.getType();

        try (FileReader fr = new FileReader(this.getClass().getResource(EVENT_TRANSFORM_FILE_PATH).getPath())) {
            return new Gson().fromJson(fr, EVENT_TRANSFORM_LIST_TYPE);
        }
    }
}