summaryrefslogtreecommitdiffstats
path: root/src/test/java
diff options
context:
space:
mode:
Diffstat (limited to 'src/test/java')
-rw-r--r--src/test/java/org/onap/dcae/ApplicationSettingsTest.java19
-rw-r--r--src/test/java/org/onap/dcae/common/EventSenderTest.java130
-rw-r--r--src/test/java/org/onap/dcae/common/JsonDataLoader.java49
-rw-r--r--src/test/java/org/onap/dcae/common/model/VesEventTest.java92
-rw-r--r--src/test/java/org/onap/dcae/restapi/EventValidatorTest.java113
-rw-r--r--src/test/java/org/onap/dcae/restapi/VesRestControllerTest.java201
6 files changed, 493 insertions, 111 deletions
diff --git a/src/test/java/org/onap/dcae/ApplicationSettingsTest.java b/src/test/java/org/onap/dcae/ApplicationSettingsTest.java
index 3d8a1a1e..6560b1ce 100644
--- a/src/test/java/org/onap/dcae/ApplicationSettingsTest.java
+++ b/src/test/java/org/onap/dcae/ApplicationSettingsTest.java
@@ -288,7 +288,6 @@ public class ApplicationSettingsTest {
// then
JsonNode correctTestObject = new ObjectMapper().readTree("{ \"state\": \"hi\" }");
- ;
assertTrue(schema.validate(correctTestObject).isEmpty());
}
@@ -316,25 +315,25 @@ public class ApplicationSettingsTest {
public void shouldReturnDMAAPStreamId() throws IOException {
// given
Map<String, String[]> expected = HashMap.of(
- "s", new String[]{"something", "something2"},
- "s2", new String[]{"something3"}
+ "log", new String[]{"ves-syslog", "ves-auditlog"},
+ "fault", new String[]{"ves-fault"}
);
// when
Map<String, String[]> dmaapStreamID = fromTemporaryConfiguration(
- "collector.dmaap.streamid=s=something,something2|s2=something3")
- .dMaaPStreamsMapping();
+ "collector.dmaap.streamid=fault=ves-fault|log=ves-syslog,ves-auditlog")
+ .getDmaapStreamIds();
// then
- assertArrayEquals(expected.get("s").get(), Objects.requireNonNull(dmaapStreamID).get("s").get());
- assertArrayEquals(expected.get("s2").get(), Objects.requireNonNull(dmaapStreamID).get("s2").get());
+ assertArrayEquals(expected.get("log").get(), Objects.requireNonNull(dmaapStreamID).get("log").get());
+ assertArrayEquals(expected.get("fault").get(), Objects.requireNonNull(dmaapStreamID).get("fault").get());
assertEquals(expected.keySet(), dmaapStreamID.keySet());
}
@Test
public void shouldReturnDefaultDMAAPStreamId() throws IOException {
// when
- Map<String, String[]> dmaapStreamID = fromTemporaryConfiguration().dMaaPStreamsMapping();
+ Map<String, String[]> dmaapStreamID = fromTemporaryConfiguration().getDmaapStreamIds();
// then
assertEquals(dmaapStreamID, HashMap.empty());
@@ -357,8 +356,8 @@ public class ApplicationSettingsTest {
).validAuthorizationCredentials();
// then
- assertEquals(allowedUsers.get("pasza").get(), "c2ltcGxlcGFzc3dvcmQNCg==");
- assertEquals(allowedUsers.get("someoneelse").get(), "c2ltcGxlcGFzc3dvcmQNCg==");
+ assertEquals( "c2ltcGxlcGFzc3dvcmQNCg==", allowedUsers.get("pasza").get());
+ assertEquals("c2ltcGxlcGFzc3dvcmQNCg==", allowedUsers.get("someoneelse").get());
}
@Test
diff --git a/src/test/java/org/onap/dcae/common/EventSenderTest.java b/src/test/java/org/onap/dcae/common/EventSenderTest.java
index f49d3cd8..e20fa993 100644
--- a/src/test/java/org/onap/dcae/common/EventSenderTest.java
+++ b/src/test/java/org/onap/dcae/common/EventSenderTest.java
@@ -3,7 +3,7 @@
* PROJECT
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * Copyright (C) 2018 Nokia. All rights reserved.s
+ * Copyright (C) 2020 Nokia. All rights reserved.s
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,56 +20,122 @@
*/
package org.onap.dcae.common;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
import io.vavr.collection.HashMap;
-import io.vavr.collection.Map;
-import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
-import org.onap.dcae.ApplicationSettings;
+import org.onap.dcae.common.model.StndDefinedNamespaceParameterNotDefinedException;
+import org.onap.dcae.common.model.VesEvent;
import org.onap.dcae.common.publishing.EventPublisher;
+import java.io.IOException;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+
@RunWith(MockitoJUnitRunner.Silent.class)
public class EventSenderTest {
- private String event = "{\"VESversion\":\"v7\",\"VESuniqueId\":\"fd69d432-5cd5-4c15-9d34-407c81c61c6a-0\",\"event\":{\"commonEventHeader\":{\"startEpochMicrosec\":1544016106000000,\"eventId\":\"fault33\",\"timeZoneOffset\":\"UTC+00.00\",\"priority\":\"Normal\",\"version\":\"4.0.1\",\"nfVendorName\":\"Ericsson\",\"reportingEntityName\":\"1\",\"sequence\":1,\"domain\":\"fault\",\"lastEpochMicrosec\":1544016106000000,\"eventName\":\"Fault_KeyFileFault\",\"vesEventListenerVersion\":\"7.0.1\",\"sourceName\":\"1\"},\"faultFields\":{\"eventSeverity\":\"CRITICAL\",\"alarmCondition\":\"KeyFileFault\",\"faultFieldsVersion\":\"4.0\",\"eventCategory\":\"PROCESSINGERRORALARM\",\"specificProblem\":\"License Key File Fault_1\",\"alarmAdditionalInformation\":{\"probableCause\":\"ConfigurationOrCustomizationError\",\"additionalText\":\"test_1\",\"source\":\"ManagedElement=1,SystemFunctions=1,Lm=1\"},\"eventSourceType\":\"Lm\",\"vfStatus\":\"Active\"}}}\n";
-
@Mock
private EventPublisher eventPublisher;
- @Mock
- private ApplicationSettings settings;
- private EventSender eventSender;
+ @Test
+ public void shouldNotSendEventWhenStreamIdIsNotDefined() throws IOException {
+ // given
+ EventSender eventSender = givenConfiguredEventSender(HashMap.empty());
+ List<VesEvent> eventToSend = createEventToSend("/eventsAfterTransformation/ves7_valid_event.json");
+
+ // when
+ eventSender.send(eventToSend);
+
+ // then
+ verifyThatEventWasNotSendAtStream();
+ }
@Test
- public void shouldntSendEventWhenStreamIdsIsEmpty() {
- when(settings.dMaaPStreamsMapping()).thenReturn(HashMap.empty());
- eventSender = new EventSender(eventPublisher, settings );
- JSONObject jsonObject = new JSONObject(event);
- JSONArray jsonArray = new JSONArray();
- jsonArray.put(jsonObject);
- eventSender.send(jsonArray);
- verify(eventPublisher,never()).sendEvent(any(),any());
+ public void shouldSendEventAtStreamsAssignedToEventDomain() throws IOException {
+ // given
+ EventSender eventSender = givenConfiguredEventSender(HashMap.of("fault", new String[]{"ves-fault", "fault-ves"}));
+ List<VesEvent> eventToSend = createEventToSend("/eventsAfterTransformation/ves7_valid_event.json");
+
+ // when
+ eventSender.send(eventToSend);
+
+ //then
+ verifyThatEventWasSendAtStream("ves-fault");
+ verifyThatEventWasSendAtStream("fault-ves");
+ }
+
+ @Test
+ public void shouldSendStdDefinedEventAtStreamAssignedToEventDomain() throws IOException {
+ // given
+ EventSender eventSender = givenConfiguredEventSender(
+ HashMap.of("3GPP-FaultSupervision", new String[]{"ves-3gpp-fault-supervision"})
+ );
+ List<VesEvent> eventToSend = createEventToSend("/eventsAfterTransformation/ves_stdnDefined_valid.json");
+
+ // when
+ eventSender.send(eventToSend);
+
+ // then
+ verifyThatEventWasSendAtStream("ves-3gpp-fault-supervision");
}
@Test
- public void shouldSendEvent() {
- Map<String, String[]> streams = HashMap.of("fault", new String[]{"ves-fault", "fault-ves"});
- when(settings.dMaaPStreamsMapping()).thenReturn(streams);
- eventSender = new EventSender(eventPublisher, settings );
+ public void shouldNotSendStndEventWhenStreamIsNotDefined() throws IOException {
+ // given
+ EventSender eventSender = givenConfiguredEventSender(HashMap.empty());
+ List<VesEvent> eventToSend = createEventToSend("/eventsAfterTransformation/ves_stdnDefined_valid.json");
+
+ // when
+ eventSender.send(eventToSend);
+
+ // then
+ verifyThatEventWasNotSendAtStream();
+ }
+
+ @Test
+ public void shouldReportThatNoStndDefinedNamespaceParameterIsDefinedInEvent() throws IOException {
+ // given
+ EventSender eventSender = givenConfiguredEventSender(HashMap.empty());
+ List<VesEvent> eventToSend = createEventToSend(
+ "/eventsAfterTransformation/ves_stdnDefined_missing_namespace_invalid.json"
+ );
+
+ // when
+ assertThatExceptionOfType(StndDefinedNamespaceParameterNotDefinedException.class)
+ .isThrownBy(() -> eventSender.send(eventToSend));
+
+ // then
+ verifyThatEventWasNotSendAtStream();
+ }
+
+ private List<VesEvent> createEventToSend(String path) throws IOException {
+ String event = JsonDataLoader.loadContent(path);
+ return givenEventToSend(event);
+ }
+
+ private EventSender givenConfiguredEventSender(io.vavr.collection.Map<String, String[]> streamIds) {
+ return new EventSender(eventPublisher, streamIds);
+ }
+
+ private List<VesEvent> givenEventToSend(String event) {
JSONObject jsonObject = new JSONObject(event);
- JSONArray jsonArray = new JSONArray();
- jsonArray.put(jsonObject);
- eventSender.send(jsonArray);
- verify(eventPublisher, times(2)).sendEvent(any(),any());
+ return List.of(new VesEvent(jsonObject));
+ }
+
+ private void verifyThatEventWasNotSendAtStream() {
+ verify(eventPublisher,never()).sendEvent(any(),any());
+ }
+
+ private void verifyThatEventWasSendAtStream(String s) {
+ verify(eventPublisher).sendEvent(any(), eq(s));
}
-} \ No newline at end of file
+}
diff --git a/src/test/java/org/onap/dcae/common/JsonDataLoader.java b/src/test/java/org/onap/dcae/common/JsonDataLoader.java
new file mode 100644
index 00000000..2ea59aa0
--- /dev/null
+++ b/src/test/java/org/onap/dcae/common/JsonDataLoader.java
@@ -0,0 +1,49 @@
+/*
+ * ============LICENSE_START=======================================================
+ * VES Collector
+ * ================================================================================
+ * Copyright (C) 2020 Nokia. All rights reserved.s
+ * ================================================================================
+ * 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.common;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+
+/**
+ * This class is static and does not have public constructor.
+ * It is responsible for data loading fot test cases.
+ *
+ * @author Zebek
+ */
+public final class JsonDataLoader {
+
+ private JsonDataLoader() {
+ }
+
+ /**
+ * This method is validating given event using schema adn throws exception if event is not valid
+ *
+ * @param path to file that will be loaded
+ * @return contend of the file located under path, given in parameters, as string
+ * @throws IOException when file under given path was not found
+ */
+ public static String loadContent(String path) throws IOException {
+ return new String(
+ Files.readAllBytes(Paths.get(JsonDataLoader.class.getResource(path).getPath()))
+ );
+ }
+}
diff --git a/src/test/java/org/onap/dcae/common/model/VesEventTest.java b/src/test/java/org/onap/dcae/common/model/VesEventTest.java
new file mode 100644
index 00000000..c66e0a9b
--- /dev/null
+++ b/src/test/java/org/onap/dcae/common/model/VesEventTest.java
@@ -0,0 +1,92 @@
+/*
+ * ============LICENSE_START=======================================================
+ * VES Collector
+ * ================================================================================
+ * Copyright (C) 2020 Nokia. All rights reserved.s
+ * ================================================================================
+ * 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.common.model;
+
+import org.assertj.core.api.Assertions;
+import org.json.JSONObject;
+import org.junit.Test;
+import org.onap.dcae.common.JsonDataLoader;
+
+import java.io.IOException;
+
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+
+public class VesEventTest {
+
+ private static final String FAULT_DOMAIN = "fault";
+ private static final String FAULT_STREAM_ID = "fault";
+ private static final String STND_DEFINED_DOMAIN = "stndDefined";
+ private static final String STND_DEFINED_STREAM_ID = "3GPP-FaultSupervision";
+
+ @Test
+ public void shouldReturnsOriginalDomainForNonStdEvent() throws IOException {
+ // given
+ final VesEvent vesEvent = createVesEvent("/eventsAfterTransformation/ves7_valid_event.json");
+
+ // when/then
+ Assertions.assertThat(vesEvent.getDomain()).isEqualTo(FAULT_DOMAIN);
+ Assertions.assertThat(vesEvent.getStreamId()).isEqualTo(FAULT_STREAM_ID);
+ }
+
+ @Test
+ public void shouldReturnsDomainStoredInStndDefinedNamespaceParameterForNonStdEvent() throws IOException {
+ // given
+ final VesEvent vesEvent = createVesEvent("/eventsAfterTransformation/ves_stdnDefined_valid.json");
+
+ // when/then
+ Assertions.assertThat(vesEvent.getDomain()).isEqualTo(STND_DEFINED_DOMAIN);
+ Assertions.assertThat(vesEvent.getStreamId()).isEqualTo(STND_DEFINED_STREAM_ID);
+ }
+
+
+ @Test
+ public void shouldReportThatStndDefinedNamespaceParameterIsNotDefinedInEvent() throws IOException {
+ // given
+ final VesEvent vesEvent = createVesEvent(
+ "/eventsAfterTransformation/ves_stdnDefined_missing_namespace_invalid.json"
+ );
+
+ // when/then
+ // when
+ assertThatExceptionOfType(StndDefinedNamespaceParameterNotDefinedException.class)
+ .isThrownBy(() -> {
+ vesEvent.getStreamId();
+ });
+ }
+
+ @Test
+ public void shouldReportThatStndDefinedNamespaceParameterHasEmptyValue() throws IOException {
+ // given
+ final VesEvent vesEvent = createVesEvent(
+ "/eventsAfterTransformation/ves_stdnDefined_empty_namespace_invalid.json"
+ );
+
+ // when/then
+ assertThatExceptionOfType(StndDefinedNamespaceParameterHasEmptyValueException.class)
+ .isThrownBy(() -> {
+ vesEvent.getStreamId();
+ });
+ }
+
+ private VesEvent createVesEvent(String path) throws IOException {
+ String event = JsonDataLoader.loadContent(path);
+ return new VesEvent(new JSONObject(event));
+ }
+}
diff --git a/src/test/java/org/onap/dcae/restapi/EventValidatorTest.java b/src/test/java/org/onap/dcae/restapi/EventValidatorTest.java
index 0d38fdac..0ca5c424 100644
--- a/src/test/java/org/onap/dcae/restapi/EventValidatorTest.java
+++ b/src/test/java/org/onap/dcae/restapi/EventValidatorTest.java
@@ -20,28 +20,29 @@
package org.onap.dcae.restapi;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.when;
-
import com.networknt.schema.JsonSchema;
import com.networknt.schema.JsonSchemaFactory;
-
-import java.util.Optional;
-
import org.json.JSONObject;
import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
-import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.dcae.ApplicationSettings;
import org.onap.dcae.FileReader;
-import org.springframework.http.ResponseEntity;
+import org.onap.dcae.common.model.VesEvent;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
-public class EventValidatorTest {
+class EventValidatorTest {
private static final String DUMMY_SCHEMA_VERSION = "v5";
private static final String DUMMY_TYPE = "type";
private final String newSchemaV7 = FileReader.readFileAsString("etc/CommonEventFormat_30.2_ONAP.json");
@@ -51,10 +52,11 @@ public class EventValidatorTest {
private static final String EVENT_TYPE = "event";
@Mock
- private static ApplicationSettings settings;
+ private ApplicationSettings settings;
+
+ private SchemaValidator schemaValidator = spy( new SchemaValidator());
- @InjectMocks
- private static EventValidator sut;
+ private EventValidator sut;
@BeforeAll
@@ -62,57 +64,70 @@ public class EventValidatorTest {
jsonObject = new JSONObject("{" + DUMMY_TYPE + ":dummy}");
}
+ @BeforeEach
+ public void setUp(){
+ this.sut = new EventValidator(settings, schemaValidator);
+ }
+
@Test
- public void shouldReturnEmptyOptionalOnJsonSchemaValidationDisabled() {
+ void shouldNotValidateEventWhenJsonSchemaValidationDisabled() throws EventValidatorException {
//given
when(settings.eventSchemaValidationEnabled()).thenReturn(false);
//when
- Optional<ResponseEntity<String>> result = sut.validate(jsonObject, DUMMY_TYPE, DUMMY_SCHEMA_VERSION);
+ this.sut.validate(new VesEvent(jsonObject), DUMMY_TYPE, DUMMY_SCHEMA_VERSION);
//then
- assertEquals(Optional.empty(), result);
+ verify(schemaValidator, never()).conformsToSchema(any(), any());
}
@Test
- public void shouldReturnInvalidJsonErrorOnWrongType() {
+ void shouldReturnInvalidJsonErrorOnWrongType() {
//given
when(settings.eventSchemaValidationEnabled()).thenReturn(true);
//when
- Optional<ResponseEntity<String>> result = sut.validate(jsonObject, "wrongType", DUMMY_SCHEMA_VERSION);
+ try {
+ sut.validate(new VesEvent(jsonObject), "wrongType", DUMMY_SCHEMA_VERSION);
+ } catch (EventValidatorException e) {
+ //then
+ assertEquals(ApiException.INVALID_JSON_INPUT, e.getApiException());
+ }
+
- //then
- assertEquals(generateResponseOptional(ApiException.INVALID_JSON_INPUT), result);
}
@Test
- public void shouldReturnSchemaValidationFailedErrorOnInvalidJsonObjectSchema() {
+ void shouldReturnSchemaValidationFailedErrorOnInvalidJsonObjectSchema() {
//given
String schemaRejectingEverything = "{\"not\":{}}";
mockJsonSchema(schemaRejectingEverything);
when(settings.eventSchemaValidationEnabled()).thenReturn(true);
//when
- Optional<ResponseEntity<String>> result = sut.validate(jsonObject, DUMMY_TYPE, DUMMY_SCHEMA_VERSION);
+ try {
+ sut.validate(new VesEvent(jsonObject), DUMMY_TYPE, DUMMY_SCHEMA_VERSION);
+ } catch (EventValidatorException e) {
+ //then
+ assertEquals(ApiException.SCHEMA_VALIDATION_FAILED, e.getApiException());
+ }
- //then
- assertEquals(generateResponseOptional(ApiException.SCHEMA_VALIDATION_FAILED), result);
}
@Test
- public void shouldReturnEmptyOptionalOnValidJsonObjectSchema() {
+ void shouldReturnEmptyOptionalOnValidJsonObjectSchema() {
//given
String schemaAcceptingEverything = "{}";
mockJsonSchema(schemaAcceptingEverything);
when(settings.eventSchemaValidationEnabled()).thenReturn(true);
//when
- Optional<ResponseEntity<String>> result = sut.validate(jsonObject, DUMMY_TYPE, DUMMY_SCHEMA_VERSION);
-
- //then
- assertEquals(Optional.empty(), result);
+ try {
+ sut.validate(new VesEvent(jsonObject), DUMMY_TYPE, DUMMY_SCHEMA_VERSION);
+ } catch (EventValidatorException e) {
+ failWithError();
+ }
}
@Test
@@ -124,14 +139,15 @@ public class EventValidatorTest {
when(settings.eventSchemaValidationEnabled()).thenReturn(true);
//when
- Optional<ResponseEntity<String>> result = sut.validate(sentEvent, EVENT_TYPE, V7_VERSION);
-
- //then
- assertEquals(Optional.empty(), result);
+ try {
+ sut.validate(new VesEvent(sentEvent), EVENT_TYPE, V7_VERSION);
+ } catch (EventValidatorException e) {
+ failWithError();
+ }
}
@Test
- public void shouldReturnNoErrorsWhenValidatingValidEventWithStndDefinedFields() {
+ void shouldReturnNoErrorsWhenValidatingValidEventWithStndDefinedFields() {
//given
sentEvent = new JSONObject(FileReader.readFileAsString("src/test/resources/ves7_valid_eventWithStndDefinedFields.json"));
@@ -139,14 +155,15 @@ public class EventValidatorTest {
when(settings.eventSchemaValidationEnabled()).thenReturn(true);
//when
- Optional<ResponseEntity<String>> result = sut.validate(sentEvent, EVENT_TYPE, V7_VERSION);
-
- //then
- assertEquals(Optional.empty(), result);
+ try {
+ sut.validate(new VesEvent(sentEvent), EVENT_TYPE, V7_VERSION);
+ } catch (EventValidatorException e) {
+ failWithError();
+ }
}
@Test
- public void shouldReturnSchemaValidationFailedWhenValidating30_1_1InvalidEvent() {
+ void shouldReturnSchemaValidationFailedWhenValidating30_1_1InvalidEvent() {
//given
sentEvent = new JSONObject(FileReader.readFileAsString("src/test/resources/ves7_invalid_30_1_1_event.json"));
@@ -154,12 +171,19 @@ public class EventValidatorTest {
when(settings.eventSchemaValidationEnabled()).thenReturn(true);
//when
- Optional<ResponseEntity<String>> result = sut.validate(this.sentEvent, EVENT_TYPE, V7_VERSION);
+ try {
+ sut.validate(new VesEvent(this.sentEvent), EVENT_TYPE, V7_VERSION);
+ } catch (EventValidatorException e) {
+ //then
+ assertEquals(ApiException.SCHEMA_VALIDATION_FAILED, e.getApiException());
+ }
+
- //then
- assertEquals(generateResponseOptional(ApiException.SCHEMA_VALIDATION_FAILED), result);
}
+ private void failWithError() {
+ fail("Validation should not report any error!");
+ }
private void mockJsonSchema(String jsonSchemaContent) {
JsonSchemaFactory factory = JsonSchemaFactory.getInstance();
@@ -167,9 +191,4 @@ public class EventValidatorTest {
JsonSchema schema = factory.getSchema(jsonSchemaContent);
when(settings.jsonSchema(any())).thenReturn(schema);
}
-
- private Optional<ResponseEntity<String>> generateResponseOptional(ApiException schemaValidationFailed) {
- return Optional.of(ResponseEntity.status(schemaValidationFailed.httpStatusCode)
- .body(schemaValidationFailed.toJSON().toString()));
- }
}
diff --git a/src/test/java/org/onap/dcae/restapi/VesRestControllerTest.java b/src/test/java/org/onap/dcae/restapi/VesRestControllerTest.java
index 6b89a356..e5e7239c 100644
--- a/src/test/java/org/onap/dcae/restapi/VesRestControllerTest.java
+++ b/src/test/java/org/onap/dcae/restapi/VesRestControllerTest.java
@@ -20,20 +20,27 @@
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.apache.http.HttpStatus;
import org.jetbrains.annotations.NotNull;
-import org.json.JSONArray;
+import org.json.JSONObject;
+import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
-import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
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.publishing.EventPublisher;
import org.slf4j.Logger;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockHttpServletRequest;
@@ -43,14 +50,15 @@ import org.springframework.web.context.request.ServletRequestAttributes;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Type;
-import java.nio.file.Files;
-import java.nio.file.Paths;
import java.util.List;
+import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
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;
@@ -58,21 +66,36 @@ import static org.mockito.Mockito.when;
public class VesRestControllerTest {
private static final String EVENT_TRANSFORM_FILE_PATH = "/eventTransform.json";
+ private static final String ACCEPTED = "Accepted";
+ private static final String VERSION_V7 = "v7";
+ public static final String VES_FAULT_TOPIC = "ves-fault";
+ public static final String VES_3_GPP_FAULT_SUPERVISION_TOPIC = "ves-3gpp-fault-supervision";
- @InjectMocks
- VesRestController vesRestController;
+ private VesRestController vesRestController;
@Mock
- ApplicationSettings applicationSettings;
+ private ApplicationSettings applicationSettings;
@Mock
- Logger logger;
+ private Logger logger;
@Mock
- EventSender eventSender;
+ private HeaderUtils headerUtils;
@Mock
- HeaderUtils headerUtils;
+ private EventPublisher eventPublisher;
+
+ @Before
+ public void setUp(){
+
+ final HashMap<String, String[]> streamIds = HashMap.of(
+ "fault", new String[]{VES_FAULT_TOPIC},
+ "3GPP-FaultSupervision", new String[]{VES_3_GPP_FAULT_SUPERVISION_TOPIC}
+ );
+ this.vesRestController = new VesRestController(
+ applicationSettings, logger, new EventSender(eventPublisher, streamIds),headerUtils
+ );
+ }
@Test
public void shouldReportThatApiVersionIsNotSupported() {
@@ -84,9 +107,9 @@ public class VesRestControllerTest {
final ResponseEntity<String> event = vesRestController.event("", "v20", request);
// then
- assertThat(event.getStatusCodeValue()).isEqualTo(400);
+ assertThat(event.getStatusCodeValue()).isEqualTo(HttpStatus.SC_BAD_REQUEST);
assertThat(event.getBody()).isEqualTo("API version v20 is not supported");
- verify(eventSender, never()).send(any(JSONArray.class));
+ verifyThatEventWasNotSend();
}
@Test
@@ -97,22 +120,153 @@ public class VesRestControllerTest {
MockHttpServletRequest request = givenMockHttpServletRequest();
- String validEvent = new String(
- Files.readAllBytes(Paths.get(this.getClass().getResource("/ves7_valid_30_1_1_event.json").getPath()))
+ 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.SC_ACCEPTED);
+ assertThat(response.getBody()).isEqualTo(ACCEPTED);
+ verifyThatTransformedEventWasSend(eventPublisher, validEvent);
+ }
+
+
+ @Test
+ public void shouldSendBatchOfEvents() throws IOException {
+ //given
+ configureEventTransformations();
+ configureHeadersForEventListener();
+
+ MockHttpServletRequest request = givenMockHttpServletRequest();
+
+ String validEvent = JsonDataLoader.loadContent("/ves7_batch_valid.json");
+
+ //when
+ final ResponseEntity<String> response = vesRestController.events(validEvent, VERSION_V7, request);
+
+ //then
+ assertThat(response.getStatusCodeValue()).isEqualTo(HttpStatus.SC_ACCEPTED);
+ assertThat(response.getBody()).isEqualTo(ACCEPTED);
+ verify(eventPublisher, times(2)).sendEvent(any(),any());
+ }
+
+ @Test
+ public void shouldSendStndDomainEventIntoDomainStream() throws IOException {
+ //given
+ configureEventTransformations();
+ configureHeadersForEventListener();
+
+ MockHttpServletRequest request = givenMockHttpServletRequest();
+ configureSchemasSupplierForStndDefineEvent();
+
+ String validEvent = JsonDataLoader.loadContent("/ves_stdnDefined_valid.json");
+
+ //when
+ final ResponseEntity<String> response = vesRestController.event(validEvent, VERSION_V7, request);
+
+ //then
+ assertThat(response.getStatusCodeValue()).isEqualTo(HttpStatus.SC_ACCEPTED);
+ assertThat(response.getBody()).isEqualTo(ACCEPTED);
+ verify(eventPublisher).sendEvent(any(),eq(VES_3_GPP_FAULT_SUPERVISION_TOPIC));
+ }
+
+
+ @Test
+ public 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.SC_BAD_REQUEST);
+ verifyErrorResponse(
+ response,
+ "SVC2006",
+ "Mandatory input attribute event.commonEventHeader.stndDefinedNamespace is missing from request"
);
+ verifyThatEventWasNotSend();
+ }
+
+ @Test
+ public 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, "v7", request);
+ final ResponseEntity<String> response = vesRestController.event(validEvent, VERSION_V7, request);
//then
- assertThat(response.getStatusCodeValue()).isEqualTo(202);
- assertThat(response.getBody()).isEqualTo("Accepted");
- verifyThatTransformedEventWasSend(eventSender, validEvent);
+ assertThat(response.getStatusCodeValue()).isEqualTo(HttpStatus.SC_BAD_REQUEST);
+ verifyErrorResponse(
+ response,
+ "SVC2006",
+ "Mandatory input attribute event.commonEventHeader.stndDefinedNamespace is empty in request"
+ );
+ verifyThatEventWasNotSend();
+ }
+
+ @Test
+ public 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.SC_ACCEPTED);
+ assertThat(response.getBody()).isEqualTo(ACCEPTED);
+ verifyThatEventWasNotSend();
+ }
+
+ 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) throws com.fasterxml.jackson.core.JsonProcessingException {
+ final Map<String, String> errorDetails = fetchErrorDetails(response);
+ assertThat(errorDetails).containsEntry("messageId", messageId);
+ assertThat(errorDetails).containsEntry("text", messageText);
+ }
+
+ private Map<String, 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("v7")).thenReturn(true);
+ when(applicationSettings.isVersionSupported(VERSION_V7)).thenReturn(true);
when(applicationSettings.eventTransformingEnabled()).thenReturn(true);
when(applicationSettings.getEventTransformations()).thenReturn(eventTransformations);
}
@@ -124,19 +278,22 @@ public class VesRestControllerTest {
);
}
- private void verifyThatTransformedEventWasSend(EventSender eventSender, String eventBeforeTransformation) {
+ private void verifyThatTransformedEventWasSend(EventPublisher eventPublisher, String eventBeforeTransformation) {
// event before transformation
assertThat(eventBeforeTransformation).contains("\"version\": \"4.0.1\"");
assertThat(eventBeforeTransformation).contains("\"faultFieldsVersion\": \"4.0\"");
- ArgumentCaptor<JSONArray> argument = ArgumentCaptor.forClass(JSONArray.class);
- verify(eventSender).send(argument.capture());
+ ArgumentCaptor<JSONObject> argument = ArgumentCaptor.forClass(JSONObject.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