2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2020-2021 Nokia. 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.dcae.restapi;
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import com.google.common.reflect.TypeToken;
25 import com.google.gson.Gson;
26 import com.networknt.schema.JsonSchema;
27 import io.vavr.collection.HashMap;
28 import org.jetbrains.annotations.NotNull;
29 import org.junit.jupiter.api.BeforeEach;
30 import org.junit.jupiter.api.Test;
31 import org.junit.jupiter.api.extension.ExtendWith;
32 import org.junit.jupiter.params.ParameterizedTest;
33 import org.junit.jupiter.params.provider.Arguments;
34 import org.junit.jupiter.params.provider.MethodSource;
35 import org.mockito.ArgumentCaptor;
36 import org.mockito.Mock;
37 import org.mockito.junit.jupiter.MockitoExtension;
38 import org.onap.dcae.ApplicationSettings;
39 import org.onap.dcae.JSonSchemasSupplier;
40 import org.onap.dcae.common.EventSender;
41 import org.onap.dcae.common.EventTransformation;
42 import org.onap.dcae.common.HeaderUtils;
43 import org.onap.dcae.common.JsonDataLoader;
44 import org.onap.dcae.common.model.InternalException;
45 import org.onap.dcae.common.model.PayloadToLargeException;
46 import org.onap.dcae.common.publishing.DMaaPEventPublisher;
47 import org.onap.dcae.common.validator.StndDefinedDataValidator;
48 import org.slf4j.Logger;
49 import org.springframework.http.HttpStatus;
50 import org.springframework.http.ResponseEntity;
51 import org.springframework.mock.web.MockHttpServletRequest;
52 import org.springframework.web.context.request.RequestContextHolder;
53 import org.springframework.web.context.request.ServletRequestAttributes;
55 import java.io.FileReader;
56 import java.io.IOException;
57 import java.lang.reflect.Type;
58 import java.util.List;
60 import java.util.stream.Stream;
62 import static org.assertj.core.api.Assertions.assertThat;
63 import static org.junit.jupiter.params.provider.Arguments.arguments;
64 import static org.mockito.ArgumentMatchers.any;
65 import static org.mockito.ArgumentMatchers.anyString;
66 import static org.mockito.ArgumentMatchers.eq;
67 import static org.mockito.Mockito.never;
68 import static org.mockito.Mockito.times;
69 import static org.mockito.Mockito.verify;
70 import static org.mockito.Mockito.when;
73 @ExtendWith(MockitoExtension.class)
74 public class VesRestControllerTest {
76 private static final String EVENT_TRANSFORM_FILE_PATH = "/eventTransform.json";
77 private static final String ACCEPTED = "Successfully send event";
78 private static final String VERSION_V7 = "v7";
79 static final String VES_FAULT_TOPIC = "ves-fault";
80 static final String VES_3_GPP_FAULT_SUPERVISION_TOPIC = "ves-3gpp-fault-supervision";
82 private VesRestController vesRestController;
85 private ApplicationSettings applicationSettings;
88 private Logger logger;
91 private Logger errorLogger;
94 private HeaderUtils headerUtils;
97 private DMaaPEventPublisher eventPublisher;
100 private StndDefinedDataValidator stndDefinedDataValidator;
104 final HashMap<String, String> streamIds = HashMap.of(
105 "fault", VES_FAULT_TOPIC,
106 "3GPP-FaultSupervision", VES_3_GPP_FAULT_SUPERVISION_TOPIC
108 this.vesRestController = new VesRestController(applicationSettings, logger,
109 errorLogger, new EventSender(eventPublisher, streamIds), headerUtils, stndDefinedDataValidator);
113 void shouldReportThatApiVersionIsNotSupported() {
115 when(applicationSettings.isVersionSupported("v20")).thenReturn(false);
116 MockHttpServletRequest request = givenMockHttpServletRequest();
119 final ResponseEntity<String> event = vesRestController.event("", "v20", request);
122 assertThat(event.getStatusCodeValue()).isEqualTo(HttpStatus.BAD_REQUEST.value());
123 assertThat(event.getBody()).isEqualTo("API version v20 is not supported");
124 verifyThatEventWasNotSend();
128 void shouldTransformEventAccordingToEventTransformFile() throws IOException {
130 configureEventTransformations();
131 configureHeadersForEventListener();
133 MockHttpServletRequest request = givenMockHttpServletRequest();
134 String validEvent = JsonDataLoader.loadContent("/ves7_valid_30_1_1_event.json");
135 when(eventPublisher.sendEvent(any(), any())).thenReturn((HttpStatus.OK));
138 final ResponseEntity<String> response = vesRestController.event(validEvent, VERSION_V7, request);
141 assertThat(response.getStatusCodeValue()).isEqualTo(HttpStatus.OK.value());
142 assertThat(response.getBody()).isEqualTo(ACCEPTED);
143 verifyThatTransformedEventWasSend(eventPublisher, validEvent);
148 void shouldSendBatchEvent() throws IOException {
150 configureEventTransformations();
151 configureHeadersForEventListener();
153 MockHttpServletRequest request = givenMockHttpServletRequest();
155 String validEvent = JsonDataLoader.loadContent("/ves7_batch_valid.json");
156 when(eventPublisher.sendEvent(any(), any())).thenReturn(HttpStatus.OK);
158 final ResponseEntity<String> response = vesRestController.events(validEvent, VERSION_V7, request);
161 assertThat(response.getStatusCodeValue()).isEqualTo(HttpStatus.OK.value());
162 assertThat(response.getBody()).isEqualTo(ACCEPTED);
163 verify(eventPublisher, times(1)).sendEvent(any(),any());
167 void shouldSendStndDomainEventIntoDomainStream() throws IOException {
169 configureEventTransformations();
170 configureHeadersForEventListener();
172 MockHttpServletRequest request = givenMockHttpServletRequest();
173 configureSchemasSupplierForStndDefineEvent();
175 String validEvent = JsonDataLoader.loadContent("/ves_stdnDefined_valid.json");
176 when(eventPublisher.sendEvent(any(), any())).thenReturn(HttpStatus.OK);
179 final ResponseEntity<String> response = vesRestController.event(validEvent, VERSION_V7, request);
182 assertThat(response.getStatusCodeValue()).isEqualTo(HttpStatus.OK.value());
183 assertThat(response.getBody()).isEqualTo(ACCEPTED);
184 verify(eventPublisher).sendEvent(any(),eq(VES_3_GPP_FAULT_SUPERVISION_TOPIC));
189 void shouldReportThatStndDomainEventHasntGotNamespaceParameter() throws IOException {
191 configureEventTransformations();
192 configureHeadersForEventListener();
194 MockHttpServletRequest request = givenMockHttpServletRequest();
195 configureSchemasSupplierForStndDefineEvent();
197 String validEvent = JsonDataLoader.loadContent("/ves_stdnDefined_missing_namespace_invalid.json");
200 final ResponseEntity<String> response = vesRestController.event(validEvent, VERSION_V7, request);
203 assertThat(response.getStatusCodeValue()).isEqualTo(HttpStatus.BAD_REQUEST.value());
207 "Mandatory input %1 %2 is missing from request",
208 List.of("attribute", "event.commonEventHeader.stndDefinedNamespace")
210 verifyThatEventWasNotSend();
214 void shouldReportThatStndDomainEventNamespaceParameterIsEmpty() throws IOException {
216 configureEventTransformations();
217 configureHeadersForEventListener();
219 MockHttpServletRequest request = givenMockHttpServletRequest();
220 configureSchemasSupplierForStndDefineEvent();
222 String validEvent = JsonDataLoader.loadContent("/ves_stdnDefined_empty_namespace_invalid.json");
225 final ResponseEntity<String> response = vesRestController.event(validEvent, VERSION_V7, request);
228 assertThat(response.getStatusCodeValue()).isEqualTo(HttpStatus.BAD_REQUEST.value());
232 "Mandatory input %1 %2 is empty in request",
233 List.of("attribute", "event.commonEventHeader.stndDefinedNamespace")
235 verifyThatEventWasNotSend();
239 void shouldNotSendStndDomainEventWhenTopicCannotBeFoundInConfiguration() throws IOException {
241 configureEventTransformations();
242 configureHeadersForEventListener();
244 MockHttpServletRequest request = givenMockHttpServletRequest();
245 String validEvent = JsonDataLoader.loadContent("/ves_stdnDefined_valid_unknown_topic.json");
248 final ResponseEntity<String> response = vesRestController.event(validEvent, VERSION_V7, request);
251 assertThat(response.getStatusCodeValue()).isEqualTo(HttpStatus.BAD_REQUEST.value());
252 verifyThatEventWasNotSend();
256 void shouldExecuteStndDefinedValidationWhenFlagIsOnTrue() throws IOException {
258 configureEventTransformations();
259 configureHeadersForEventListener();
261 MockHttpServletRequest request = givenMockHttpServletRequest();
262 String validEvent = JsonDataLoader.loadContent("/ves7_batch_with_stndDefined_valid.json");
263 when(applicationSettings.getExternalSchemaValidationCheckflag()).thenReturn(true);
264 when(eventPublisher.sendEvent(any(), any())).thenReturn(HttpStatus.OK);
266 final ResponseEntity<String> response = vesRestController.events(validEvent, VERSION_V7, request);
269 assertThat(response.getStatusCodeValue()).isEqualTo(HttpStatus.OK.value());
270 assertThat(response.getBody()).isEqualTo(ACCEPTED);
271 verify(stndDefinedDataValidator, times(2)).validate(any());
275 void shouldNotExecuteStndDefinedValidationWhenFlagIsOnFalse() throws IOException {
277 configureEventTransformations();
278 configureHeadersForEventListener();
280 MockHttpServletRequest request = givenMockHttpServletRequest();
281 String validEvent = JsonDataLoader.loadContent("/ves7_batch_with_stndDefined_valid.json");
282 when(applicationSettings.getExternalSchemaValidationCheckflag()).thenReturn(false);
283 when(eventPublisher.sendEvent(any(), any())).thenReturn(HttpStatus.OK);
286 final ResponseEntity<String> response = vesRestController.events(validEvent, VERSION_V7, request);
289 assertThat(response.getStatusCodeValue()).isEqualTo(HttpStatus.OK.value());
290 assertThat(response.getBody()).isEqualTo(ACCEPTED);
291 verify(stndDefinedDataValidator, times(0)).validate(any());
295 void shouldReturn413WhenPayloadIsTooLarge() throws IOException {
297 configureEventTransformations();
298 configureHeadersForEventListener();
300 MockHttpServletRequest request = givenMockHttpServletRequest();
301 when(eventPublisher.sendEvent(any(), any())).thenThrow(new PayloadToLargeException());
302 String validEvent = JsonDataLoader.loadContent("/ves7_valid_30_1_1_event.json");
305 final ResponseEntity<String> response = vesRestController.event(validEvent, VERSION_V7, request);
308 assertThat(response.getStatusCodeValue()).isEqualTo(HttpStatus.PAYLOAD_TOO_LARGE.value());
312 "The following service error occurred: %1. Error code is %2",
313 List.of("Request Entity Too Large","413")
318 @MethodSource("errorsCodeAndResponseBody")
319 void shouldMapErrorTo503AndReturnOriginalBody(ApiException apiException,String bodyVariable,String bodyVariable2) throws IOException {
321 configureEventTransformations();
322 configureHeadersForEventListener();
324 MockHttpServletRequest request = givenMockHttpServletRequest();
325 when(eventPublisher.sendEvent(any(), any())).thenThrow(new InternalException(apiException));
326 String validEvent = JsonDataLoader.loadContent("/ves7_valid_30_1_1_event.json");
329 final ResponseEntity<String> response = vesRestController.event(validEvent, VERSION_V7, request);
332 assertThat(response.getStatusCodeValue()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE.value());
336 "The following service error occurred: %1. Error code is %2",
337 List.of(bodyVariable,bodyVariable2)
341 private static Stream<Arguments> errorsCodeAndResponseBody() {
343 arguments(ApiException.NOT_FOUND, "Not Found","404"),
344 arguments(ApiException.REQUEST_TIMEOUT, "Request Timeout","408"),
345 arguments(ApiException.TOO_MANY_REQUESTS, "Too Many Requests","429"),
346 arguments(ApiException.INTERNAL_SERVER_ERROR, "Internal Server Error","500"),
347 arguments(ApiException.BAD_GATEWAY, "Bad Gateway","502"),
348 arguments(ApiException.SERVICE_UNAVAILABLE, "Service Unavailable","503"),
349 arguments(ApiException.GATEWAY_TIMEOUT, "Gateway Timeout","504")
353 private void verifyThatEventWasNotSend() {
354 verify(eventPublisher, never()).sendEvent(any(), any());
357 private void configureSchemasSupplierForStndDefineEvent() {
358 String collectorSchemaFile = "{\"v7\":\"./etc/CommonEventFormat_30.2_ONAP.json\"}";
359 final io.vavr.collection.Map<String, JsonSchema> loadedJsonSchemas = new JSonSchemasSupplier().loadJsonSchemas(collectorSchemaFile);
361 when(applicationSettings.eventSchemaValidationEnabled()).thenReturn(true);
362 when(applicationSettings.jsonSchema(eq(VERSION_V7))).thenReturn(loadedJsonSchemas.get(VERSION_V7).get());
365 private void verifyErrorResponse(ResponseEntity<String> response, String messageId, String messageText, List<String> variables) throws com.fasterxml.jackson.core.JsonProcessingException {
366 final Map<String, ?> errorDetails = fetchErrorDetails(response);
367 assertThat((Map<String, String>)errorDetails).containsEntry("messageId", messageId);
368 assertThat((Map<String, String>)errorDetails).containsEntry("text", messageText);
369 assertThat((Map<String, List<String>>)errorDetails).containsEntry("variables", variables);
372 private Map<String, ?> fetchErrorDetails(ResponseEntity<String> response) throws com.fasterxml.jackson.core.JsonProcessingException {
373 final String body = response.getBody();
374 ObjectMapper mapper = new ObjectMapper();
375 Map<String, Map<String, Map<String,String>>> map = mapper.readValue(body, Map.class);
376 return map.get("requestError").get("ServiceException");
379 private void configureEventTransformations() throws IOException {
380 final List<EventTransformation> eventTransformations = loadEventTransformations();
381 when(applicationSettings.isVersionSupported(VERSION_V7)).thenReturn(true);
382 when(applicationSettings.eventTransformingEnabled()).thenReturn(true);
383 when(applicationSettings.getEventTransformations()).thenReturn((eventTransformations));
386 private void configureHeadersForEventListener() {
387 when(headerUtils.getRestApiIdentify(anyString())).thenReturn("eventListener");
388 when(applicationSettings.getApiVersionDescriptionFilepath()).thenReturn("etc/api_version_description.json");
391 private void verifyThatTransformedEventWasSend(DMaaPEventPublisher eventPublisher, String eventBeforeTransformation) {
392 // event before transformation
393 assertThat(eventBeforeTransformation).contains("\"version\": \"4.0.1\"");
394 assertThat(eventBeforeTransformation).contains("\"faultFieldsVersion\": \"4.0\"");
396 ArgumentCaptor<List> argument = ArgumentCaptor.forClass(List.class);
397 ArgumentCaptor<String> domain = ArgumentCaptor.forClass(String.class);
398 verify(eventPublisher).sendEvent(argument.capture(), domain.capture());
400 final String transformedEvent = argument.getValue().toString();
401 final String eventSentAtTopic = domain.getValue();
403 // event after transformation
404 assertThat(transformedEvent).contains("\"priority\":\"High\",\"version\":3,");
405 assertThat(transformedEvent).contains(",\"faultFieldsVersion\":3,\"specificProblem");
406 assertThat(eventSentAtTopic).isEqualTo(VES_FAULT_TOPIC);
410 private MockHttpServletRequest givenMockHttpServletRequest() {
411 MockHttpServletRequest request = new MockHttpServletRequest();
412 request.setContentType("application/json");
414 RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
418 private List<EventTransformation> loadEventTransformations() throws IOException {
419 Type EVENT_TRANSFORM_LIST_TYPE = new TypeToken<List<EventTransformation>>() {
422 try (FileReader fr = new FileReader(this.getClass().getResource(EVENT_TRANSFORM_FILE_PATH).getPath())) {
423 return new Gson().fromJson(fr, EVENT_TRANSFORM_LIST_TYPE);