diff options
Diffstat (limited to 'aai-core/src/test/java')
42 files changed, 1142 insertions, 549 deletions
diff --git a/aai-core/src/test/java/org/onap/aai/AAISetup.java b/aai-core/src/test/java/org/onap/aai/AAISetup.java index e1fc351f..5273c6e7 100644 --- a/aai-core/src/test/java/org/onap/aai/AAISetup.java +++ b/aai-core/src/test/java/org/onap/aai/AAISetup.java @@ -33,6 +33,7 @@ import org.onap.aai.nodes.NodeIngestor; import org.onap.aai.prevalidation.ValidationConfiguration; import org.onap.aai.prevalidation.ValidationService; import org.onap.aai.rest.db.HttpEntry; +import org.onap.aai.rest.notification.NotificationService; import org.onap.aai.serialization.db.EdgeSerializer; import org.onap.aai.serialization.queryformats.QueryFormatTestHelper; import org.onap.aai.setup.AAIConfigTranslator; @@ -51,11 +52,13 @@ import org.springframework.test.context.web.WebAppConfiguration; @ContextConfiguration( classes = {ConfigConfiguration.class, AAIConfigTranslator.class, EdgeIngestor.class, EdgeSerializer.class, NodeIngestor.class, SpringContextAware.class, IntrospectionConfig.class, RestBeanConfig.class, - XmlFormatTransformerConfiguration.class, ValidationService.class, ValidationConfiguration.class}) + XmlFormatTransformerConfiguration.class, ValidationService.class, ValidationConfiguration.class, + KafkaConfig.class, LoaderFactory.class, NotificationService.class, KafkaConfig.class}) @TestPropertySource( properties = {"schema.uri.base.path = /aai", "schema.xsd.maxoccurs = 5000", "schema.translator.list=config", "schema.nodes.location=src/test/resources/onap/oxm", - "schema.edges.location=src/test/resources/onap/dbedgerules"}) + "schema.edges.location=src/test/resources/onap/dbedgerules", + "aai.notifications.enabled=false"}) public abstract class AAISetup { @ClassRule diff --git a/aai-core/src/test/java/org/onap/aai/DataLinkSetup.java b/aai-core/src/test/java/org/onap/aai/DataLinkSetup.java index b8782045..5ede5c22 100644 --- a/aai-core/src/test/java/org/onap/aai/DataLinkSetup.java +++ b/aai-core/src/test/java/org/onap/aai/DataLinkSetup.java @@ -31,6 +31,7 @@ import org.onap.aai.introspection.LoaderFactory; import org.onap.aai.introspection.MoxyLoader; import org.onap.aai.nodes.NodeIngestor; import org.onap.aai.rest.db.HttpEntry; +import org.onap.aai.rest.notification.NotificationService; import org.onap.aai.serialization.db.EdgeSerializer; import org.onap.aai.serialization.queryformats.QueryFormatTestHelper; import org.onap.aai.setup.SchemaVersion; @@ -48,13 +49,13 @@ import org.springframework.test.context.junit4.rules.SpringMethodRule; @ContextConfiguration( classes = {ConfigConfiguration.class, TestUtilConfigTranslatorforDataLink.class, EdgeIngestor.class, EdgeSerializer.class, NodeIngestor.class, SpringContextAware.class, IntrospectionConfig.class, - RestBeanConfig.class, XmlFormatTransformerConfiguration.class}) + RestBeanConfig.class, XmlFormatTransformerConfiguration.class, LoaderFactory.class, NotificationService.class, KafkaConfig.class}) @TestPropertySource( properties = {"schema.uri.base.path = /aai", "schema.xsd.maxoccurs = 5000", "schema.version.api.default = v4", "schema.version.edge.label.start = v4", "schema.version.depth.start = v3", "schema.version.app.root.start = v4", "schema.version.related.link.start = v4", "schema.version.namespace.change.start = v4", "schema.version.list = v1,v2,v3,v4", - "schema.translator.list = config"}) + "schema.translator.list = config","aai.notifications.enabled = false"}) @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) public abstract class DataLinkSetup { diff --git a/aai-core/src/test/java/org/onap/aai/HttpTestUtil.java b/aai-core/src/test/java/org/onap/aai/HttpTestUtil.java index 07764ecc..62f63ea3 100644 --- a/aai-core/src/test/java/org/onap/aai/HttpTestUtil.java +++ b/aai-core/src/test/java/org/onap/aai/HttpTestUtil.java @@ -52,7 +52,7 @@ import org.onap.aai.parsers.query.QueryParser; import org.onap.aai.parsers.uri.URIToObject; import org.onap.aai.rest.db.DBRequest; import org.onap.aai.rest.db.HttpEntry; -import org.onap.aai.rest.ueb.UEBNotification; +import org.onap.aai.rest.notification.UEBNotification; import org.onap.aai.restcore.HttpMethod; import org.onap.aai.restcore.RESTAPI; import org.onap.aai.serialization.engines.QueryStyle; @@ -153,14 +153,6 @@ public class HttpTestUtil extends RESTAPI { doReturn(null).when(queryParameters).remove(any()); when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON); - - try { - if (notification != null) { - doNothing().when(notification).triggerEvents(); - } - } catch (AAIException e) { - e.printStackTrace(); - } } public Response doPut(String uri, String payload) throws UnsupportedEncodingException, AAIException { diff --git a/aai-core/src/test/java/org/onap/aai/db/DbMethHelperTest.java b/aai-core/src/test/java/org/onap/aai/db/DbMethHelperTest.java index c79b9148..7bea305e 100644 --- a/aai-core/src/test/java/org/onap/aai/db/DbMethHelperTest.java +++ b/aai-core/src/test/java/org/onap/aai/db/DbMethHelperTest.java @@ -36,7 +36,6 @@ import org.apache.commons.io.IOUtils; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.structure.VertexProperty; import org.janusgraph.core.JanusGraphFactory; import org.junit.After; import org.junit.AfterClass; diff --git a/aai-core/src/test/java/org/onap/aai/domain/model/AAIResourceTest.java b/aai-core/src/test/java/org/onap/aai/domain/model/AAIResourceTest.java index 3ef1befa..5eb0d99c 100644 --- a/aai-core/src/test/java/org/onap/aai/domain/model/AAIResourceTest.java +++ b/aai-core/src/test/java/org/onap/aai/domain/model/AAIResourceTest.java @@ -23,7 +23,9 @@ package org.onap.aai.domain.model; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; import org.junit.Assert; import org.junit.Before; diff --git a/aai-core/src/test/java/org/onap/aai/introspection/IntrospectorSerializationTest.java b/aai-core/src/test/java/org/onap/aai/introspection/IntrospectorSerializationTest.java new file mode 100644 index 00000000..60749ddd --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/introspection/IntrospectorSerializationTest.java @@ -0,0 +1,87 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2024 Deutsche Telekom. 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.aai.introspection; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.AAISetup; +import org.onap.aai.domain.notificationEvent.NotificationEvent; +import org.onap.aai.domain.notificationEvent.NotificationEvent.EventHeader; +import org.onap.aai.introspection.exceptions.AAIUnmarshallingException; +import org.onap.aai.setup.SchemaVersion; +import org.skyscreamer.jsonassert.JSONAssert; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule; + +public class IntrospectorSerializationTest extends AAISetup { + + ObjectMapper mapper; + Loader loader; + + @Before + public void setup() { + loader = loaderFactory.getMoxyLoaderInstance().get(new SchemaVersion("v14")); + } + + @Test + public void serializePlain() throws IOException, AAIUnmarshallingException { + mapper = new ObjectMapper(); + + String pserver = new String(Files.readAllBytes(Path.of("src/test/resources/payloads/templates/pserver.json"))); + Introspector introspector = loader.unmarshal("pserver", pserver); + String result = mapper.writeValueAsString(introspector); + JSONAssert.assertEquals(pserver, result, false); + } + + @Test + public void serializeNotificationEvent() throws IOException, AAIUnmarshallingException { + mapper = new ObjectMapper(); + mapper.registerModule(new JaxbAnnotationModule()); + + String pserver = new String(Files.readAllBytes(Path.of("src/test/resources/payloads/templates/pserver.json"))).replace("${hostname}", "pserver1"); + Introspector introspector = loader.unmarshal("pserver", pserver); + + NotificationEvent notificationEvent = new NotificationEvent(); + notificationEvent.setCambriaPartition("AAI"); + notificationEvent.setEntity(introspector); + EventHeader eventHeader = new EventHeader(); + eventHeader.setSeverity("NORMAL"); + eventHeader.setEntityType("pserver"); + eventHeader.setTopEntityType("pserver"); + eventHeader.setEntityLink("/aai/v14/cloud-infrastructure/pservers/pserver/pserver1"); + eventHeader.setEventType("AAI-EVENT"); + eventHeader.setDomain("devINT1"); + eventHeader.setAction("CREATE"); + eventHeader.setSequenceNumber("0"); + eventHeader.setId("someTransaction"); + eventHeader.setSourceName("test"); + eventHeader.setVersion("v14"); + notificationEvent.setEventHeader(eventHeader); + String result = mapper.writeValueAsString(notificationEvent); + String expectedEvent = new String(Files.readAllBytes(Path.of("src/test/resources/payloads/expected/pserver-event.json"))); + JSONAssert.assertEquals(expectedEvent, result, false); + } +} diff --git a/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataLinkTest.java b/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataLinkTest.java index 138723aa..368a9466 100644 --- a/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataLinkTest.java +++ b/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataLinkTest.java @@ -218,7 +218,7 @@ public class DataLinkTest extends DataLinkSetup { } - /** + /** * This is more directly testing the modification mechanism (see verifyModificationOfVertex test) */ @Test @@ -229,7 +229,7 @@ public class DataLinkTest extends DataLinkSetup { URI uri = new URI("/network/vpn-bindings/vpn-binding/modifyKey/route-targets/route-target/modifyTargetKey2/modifyRoleKey2"); MultivaluedMap<String, String> map = URITools.getQueryMap(uri); GraphTraversal<Vertex, Vertex> traversal = __.<Vertex>start(); - + QueryParser uriQuery = dbEngine.getQueryBuilder(this.queryStyle, loader, source, traversal).createQueryFromURI(uri, map); List<Vertex> results = uriQuery.getQueryBuilder().toList(); @@ -390,4 +390,3 @@ public class DataLinkTest extends DataLinkSetup { } } -
\ No newline at end of file diff --git a/aai-core/src/test/java/org/onap/aai/introspection/tools/CreateUUIDTest.java b/aai-core/src/test/java/org/onap/aai/introspection/tools/CreateUUIDTest.java index 6d8508ce..49baf789 100644 --- a/aai-core/src/test/java/org/onap/aai/introspection/tools/CreateUUIDTest.java +++ b/aai-core/src/test/java/org/onap/aai/introspection/tools/CreateUUIDTest.java @@ -26,7 +26,10 @@ import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.onap.aai.AAISetup; -import org.onap.aai.introspection.*; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.LoaderFactory; +import org.onap.aai.introspection.ModelType; import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; import org.springframework.test.annotation.DirtiesContext; diff --git a/aai-core/src/test/java/org/onap/aai/introspection/tools/DefaultFieldsTest.java b/aai-core/src/test/java/org/onap/aai/introspection/tools/DefaultFieldsTest.java index 664a69c5..704f02a1 100644 --- a/aai-core/src/test/java/org/onap/aai/introspection/tools/DefaultFieldsTest.java +++ b/aai-core/src/test/java/org/onap/aai/introspection/tools/DefaultFieldsTest.java @@ -28,7 +28,10 @@ import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.onap.aai.AAISetup; -import org.onap.aai.introspection.*; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.LoaderFactory; +import org.onap.aai.introspection.ModelType; import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; import org.springframework.test.annotation.DirtiesContext; diff --git a/aai-core/src/test/java/org/onap/aai/introspection/tools/InjectKeysFromURITest.java b/aai-core/src/test/java/org/onap/aai/introspection/tools/InjectKeysFromURITest.java index cd5bdb93..15ba9a5e 100644 --- a/aai-core/src/test/java/org/onap/aai/introspection/tools/InjectKeysFromURITest.java +++ b/aai-core/src/test/java/org/onap/aai/introspection/tools/InjectKeysFromURITest.java @@ -31,7 +31,10 @@ import java.net.URI; import org.junit.Before; import org.junit.Test; import org.onap.aai.AAISetup; -import org.onap.aai.introspection.*; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.LoaderFactory; +import org.onap.aai.introspection.ModelType; import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; import org.springframework.test.annotation.DirtiesContext; diff --git a/aai-core/src/test/java/org/onap/aai/introspection/tools/RemoveNonVisiblePropertyTest.java b/aai-core/src/test/java/org/onap/aai/introspection/tools/RemoveNonVisiblePropertyTest.java index a3380ee2..2ca97007 100644 --- a/aai-core/src/test/java/org/onap/aai/introspection/tools/RemoveNonVisiblePropertyTest.java +++ b/aai-core/src/test/java/org/onap/aai/introspection/tools/RemoveNonVisiblePropertyTest.java @@ -27,7 +27,10 @@ import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.onap.aai.AAISetup; -import org.onap.aai.introspection.*; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.LoaderFactory; +import org.onap.aai.introspection.ModelType; import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; import org.springframework.test.annotation.DirtiesContext; diff --git a/aai-core/src/test/java/org/onap/aai/introspection/validation/IntrospectorValidationTest.java b/aai-core/src/test/java/org/onap/aai/introspection/validation/IntrospectorValidationTest.java index 88e148f1..374ee558 100644 --- a/aai-core/src/test/java/org/onap/aai/introspection/validation/IntrospectorValidationTest.java +++ b/aai-core/src/test/java/org/onap/aai/introspection/validation/IntrospectorValidationTest.java @@ -29,7 +29,10 @@ import org.junit.Ignore; import org.junit.Test; import org.onap.aai.AAISetup; import org.onap.aai.exceptions.AAIException; -import org.onap.aai.introspection.*; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.LoaderFactory; +import org.onap.aai.introspection.ModelType; import org.onap.aai.introspection.tools.IntrospectorValidator; import org.onap.aai.introspection.tools.Issue; import org.onap.aai.introspection.tools.IssueType; diff --git a/aai-core/src/test/java/org/onap/aai/kafka/AAIKafkaEventIntegrationTest.java b/aai-core/src/test/java/org/onap/aai/kafka/AAIKafkaEventIntegrationTest.java new file mode 100644 index 00000000..d00fa818 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/kafka/AAIKafkaEventIntegrationTest.java @@ -0,0 +1,167 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2024 Deutsche Telekom. 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.aai.kafka; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.UriInfo; + +import org.apache.kafka.clients.consumer.Consumer; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Mock; +import org.onap.aai.AAISetup; +import org.onap.aai.PayloadUtil; +import org.onap.aai.domain.notificationEvent.NotificationEvent; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.parsers.query.QueryParser; +import org.onap.aai.rest.db.DBRequest; +import org.onap.aai.restcore.HttpMethod; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; +import org.onap.aai.setup.SchemaVersion; +import org.skyscreamer.jsonassert.JSONAssert; +import org.skyscreamer.jsonassert.JSONCompareMode; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Import; +import org.springframework.kafka.core.ConsumerFactory; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.test.context.EmbeddedKafka; +import org.springframework.kafka.test.utils.KafkaTestUtils; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.TestPropertySource; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@ActiveProfiles("kafka") +@Import(KafkaTestConfiguration.class) +@EmbeddedKafka(partitions = 1, topics = { "AAI-EVENT" }) +@TestPropertySource( + properties = { + "aai.events.enabled=true", + "spring.kafka.producer.retries=0", + "spring.kafka.producer.properties.sasl.jaas.config=#{null}", + "spring.kafka.producer.bootstrap-servers=${spring.embedded.kafka.brokers}", + "aai.notifications.enabled=true" + }) +public class AAIKafkaEventIntegrationTest extends AAISetup { + + @Mock + private KafkaTemplate<String, String> kafkaTemplate; + + @Autowired + ObjectMapper mapper; + + @Autowired + NotificationProducer messageProducer; + + @Autowired + private ConsumerFactory<String, String> consumerFactory; + + @Mock UriInfo uriInfoMock; + @Mock MultivaluedMap<String, String> queryParamsMock; + @Mock HttpHeaders headersMock; + + @Before + public void setup() { + when(headersMock.getAcceptableMediaTypes()).thenReturn(Collections.singletonList(MediaType.APPLICATION_JSON_TYPE)); + when(uriInfoMock.getQueryParameters(anyBoolean())).thenReturn(queryParamsMock); + when(queryParamsMock.getFirst("depth")).thenReturn("0"); + when(headersMock.getRequestHeader("aai-request-context")).thenReturn(null); + } + + @Test + @Ignore + public void onMessage_shouldSendMessageToKafkaTopic_whenAAIEventReceived() + throws Exception { + Consumer<String, String> consumer = consumerFactory.createConsumer(); + + consumer.subscribe(Collections.singletonList("AAI-EVENT")); + + String payload = PayloadUtil.getResourcePayload("aai-event.json"); + NotificationEvent event = mapper.readValue(payload, NotificationEvent.class); + String expectedResponse = PayloadUtil.getExpectedPayload("aai-event.json"); + messageProducer.sendNotification(event); + + ConsumerRecords<String, String> consumerRecords = KafkaTestUtils.getRecords(consumer, 10000); + assertFalse(consumerRecords.isEmpty()); + consumerRecords.forEach(consumerRecord -> { + JSONAssert.assertEquals(expectedResponse, consumerRecord.value(), JSONCompareMode.NON_EXTENSIBLE); + }); + } + + @Test + public void thatEventsAreBeingCreated() throws AAIException, IOException { + Consumer<String, String> consumer = consumerFactory.createConsumer(); + consumer.subscribe(Collections.singletonList("AAI-EVENT")); + + traversalUriHttpEntry.setHttpEntryProperties(new SchemaVersion("v14")); + String pserverUri = "/aai/v14/cloud-infrastructure/pservers/pserver/pserver1"; + String entity = new String(Files.readAllBytes(Path.of("src/test/resources/payloads/templates/pserver.json"))).replace("${hostname}", "pserver1"); + DBRequest dbRequest = createDBRequest(pserverUri, entity); + List<DBRequest> dbRequests = new ArrayList<>(); + dbRequests.add(dbRequest); + + traversalUriHttpEntry.process(dbRequests, "test"); + + ConsumerRecords<String, String> consumerRecords = KafkaTestUtils.getRecords(consumer, 100000); + assertFalse(consumerRecords.isEmpty()); + String expectedResponse = PayloadUtil.getExpectedPayload("pserver-event.json"); + + consumerRecords.forEach(consumerRecord -> { + JSONAssert.assertEquals(expectedResponse, consumerRecord.value(), JSONCompareMode.LENIENT); + }); + } + + @SneakyThrows + private DBRequest createDBRequest(String uri, String entity) { + TransactionalGraphEngine dbEngine = traversalUriHttpEntry.getDbEngine(); + Loader loader = traversalUriHttpEntry.getLoader(); + URI uriObject = new URI(uri); + QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject); + String objName = uriQuery.getResultType(); + Introspector obj = loader.unmarshal(objName, entity, + org.onap.aai.restcore.MediaType.getEnum("application/json")); + return new DBRequest.Builder(HttpMethod.PUT, uriObject, uriQuery, obj, headersMock, uriInfoMock, "someTransaction") + .rawRequestContent(entity) + .build(); + } + +} diff --git a/aai-core/src/test/java/org/onap/aai/kafka/AAIKafkaEventJMSConsumerTest.java b/aai-core/src/test/java/org/onap/aai/kafka/AAIKafkaEventJMSConsumerTest.java deleted file mode 100644 index c72499c4..00000000 --- a/aai-core/src/test/java/org/onap/aai/kafka/AAIKafkaEventJMSConsumerTest.java +++ /dev/null @@ -1,89 +0,0 @@ -package org.onap.aai.kafka; - -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import javax.jms.TextMessage; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import org.onap.aai.PayloadUtil; -import org.springframework.core.env.Environment; -import org.springframework.kafka.core.KafkaTemplate; -import org.springframework.kafka.test.context.EmbeddedKafka; -import org.springframework.test.util.ReflectionTestUtils; - -@RunWith(MockitoJUnitRunner.class) -@EmbeddedKafka(partitions = 1, brokerProperties = { "listeners=PLAINTEXT://localhost:9092", "port=9092" }) -public class AAIKafkaEventJMSConsumerTest { - - @Mock - private Environment environment; - - @Mock - private KafkaTemplate<String,String> kafkaTemplate; - - private AAIKafkaEventJMSConsumer aaiKafkaEventJMSConsumer; - - @Before - public void setUp(){ - aaiKafkaEventJMSConsumer = new AAIKafkaEventJMSConsumer(environment,kafkaTemplate); - } - - @Test - public void onMessage_shouldSendMessageToKafkaTopic_whenAAIEventReceived() - throws Exception - { - TextMessage mockTextMessage = mock(TextMessage.class); - String payload = PayloadUtil.getResourcePayload("aai-event.json"); - - when(mockTextMessage.getText()).thenReturn(payload); - aaiKafkaEventJMSConsumer.onMessage(mockTextMessage); - verify(kafkaTemplate, times(1)).send(eq("AAI-EVENT"), anyString()); - } - - @Test - public void onMessage_shouldNotSendMessageToKafkaTopic_whenInvalidEventReceived() throws Exception{ - TextMessage mockTextMessage = mock(TextMessage.class); - String payload = PayloadUtil.getResourcePayload("aai-invalid-event.json"); - when(mockTextMessage.getText()).thenReturn(payload); - aaiKafkaEventJMSConsumer.onMessage(mockTextMessage); - } - - - @Test - public void onMessage_shouldHandleJSONException() throws Exception { - // Arrange - AAIKafkaEventJMSConsumer consumer = new AAIKafkaEventJMSConsumer(null, kafkaTemplate); - TextMessage mockTextMessage = mock(TextMessage.class); - ReflectionTestUtils.setField(consumer, "kafkaTemplate", null); // Simulate null kafkaTemplate - - // Act - consumer.onMessage(mockTextMessage); - - // Assert - // Verify that exception is logged - } - - @Test - public void onMessage_shouldHandleGenericException() throws Exception { - // Arrange - AAIKafkaEventJMSConsumer consumer = new AAIKafkaEventJMSConsumer(null, kafkaTemplate); - TextMessage mockTextMessage = mock(TextMessage.class); - when(mockTextMessage.getText()).thenReturn("{\"event-topic\":\"AAI-EVENT\",\"aaiEventPayload\":{}}"); // Valid JSON but missing required fields - - // Act - consumer.onMessage(mockTextMessage); - - // Assert - // Verify that exception is logged - } - -} diff --git a/aai-core/src/test/java/org/onap/aai/kafka/KafkaTestConfiguration.java b/aai-core/src/test/java/org/onap/aai/kafka/KafkaTestConfiguration.java new file mode 100644 index 00000000..e77f21af --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/kafka/KafkaTestConfiguration.java @@ -0,0 +1,76 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2024 Deutsche Telekom. 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.aai.kafka; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.kafka.clients.admin.AdminClientConfig; +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.common.serialization.StringDeserializer; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; +import org.springframework.kafka.core.ConsumerFactory; +import org.springframework.kafka.core.DefaultKafkaConsumerFactory; +import org.springframework.kafka.core.KafkaAdmin; + +@TestConfiguration +public class KafkaTestConfiguration { + + @Value("${spring.embedded.kafka.brokers}") private String bootstrapAddress; + + private String groupId = "test-consumer"; + + @Bean + public KafkaAdmin kafkaAdmin() { + Map<String, Object> configs = new HashMap<>(); + configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress); + return new KafkaAdmin(configs); + } + + @Bean + public ConsumerFactory<String, String> consumerFactory() { + Map<String, Object> props = new HashMap<>(); + props.put( + ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, + bootstrapAddress); + props.put( + ConsumerConfig.GROUP_ID_CONFIG, + groupId); + props.put( + ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, + StringDeserializer.class); + props.put( + ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, + StringDeserializer.class); + props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); + return new DefaultKafkaConsumerFactory<>(props); + } + + @Bean + public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory(ConsumerFactory<String, String> consumerFactory) { + + ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>(); + factory.setConsumerFactory(consumerFactory); + return factory; + } +} diff --git a/aai-core/src/test/java/org/onap/aai/parsers/query/GraphTraversalTest.java b/aai-core/src/test/java/org/onap/aai/parsers/query/GraphTraversalTest.java index 04a29916..7651d409 100644 --- a/aai-core/src/test/java/org/onap/aai/parsers/query/GraphTraversalTest.java +++ b/aai-core/src/test/java/org/onap/aai/parsers/query/GraphTraversalTest.java @@ -52,8 +52,6 @@ import org.onap.aai.TinkerpopUpgrade; import org.onap.aai.db.props.AAIProperties; import org.onap.aai.exceptions.AAIException; import org.onap.aai.introspection.ModelType; -import org.onap.aai.query.builder.Pageable; -import org.onap.aai.query.builder.QueryBuilder; import org.onap.aai.rest.RestTokens; import org.onap.aai.serialization.engines.JanusGraphDBEngine; import org.onap.aai.serialization.engines.QueryStyle; diff --git a/aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipGremlinQueryTest.java b/aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipGremlinQueryTest.java index 96a22d4e..2675045c 100644 --- a/aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipGremlinQueryTest.java +++ b/aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipGremlinQueryTest.java @@ -40,7 +40,10 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.onap.aai.AAISetup; import org.onap.aai.exceptions.AAIException; -import org.onap.aai.introspection.*; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.IntrospectorFactory; +import org.onap.aai.introspection.LoaderFactory; +import org.onap.aai.introspection.ModelType; import org.onap.aai.nodes.NodeIngestor; import org.onap.aai.serialization.engines.JanusGraphDBEngine; import org.onap.aai.serialization.engines.QueryStyle; diff --git a/aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipQueryTest.java b/aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipQueryTest.java index b0f6b240..accb471c 100644 --- a/aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipQueryTest.java +++ b/aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipQueryTest.java @@ -37,7 +37,10 @@ import org.junit.Ignore; import org.junit.Test; import org.onap.aai.AAISetup; import org.onap.aai.exceptions.AAIException; -import org.onap.aai.introspection.*; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.IntrospectorFactory; +import org.onap.aai.introspection.LoaderFactory; +import org.onap.aai.introspection.ModelType; import org.onap.aai.serialization.engines.JanusGraphDBEngine; import org.onap.aai.serialization.engines.QueryStyle; import org.onap.aai.serialization.engines.TransactionalGraphEngine; diff --git a/aai-core/src/test/java/org/onap/aai/parsers/query/UniqueRelationshipQueryTest.java b/aai-core/src/test/java/org/onap/aai/parsers/query/UniqueRelationshipQueryTest.java index 68fc4376..a2f04c76 100644 --- a/aai-core/src/test/java/org/onap/aai/parsers/query/UniqueRelationshipQueryTest.java +++ b/aai-core/src/test/java/org/onap/aai/parsers/query/UniqueRelationshipQueryTest.java @@ -40,7 +40,10 @@ import org.junit.Ignore; import org.junit.Test; import org.onap.aai.AAISetup; import org.onap.aai.exceptions.AAIException; -import org.onap.aai.introspection.*; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.IntrospectorFactory; +import org.onap.aai.introspection.LoaderFactory; +import org.onap.aai.introspection.ModelType; import org.onap.aai.nodes.NodeIngestor; import org.onap.aai.serialization.engines.JanusGraphDBEngine; import org.onap.aai.serialization.engines.QueryStyle; diff --git a/aai-core/src/test/java/org/onap/aai/parsers/uri/URIParserTest.java b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIParserTest.java index 74914cce..ebef3cc3 100644 --- a/aai-core/src/test/java/org/onap/aai/parsers/uri/URIParserTest.java +++ b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIParserTest.java @@ -23,20 +23,13 @@ package org.onap.aai.parsers.uri; import static org.hamcrest.Matchers.hasProperty; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import java.io.UnsupportedEncodingException; import java.net.URI; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; import javax.annotation.PostConstruct; import javax.ws.rs.core.MultivaluedHashMap; @@ -47,14 +40,12 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; -import org.mockito.InOrder; import org.onap.aai.AAISetup; import org.onap.aai.edges.enums.EdgeType; import org.onap.aai.exceptions.AAIException; import org.onap.aai.introspection.Introspector; import org.onap.aai.introspection.Loader; import org.onap.aai.introspection.ModelType; -import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; import org.onap.aai.setup.SchemaVersion; diff --git a/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToDBKeyTest.java b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToDBKeyTest.java index f9055b1d..4bac547d 100644 --- a/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToDBKeyTest.java +++ b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToDBKeyTest.java @@ -36,7 +36,9 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.onap.aai.AAISetup; import org.onap.aai.exceptions.AAIException; -import org.onap.aai.introspection.*; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.LoaderFactory; +import org.onap.aai.introspection.ModelType; import org.onap.aai.parsers.exceptions.DoesNotStartWithValidNamespaceException; public class URIToDBKeyTest extends AAISetup { diff --git a/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToObjectTest.java b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToObjectTest.java index 52aa470d..2aad37a0 100644 --- a/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToObjectTest.java +++ b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToObjectTest.java @@ -38,7 +38,10 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.onap.aai.AAISetup; import org.onap.aai.exceptions.AAIException; -import org.onap.aai.introspection.*; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.LoaderFactory; +import org.onap.aai.introspection.ModelType; import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; import org.onap.aai.setup.SchemaVersion; import org.springframework.test.annotation.DirtiesContext; diff --git a/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToRelationshipObjectTest.java b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToRelationshipObjectTest.java index ee8cce21..f94d9241 100644 --- a/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToRelationshipObjectTest.java +++ b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToRelationshipObjectTest.java @@ -38,7 +38,10 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.onap.aai.AAISetup; import org.onap.aai.exceptions.AAIException; -import org.onap.aai.introspection.*; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.LoaderFactory; +import org.onap.aai.introspection.ModelType; import org.onap.aai.setup.SchemaVersion; import org.springframework.test.annotation.DirtiesContext; diff --git a/aai-core/src/test/java/org/onap/aai/prevalidation/ValidationServiceTest.java b/aai-core/src/test/java/org/onap/aai/prevalidation/ValidationServiceTest.java index 8ef1d706..db9ee961 100644 --- a/aai-core/src/test/java/org/onap/aai/prevalidation/ValidationServiceTest.java +++ b/aai-core/src/test/java/org/onap/aai/prevalidation/ValidationServiceTest.java @@ -24,9 +24,14 @@ import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; +import static org.mockito.ArgumentCaptor.forClass; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule; import com.google.gson.Gson; import java.io.IOException; @@ -38,10 +43,13 @@ import org.apache.http.conn.ConnectTimeoutException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.onap.aai.PayloadUtil; +import org.onap.aai.domain.notificationEvent.NotificationEvent; import org.onap.aai.exceptions.AAIException; import org.onap.aai.restclient.RestClient; +import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.boot.test.system.OutputCaptureRule; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; @@ -56,12 +64,15 @@ public class ValidationServiceTest { public OutputCaptureRule capture = new OutputCaptureRule(); private Gson gson; + private ObjectMapper mapper; @Before public void setUp() throws Exception { + mapper = new ObjectMapper(); + mapper.registerModule(new JaxbAnnotationModule()); gson = new Gson(); restClient = Mockito.mock(RestClient.class); - validationService = Mockito.spy(new ValidationService(restClient, "JUNIT", "generic-vnf", null)); + validationService = Mockito.spy(new ValidationService(restClient, "JUNIT", "generic-vnf", null, mapper)); } @Test @@ -81,14 +92,19 @@ public class ValidationServiceTest { throws IOException, AAIException { String pserverRequest = PayloadUtil.getResourcePayload("prevalidation/success-request-with-no-violations.json"); + NotificationEvent notificationEvent = mapper.readValue(pserverRequest, NotificationEvent.class); Mockito.when(restClient.execute(eq(ValidationService.VALIDATION_ENDPOINT), eq(HttpMethod.POST), any(), - eq(pserverRequest))).thenThrow(new RuntimeException(new ConnectException("Connection refused"))); + anyString())).thenThrow(new RuntimeException(new ConnectException("Connection refused"))); - validationService.preValidate(pserverRequest); + validationService.preValidate(notificationEvent); assertThat(capture.toString(), containsString("Connection refused to the validation microservice due to service unreachable")); + ArgumentCaptor<String> bodyCaptor = forClass(String.class); + verify(restClient).execute(eq(ValidationService.VALIDATION_ENDPOINT), eq(HttpMethod.POST), any(), bodyCaptor.capture()); + + JSONAssert.assertEquals(pserverRequest, bodyCaptor.getValue(), false); } @Test @@ -96,15 +112,20 @@ public class ValidationServiceTest { throws IOException, AAIException { String pserverRequest = PayloadUtil.getResourcePayload("prevalidation/success-request-with-no-violations.json"); + NotificationEvent notificationEvent = mapper.readValue(pserverRequest, NotificationEvent.class); Mockito.when(restClient.execute(eq(ValidationService.VALIDATION_ENDPOINT), eq(HttpMethod.POST), any(), - eq(pserverRequest))) + anyString())) .thenThrow(new RuntimeException(new ConnectTimeoutException("Connection timed out"))); - validationService.preValidate(pserverRequest); + validationService.preValidate(notificationEvent); assertThat(capture.toString(), containsString( "Connection timeout to the validation microservice as this could indicate the server is unable to reach port")); + ArgumentCaptor<String> bodyCaptor = forClass(String.class); + verify(restClient).execute(eq(ValidationService.VALIDATION_ENDPOINT), eq(HttpMethod.POST), any(), bodyCaptor.capture()); + + JSONAssert.assertEquals(pserverRequest, bodyCaptor.getValue(), false); } @Test @@ -112,22 +133,28 @@ public class ValidationServiceTest { throws IOException, AAIException { String pserverRequest = PayloadUtil.getResourcePayload("prevalidation/success-request-with-no-violations.json"); + NotificationEvent notificationEvent = mapper.readValue(pserverRequest, NotificationEvent.class); String validationResponse = PayloadUtil.getResourcePayload("prevalidation/success-response-with-empty-violations.json"); ResponseEntity responseEntity = Mockito.mock(ResponseEntity.class, Mockito.RETURNS_DEEP_STUBS); Mockito.when(restClient.execute(eq(ValidationService.VALIDATION_ENDPOINT), eq(HttpMethod.POST), any(), - eq(pserverRequest))).thenReturn(responseEntity); + anyString())).thenReturn(responseEntity); Mockito.when(responseEntity.getStatusCodeValue()).thenReturn(200); Mockito.when(responseEntity.getBody()).thenReturn(validationResponse); Mockito.doReturn(true).when(validationService).isSuccess(responseEntity); - List<String> errorMessages = validationService.preValidate(pserverRequest); + List<String> errorMessages = validationService.preValidate(notificationEvent); assertNotNull("Expected the error messages to be not null", errorMessages); assertThat(errorMessages.size(), is(0)); + + ArgumentCaptor<String> bodyCaptor = forClass(String.class); + verify(restClient).execute(eq(ValidationService.VALIDATION_ENDPOINT), eq(HttpMethod.POST), any(), bodyCaptor.capture()); + + JSONAssert.assertEquals(pserverRequest, bodyCaptor.getValue(), false); } @Test @@ -135,16 +162,21 @@ public class ValidationServiceTest { throws IOException, AAIException { String pserverRequest = PayloadUtil.getResourcePayload("prevalidation/success-request-with-no-violations.json"); + NotificationEvent notificationEvent = mapper.readValue(pserverRequest, NotificationEvent.class); Mockito.when(restClient.execute(eq(ValidationService.VALIDATION_ENDPOINT), eq(HttpMethod.POST), any(), - eq(pserverRequest))) + anyString())) .thenThrow(new RuntimeException( new SocketTimeoutException("Request timed out due to taking longer than client expected"))); - validationService.preValidate(pserverRequest); + validationService.preValidate(notificationEvent); assertThat(capture.toString(), containsString("Request to validation service took longer than the currently set timeout")); + ArgumentCaptor<String> bodyCaptor = forClass(String.class); + verify(restClient).execute(eq(ValidationService.VALIDATION_ENDPOINT), eq(HttpMethod.POST), any(), bodyCaptor.capture()); + + JSONAssert.assertEquals(pserverRequest, bodyCaptor.getValue(), false); } @Test diff --git a/aai-core/src/test/java/org/onap/aai/query/builder/QueryBuilderTestAbstraction.java b/aai-core/src/test/java/org/onap/aai/query/builder/QueryBuilderTestAbstraction.java index 6d10115a..7685360b 100644 --- a/aai-core/src/test/java/org/onap/aai/query/builder/QueryBuilderTestAbstraction.java +++ b/aai-core/src/test/java/org/onap/aai/query/builder/QueryBuilderTestAbstraction.java @@ -42,6 +42,7 @@ import org.junit.*; import org.junit.runner.RunWith; import org.onap.aai.config.ConfigConfiguration; import org.onap.aai.config.IntrospectionConfig; +import org.onap.aai.config.KafkaConfig; import org.onap.aai.config.SpringContextAware; import org.onap.aai.config.XmlFormatTransformerConfiguration; import org.onap.aai.db.props.AAIProperties; @@ -52,6 +53,7 @@ import org.onap.aai.introspection.Loader; import org.onap.aai.introspection.LoaderFactory; import org.onap.aai.introspection.ModelType; import org.onap.aai.nodes.NodeIngestor; +import org.onap.aai.rest.notification.NotificationService; import org.onap.aai.serialization.db.EdgeSerializer; import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException; import org.onap.aai.serialization.queryformats.QueryFormatTestHelper; @@ -67,11 +69,12 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ContextConfiguration( classes = {ConfigConfiguration.class, QueryTestsConfigTranslator.class, NodeIngestor.class, EdgeIngestor.class, EdgeSerializer.class, SpringContextAware.class, IntrospectionConfig.class, - XmlFormatTransformerConfiguration.class}) + XmlFormatTransformerConfiguration.class, LoaderFactory.class, NotificationService.class, KafkaConfig.class}) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) @TestPropertySource( properties = {"schema.translator.list = config", "schema.nodes.location=src/test/resources/onap/oxm", - "schema.edges.location=src/test/resources/onap/dbedgerules"}) + "schema.edges.location=src/test/resources/onap/dbedgerules", + "aai.notifications.enabled=false"}) public abstract class QueryBuilderTestAbstraction { protected Loader loader; diff --git a/aai-core/src/test/java/org/onap/aai/rest/ImpliedDeleteIntegrationTest.java b/aai-core/src/test/java/org/onap/aai/rest/ImpliedDeleteIntegrationTest.java index e6664e1a..38731288 100644 --- a/aai-core/src/test/java/org/onap/aai/rest/ImpliedDeleteIntegrationTest.java +++ b/aai-core/src/test/java/org/onap/aai/rest/ImpliedDeleteIntegrationTest.java @@ -45,9 +45,10 @@ import org.onap.aai.HttpTestUtil; import org.onap.aai.PayloadUtil; import org.onap.aai.db.props.AAIProperties; import org.onap.aai.dbmap.AAIGraph; +import org.onap.aai.domain.notificationEvent.NotificationEvent; +import org.onap.aai.domain.notificationEvent.NotificationEvent.EventHeader; import org.onap.aai.introspection.ModelType; -import org.onap.aai.rest.ueb.NotificationEvent; -import org.onap.aai.rest.ueb.UEBNotification; +import org.onap.aai.rest.notification.UEBNotification; import org.onap.aai.serialization.engines.QueryStyle; import org.skyscreamer.jsonassert.JSONAssert; import org.slf4j.Logger; @@ -73,7 +74,7 @@ public class ImpliedDeleteIntegrationTest extends AAISetup { String uri = "/aai/v12/cloud-infrastructure/pservers/pserver/test-pserver-implied-delete"; - UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions)); HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MINIMUM_DEPTH); String resource = PayloadUtil.getResourcePayload("pserver-implied-delete.json"); @@ -91,7 +92,7 @@ public class ImpliedDeleteIntegrationTest extends AAISetup { JSONAssert.assertEquals(resource, response.getEntity().toString(), false); jsonObject.getJSONObject("p-interfaces").remove("p-interface"); - notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions)); httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MINIMUM_DEPTH); response = httpTestUtil.doPut(uri, jsonObject.toString()); @@ -100,10 +101,11 @@ public class ImpliedDeleteIntegrationTest extends AAISetup { List<NotificationEvent> notificationEvents = notification.getEvents(); assertThat(notificationEvents.size(), is(5)); - List<String> notificationEventHeaders = notification.getEvents().stream() - .map(event -> event.getEventHeader().marshal(false)).collect(Collectors.toList()); + List<EventHeader> notificationEventHeaders = notification.getEvents().stream() + .map(NotificationEvent::getEventHeader) + .collect(Collectors.toList()); - Long deletedEventsCount = notificationEventHeaders.stream().filter(e -> e.contains("\"DELETE\"")).count(); + Long deletedEventsCount = notificationEventHeaders.stream().filter(e -> "DELETE".equals(e.getAction())).count(); assertThat(deletedEventsCount, is(4L)); diff --git a/aai-core/src/test/java/org/onap/aai/rest/NotificationDmaapEventTest.java b/aai-core/src/test/java/org/onap/aai/rest/NotificationDmaapEventTest.java index 399ef7e0..0eafdf1c 100644 --- a/aai-core/src/test/java/org/onap/aai/rest/NotificationDmaapEventTest.java +++ b/aai-core/src/test/java/org/onap/aai/rest/NotificationDmaapEventTest.java @@ -26,6 +26,7 @@ import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.junit.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.JsonObject; import com.google.gson.JsonParser; @@ -55,24 +56,29 @@ import org.onap.aai.HttpTestUtil; import org.onap.aai.PayloadUtil; import org.onap.aai.db.props.AAIProperties; import org.onap.aai.dbmap.AAIGraph; +import org.onap.aai.domain.notificationEvent.NotificationEvent; +import org.onap.aai.domain.notificationEvent.NotificationEvent.EventHeader; import org.onap.aai.exceptions.AAIException; import org.onap.aai.introspection.ModelType; -import org.onap.aai.rest.ueb.NotificationEvent; -import org.onap.aai.rest.ueb.UEBNotification; +import org.onap.aai.rest.notification.UEBNotification; import org.onap.aai.serialization.engines.QueryStyle; import org.skyscreamer.jsonassert.JSONAssert; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; @RunWith(value = Parameterized.class) @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) public class NotificationDmaapEventTest extends AAISetup { +// ObjectMapper mapper = new ObjectMapper(); + @Autowired private ObjectMapper mapper; + @Parameterized.Parameter public QueryStyle queryStyle; @Parameterized.Parameters(name = "QueryStyle.{0}") public static Collection<Object[]> data() { - return Arrays.asList(new Object[][] {{QueryStyle.TRAVERSAL}, {QueryStyle.TRAVERSAL_URI}}); + return Arrays.asList(new Object[][] {{QueryStyle.TRAVERSAL}}); } @Test @@ -80,7 +86,7 @@ public class NotificationDmaapEventTest extends AAISetup { throws IOException, AAIException { String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598"; - UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions)); HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MINIMUM_DEPTH); String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); @@ -97,13 +103,8 @@ public class NotificationDmaapEventTest extends AAISetup { // Verify all the events are create since its a new PUT notification.getEvents().forEach((event) -> { - - String header = event.getEventHeader().marshal(false); - - assertThat(event.getEventHeader().marshal(false), containsString("\"CREATE\"")); - - assertThat(header, containsString("\"top-entity-type\":\"pserver\"")); - + assertEquals("CREATE", event.getEventHeader().getAction()); + assertEquals("pserver", event.getEventHeader().getTopEntityType()); }); response = httpTestUtil.doGet(uri); @@ -116,7 +117,7 @@ public class NotificationDmaapEventTest extends AAISetup { throws IOException, AAIException { String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598"; - UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions)); HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); String pserverResource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); @@ -147,19 +148,20 @@ public class NotificationDmaapEventTest extends AAISetup { List<NotificationEvent> events = notification.getEvents(); assertThat(events.size(), is(2)); - String notificationEventHeader = events.get(1).getEventHeader().marshal(false); - String notificationEventBody = events.get(1).getObj().marshal(false); + EventHeader notificationEventHeader = events.get(1).getEventHeader(); + String notificationEventBody = events.get(1).getEntity().toString(); - assertThat(notificationEventHeader, containsString("\"action\":\"CREATE\"")); - assertThat(notificationEventHeader, containsString("\"entity-type\":\"p-interface\"")); - assertThat(notificationEventHeader, containsString("\"top-entity-type\":\"pserver\"")); + assertEquals("CREATE", notificationEventHeader.getAction()); + assertEquals("p-interface", notificationEventHeader.getEntityType()); + assertEquals("pserver", notificationEventHeader.getTopEntityType()); String expectedNotificationHeader = PayloadUtil.getResourcePayload( "notification-dmaap-events/depth-zero/expected-notification-header-create-child-on-existing-obj.json"); String expectedNotificationBody = PayloadUtil.getResourcePayload( "notification-dmaap-events/depth-zero/expected-notification-body-create-child-on-existing-obj.json"); - JSONAssert.assertEquals(expectedNotificationHeader, notificationEventHeader, false); + String eventHeaderJson = mapper.writeValueAsString(events.get(1).getEventHeader()); + JSONAssert.assertEquals(expectedNotificationHeader, eventHeaderJson, false); JSONAssert.assertEquals(expectedNotificationBody, notificationEventBody, false); } @@ -168,7 +170,7 @@ public class NotificationDmaapEventTest extends AAISetup { throws IOException, AAIException { String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598"; - UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions)); HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); String pserverResource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); @@ -200,19 +202,19 @@ public class NotificationDmaapEventTest extends AAISetup { List<NotificationEvent> events = notification.getEvents(); assertThat(events.size(), is(1)); - String notificationEventHeader = events.get(0).getEventHeader().marshal(false); - String notificationEventBody = events.get(0).getObj().marshal(false); - - assertThat(notificationEventHeader, containsString("\"action\":\"UPDATE\"")); - assertThat(notificationEventHeader, containsString("\"entity-type\":\"pserver\"")); - assertThat(notificationEventHeader, containsString("\"top-entity-type\":\"pserver\"")); + EventHeader notificationEventHeader = events.get(0).getEventHeader(); + String notificationEventBody = events.get(0).getEntity().toString(); + assertEquals("UPDATE", notificationEventHeader.getAction()); + assertEquals("pserver", notificationEventHeader.getEntityType()); + assertEquals("pserver", notificationEventHeader.getTopEntityType()); String expectedNotificationHeader = PayloadUtil.getResourcePayload( "notification-dmaap-events/depth-all/expected-notification-header-create-child-on-existing-obj.json"); String expectedNotificationBody = PayloadUtil.getResourcePayload( "notification-dmaap-events/depth-all/expected-notification-body-create-child-on-existing-obj.json"); - JSONAssert.assertEquals(expectedNotificationHeader, notificationEventHeader, false); + String eventHeaderJson = mapper.writeValueAsString(events.get(0).getEventHeader()); + JSONAssert.assertEquals(expectedNotificationHeader, eventHeaderJson, false); JSONAssert.assertEquals(expectedNotificationBody, notificationEventBody, false); response = httpTestUtil.doGet(uri, "0"); @@ -235,7 +237,7 @@ public class NotificationDmaapEventTest extends AAISetup { String cloudRegionUri = "/aai/v14/cloud-infrastructure/cloud-regions/cloud-region/random-cloud-region-owner/random-cloud-region-id"; - UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions)); HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MINIMUM_DEPTH); Map<String, String> uriPayload = new LinkedHashMap<>(); @@ -252,8 +254,7 @@ public class NotificationDmaapEventTest extends AAISetup { assertThat("Expecting the number of dmaap events to be 2", numberOfEventsActual, is(expectedEvents)); notification.getEvents().forEach((event) -> { - String notificationEventHeader = event.getEventHeader().marshal(false); - assertThat(notificationEventHeader, containsString("\"CREATE\"")); + assertEquals("CREATE", event.getEventHeader().getAction()); }); } @@ -265,7 +266,7 @@ public class NotificationDmaapEventTest extends AAISetup { String cloudRegionUri = "/aai/v14/cloud-infrastructure/cloud-regions/cloud-region/random-cloud-region-owner/random-cloud-region-id"; - UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions)); HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MAXIMUM_DEPTH); Map<String, String> uriPayload = new LinkedHashMap<>(); @@ -282,8 +283,7 @@ public class NotificationDmaapEventTest extends AAISetup { assertThat("Expecting the number of dmaap events to be 2", numberOfEventsActual, is(expectedEvents)); notification.getEvents().forEach((event) -> { - String notificationEventHeader = event.getEventHeader().marshal(false); - assertThat(notificationEventHeader, containsString("\"CREATE\"")); + assertEquals("CREATE", event.getEventHeader().getAction()); }); } @@ -291,7 +291,7 @@ public class NotificationDmaapEventTest extends AAISetup { public void testDeleteOnExistingPserverAndCheckIfNotificationDepthIsZeroThatAllEventsHaveDeleteAndThatDepthIsZeroOnEachNotificationEvent() throws IOException, AAIException { String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598"; - UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions)); HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); String pserverResource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); @@ -316,19 +316,16 @@ public class NotificationDmaapEventTest extends AAISetup { assertThat(notificationEvents.size(), is(17)); notificationEvents.forEach((event) -> { - - String header = event.getEventHeader().marshal(false); - - assertThat(event.getEventHeader().marshal(false), containsString("\"DELETE\"")); - - assertThat(header, containsString("\"top-entity-type\":\"pserver\"")); + EventHeader header = event.getEventHeader(); + assertEquals("DELETE", header.getAction()); + assertEquals("pserver", header.getTopEntityType()); }); } @Test public void testDeleteOnExistingResourceVersionMismatchNoEventGenerated() throws IOException, AAIException { String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598"; - UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions)); HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); String pserverResource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); @@ -362,7 +359,7 @@ public class NotificationDmaapEventTest extends AAISetup { throws IOException, AAIException { String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598"; - UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions)); HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MAXIMUM_DEPTH); String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); @@ -378,20 +375,16 @@ public class NotificationDmaapEventTest extends AAISetup { NotificationEvent notificationEvent = notification.getEvents().get(0); // Verify all the events are create since its a new PUT - String header = notificationEvent.getEventHeader().marshal(false); - - assertThat(header, containsString("\"CREATE\"")); - - assertThat(header, containsString("\"entity-type\":\"pserver\"")); - - assertThat(header, containsString("\"top-entity-type\":\"pserver\"")); - - assertThat(header, containsString("\"entity-link\":\"" + uri + "\"")); + EventHeader eventHeader = notificationEvent.getEventHeader(); + assertEquals("CREATE", eventHeader.getAction()); + assertEquals("pserver", eventHeader.getEntityType()); + assertEquals("pserver", eventHeader.getTopEntityType()); + assertEquals(uri, eventHeader.getEntityLink()); response = httpTestUtil.doGet(uri); assertEquals("Expecting the pserver to be found", 200, response.getStatus()); - JSONAssert.assertEquals(response.getEntity().toString(), notificationEvent.getObj().marshal(false), false); + JSONAssert.assertEquals(response.getEntity().toString(), notificationEvent.getEntity().toString(), false); } @Test @@ -399,7 +392,7 @@ public class NotificationDmaapEventTest extends AAISetup { throws IOException, AAIException { String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598"; - UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions)); HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); @@ -424,7 +417,7 @@ public class NotificationDmaapEventTest extends AAISetup { assertThat(response.getEntity().toString(), containsString("new-equip-patch-type")); assertThat(notification.getEvents().size(), is(1)); - String updateNotificationEvent = notification.getEvents().get(0).getObj().marshal(true); + String updateNotificationEvent = notification.getEvents().get(0).getEntity().toString(); // Check that everything in notification event is also response body // Not comparing the other way as notification only includes parents main properties @@ -436,7 +429,7 @@ public class NotificationDmaapEventTest extends AAISetup { throws IOException, AAIException { String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598"; - UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions)); HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); @@ -461,7 +454,7 @@ public class NotificationDmaapEventTest extends AAISetup { assertThat(response.getEntity().toString(), containsString("new-equip-patch-type")); assertThat(notification.getEvents().size(), is(1)); - String updateNotificationEvent = notification.getEvents().get(0).getObj().marshal(true); + String updateNotificationEvent = notification.getEvents().get(0).getEntity().toString(); // Check that everything in notification event is also response body // Not comparing the other way as notification only includes parents main properties @@ -476,7 +469,7 @@ public class NotificationDmaapEventTest extends AAISetup { throws IOException, AAIException { String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598"; - UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions)); HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); @@ -506,7 +499,7 @@ public class NotificationDmaapEventTest extends AAISetup { assertThat(response.getEntity().toString(), containsString("new-equipment-identifier")); assertThat(notification.getEvents().size(), is(1)); - String updateNotificationEvent = notification.getEvents().get(0).getObj().marshal(true); + String updateNotificationEvent = notification.getEvents().get(0).getEntity().toString(); // Check that everything in notification event is also response body // Not comparing the other way as notification only includes parents main properties @@ -520,7 +513,7 @@ public class NotificationDmaapEventTest extends AAISetup { throws IOException, AAIException { String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598"; - UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions)); HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); @@ -547,7 +540,7 @@ public class NotificationDmaapEventTest extends AAISetup { response = httpTestUtil.doGet(uri); assertThat(notification.getEvents().size(), is(1)); - String updateNotificationEvent = notification.getEvents().get(0).getObj().marshal(true); + String updateNotificationEvent = notification.getEvents().get(0).getEntity().toString(); System.out.println("Update notification " + updateNotificationEvent); // Check that everything in notification event is also response body @@ -564,7 +557,7 @@ public class NotificationDmaapEventTest extends AAISetup { String pserverUri = "/aai/v14/cloud-infrastructure/pservers/pserver/" + hostname; String genericVnfUri = "/aai/v14/network/generic-vnfs/generic-vnf/generic-vnf-notification"; - UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions)); HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); @@ -604,9 +597,9 @@ public class NotificationDmaapEventTest extends AAISetup { String expectedNotificationBody = PayloadUtil.getResourcePayload( "notification-dmaap-events/depth-zero/expected-notification-body-create-edge-between-pserver-and-generic-vnf.json"); - JSONAssert.assertEquals(expectedNotificationHeader, notificationEvents.get(0).getEventHeader().marshal(false), + JSONAssert.assertEquals(expectedNotificationHeader, mapper.writeValueAsString(notificationEvents.get(0).getEventHeader()), false); - JSONAssert.assertEquals(expectedNotificationBody, notificationEvents.get(0).getObj().marshal(false), false); + JSONAssert.assertEquals(expectedNotificationBody, notificationEvents.get(0).getEntity().toString(), false); response = httpTestUtil.doGet(genericVnfUri); @@ -623,7 +616,7 @@ public class NotificationDmaapEventTest extends AAISetup { String pserverUri = "/aai/v14/cloud-infrastructure/pservers/pserver/" + hostname; String genericVnfUri = "/aai/v14/network/generic-vnfs/generic-vnf/generic-vnf-notification"; - UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions)); HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); @@ -663,10 +656,10 @@ public class NotificationDmaapEventTest extends AAISetup { String expectedNotificationBody = PayloadUtil.getResourcePayload( "notification-dmaap-events/depth-all/expected-notification-body-create-edge-between-pserver-and-generic-vnf.json"); - System.out.println("Notification Body: " + notificationEvents.get(0).getObj().marshal(false)); - JSONAssert.assertEquals(expectedNotificationHeader, notificationEvents.get(0).getEventHeader().marshal(false), + System.out.println("Notification Body: " + notificationEvents.get(0).getEntity().toString()); + JSONAssert.assertEquals(expectedNotificationHeader, mapper.writeValueAsString(notificationEvents.get(0).getEventHeader()), false); - JSONAssert.assertEquals(expectedNotificationBody, notificationEvents.get(0).getObj().marshal(false), false); + JSONAssert.assertEquals(expectedNotificationBody, notificationEvents.get(0).getEntity().toString(), false); response = httpTestUtil.doGet(genericVnfUri); @@ -685,7 +678,7 @@ public class NotificationDmaapEventTest extends AAISetup { String relationship = PayloadUtil.getResourcePayload("pserver-to-gvnf-relationship-notification.json"); - UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions)); HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); @@ -741,9 +734,9 @@ public class NotificationDmaapEventTest extends AAISetup { String expectedNotificationBody = PayloadUtil.getResourcePayload( "notification-dmaap-events/depth-zero/expected-notification-body-delete-edge-between-pserver-and-generic-vnf.json"); - JSONAssert.assertEquals(expectedNotificationHeader, notificationEvents.get(0).getEventHeader().marshal(false), + JSONAssert.assertEquals(expectedNotificationHeader, mapper.writeValueAsString(notificationEvents.get(0).getEventHeader()), false); - JSONAssert.assertEquals(expectedNotificationBody, notificationEvents.get(0).getObj().marshal(false), false); + JSONAssert.assertEquals(expectedNotificationBody, notificationEvents.get(0).getEntity().toString(), false); } @@ -758,7 +751,7 @@ public class NotificationDmaapEventTest extends AAISetup { String relationship = PayloadUtil.getResourcePayload("pserver-to-gvnf-relationship-notification.json"); - UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions)); HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); @@ -813,9 +806,9 @@ public class NotificationDmaapEventTest extends AAISetup { String expectedNotificationBody = PayloadUtil.getResourcePayload( "notification-dmaap-events/depth-all/expected-notification-body-delete-edge-between-pserver-and-generic-vnf.json"); - JSONAssert.assertEquals(expectedNotificationHeader, notificationEvents.get(0).getEventHeader().marshal(false), + JSONAssert.assertEquals(expectedNotificationHeader, mapper.writeValueAsString(notificationEvents.get(0).getEventHeader()), false); - JSONAssert.assertEquals(expectedNotificationBody, notificationEvents.get(0).getObj().marshal(false), false); + JSONAssert.assertEquals(expectedNotificationBody, notificationEvents.get(0).getEntity().toString(), false); } @@ -823,7 +816,7 @@ public class NotificationDmaapEventTest extends AAISetup { public void testDeleteOnExistingResourceVersionMismatchNoEventGeneratedFullDepth() throws IOException, AAIException { String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598"; - UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions)); HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); String pserverResource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); @@ -851,7 +844,7 @@ public class NotificationDmaapEventTest extends AAISetup { @Test public void testCreateVnfWithChildrenCreateCustomerWithChildrenAndCousinBetweenVlanAndServiceInstanceThenDeleteCustomerVerifyingVlanRV() throws IOException, AAIException { - UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions)); HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); String json = PayloadUtil.getResourcePayload( @@ -912,7 +905,7 @@ public class NotificationDmaapEventTest extends AAISetup { @Test public void testBulkCreateOfComplexAndPserverWithRelationshipThenBulkDeleteBoth() throws IOException, AAIException { - UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions)); HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MAXIMUM_DEPTH); JsonObject payloads = JsonParser @@ -945,7 +938,7 @@ public class NotificationDmaapEventTest extends AAISetup { Map<String, Pair<String, String>> deletes = new LinkedHashMap<>(); deletes.put(pserverUri, new Pair<>(pserverRv, null)); deletes.put(complexUri, new Pair<>(complexRV, null)); - notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions)); httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MAXIMUM_DEPTH); httpTestUtil.doDelete(deletes); @@ -958,7 +951,7 @@ public class NotificationDmaapEventTest extends AAISetup { @Test public void testCreateVnfWithChildrenCreateCustomerWithChildrenAndCousinBetweenVlanAndServiceInstanceThenImplicitDeleteVlanVerifyingServiceInstanceRV() throws IOException, AAIException { - UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + UEBNotification notification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions)); HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); String json = PayloadUtil.getResourcePayload( diff --git a/aai-core/src/test/java/org/onap/aai/rest/RestHandlerTest.java b/aai-core/src/test/java/org/onap/aai/rest/RestHandlerTest.java index 494d7e4e..b408940e 100644 --- a/aai-core/src/test/java/org/onap/aai/rest/RestHandlerTest.java +++ b/aai-core/src/test/java/org/onap/aai/rest/RestHandlerTest.java @@ -22,7 +22,8 @@ package org.onap.aai.rest; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; import org.junit.Test; diff --git a/aai-core/src/test/java/org/onap/aai/rest/db/HttpEntryNotificationIntegrationTest.java b/aai-core/src/test/java/org/onap/aai/rest/db/HttpEntryNotificationIntegrationTest.java new file mode 100644 index 00000000..6b90782c --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/rest/db/HttpEntryNotificationIntegrationTest.java @@ -0,0 +1,207 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2024 Deutsche Telekom. 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.aai.rest.db; + +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.when; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.UUID; + +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriInfo; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.javatuples.Pair; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.aai.AAISetup; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.ModelType; +import org.onap.aai.parsers.query.QueryParser; +import org.onap.aai.query.builder.QueryOptions; +import org.onap.aai.rest.notification.UEBNotification; +import org.onap.aai.restcore.HttpMethod; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; +import org.springframework.test.annotation.DirtiesContext; + +@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) +public class HttpEntryNotificationIntegrationTest extends AAISetup { + + private static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json"); + private Loader loader; + private TransactionalGraphEngine dbEngine; + private GraphTraversalSource traversal; + private HttpHeaders httpHeaders; + private UriInfo uriInfo; + private MultivaluedMap<String, String> headersMultiMap; + private MultivaluedMap<String, String> queryParameters; + private List<String> aaiRequestContextList; + private List<MediaType> outputMediaTypes; + + @Before + public void setup() { + + httpHeaders = Mockito.mock(HttpHeaders.class); + uriInfo = Mockito.mock(UriInfo.class); + + headersMultiMap = new MultivaluedHashMap<>(); + queryParameters = Mockito.spy(new MultivaluedHashMap<>()); + + headersMultiMap.add("X-FromAppId", "JUNIT"); + headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString()); + headersMultiMap.add("Real-Time", "true"); + headersMultiMap.add("Accept", "application/json"); + headersMultiMap.add("aai-request-context", ""); + + outputMediaTypes = new ArrayList<>(); + outputMediaTypes.add(APPLICATION_JSON); + + aaiRequestContextList = new ArrayList<>(); + aaiRequestContextList.add(""); + + traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion()); + loader = traversalHttpEntry.getLoader(); + dbEngine = traversalHttpEntry.getDbEngine(); + traversal = dbEngine.tx().traversal(); + + when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes); + when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap); + + when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList); + + when(uriInfo.getQueryParameters()).thenReturn(queryParameters); + when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters); + + // TODO - Check if this is valid since RemoveDME2QueryParameters seems to be + // very unreasonable + Mockito.doReturn(null).when(queryParameters).remove(any()); + + when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON); + } + + @After + public void rollback() { + dbEngine.rollback(); + } + + @Test + public void notificationOnRelatedToTest() throws UnsupportedEncodingException, AAIException { + + Loader ld = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion()); + UEBNotification uebNotification = Mockito.spy(new UEBNotification(loaderFactory, schemaVersions)); + traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), uebNotification); + + Loader loader = traversalHttpEntry.getLoader(); + TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine(); + // Put pserver + String uri = "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver"; + String content = "{\"hostname\":\"junit-edge-test-pserver\"}"; + doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, content); + // Put complex + uri = "/cloud-infrastructure/complexes/complex/junit-edge-test-complex"; + content = "{\"physical-location-id\":\"junit-edge-test-complex\",\"physical-location-type\":\"AAIDefault\",\"street1\":\"AAIDefault\",\"city\":\"AAIDefault\",\"state\":\"NJ\",\"postal-code\":\"07748\",\"country\":\"USA\",\"region\":\"US\"}"; + doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, content); + + // PutEdge + uri = "/cloud-infrastructure/complexes/complex/junit-edge-test-complex/relationship-list/relationship"; + content = "{\"related-to\":\"pserver\",\"related-link\":\"/aai/" + schemaVersions.getDefaultVersion().toString() + + "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver\",\"relationship-label\":\"org.onap.relationships.inventory.LocatedIn\"}"; + + Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT_EDGE, uri, + content); + + assertEquals("Expected the pserver relationship to be deleted", 200, response.getStatus()); + assertEquals("Two notifications", 2, uebNotification.getEvents().size()); + assertEquals("Notification generated for PUT edge", "UPDATE", + uebNotification.getEvents().get(1).getEventHeader().getAction()); + assertThat("Event body for the edge create has the related to", + uebNotification.getEvents().get(1).getEntity().toString(), + containsString("cloud-infrastructure/pservers/pserver/junit-edge-test-pserver")); + + response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.DELETE_EDGE, uri, content); + assertEquals("Expected the pserver relationship to be deleted", 204, response.getStatus()); + assertEquals("Two notifications", 2, uebNotification.getEvents().size()); + assertEquals("Notification generated for DELETE edge", "UPDATE", + uebNotification.getEvents().get(0).getEventHeader().getAction()); + assertThat("Event body for the edge delete does not have the related to", + uebNotification.getEvents().get(0).getEntity().toString(), + not(containsString("cloud-infrastructure/pservers/pserver/junit-edge-test-pserver"))); + dbEngine.rollback(); + + } + + private Response doRequest(HttpEntry httpEntry, Loader loader, TransactionalGraphEngine dbEngine, HttpMethod method, + String uri, String requestBody) throws UnsupportedEncodingException, AAIException { + return doRequest(httpEntry, loader, dbEngine, method, uri, requestBody, null); + } + + private Response doRequest(HttpEntry httpEntry, Loader loader, TransactionalGraphEngine dbEngine, HttpMethod method, + String uri, String requestBody, QueryOptions queryOptions) throws UnsupportedEncodingException, AAIException { + URI uriObject = UriBuilder.fromPath(uri).build(); + QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject); + String objType; + if (!uriQuery.getContainerType().equals("")) { + objType = uriQuery.getContainerType(); + } else { + objType = uriQuery.getResultType(); + } + if (uri.endsWith("relationship")) { + objType = "relationship"; + } + Introspector obj; + if (method.equals(HttpMethod.GET) || method.equals(HttpMethod.GET_RELATIONSHIP)) { + obj = loader.introspectorFromName(objType); + } else { + obj = loader.unmarshal(objType, requestBody, org.onap.aai.restcore.MediaType.getEnum("application/json")); + } + + DBRequest.Builder builder = new DBRequest.Builder(method, uriObject, uriQuery, obj, httpHeaders, uriInfo, + "JUNIT-TRANSACTION"); + DBRequest dbRequest = requestBody != null + ? builder.rawRequestContent(requestBody).build() + : builder.build(); + + List<DBRequest> dbRequestList = Collections.singletonList(dbRequest); + + Pair<Boolean, List<Pair<URI, Response>>> responsesTuple = httpEntry.process(dbRequestList, "JUNIT", + Collections.emptySet(), true, queryOptions); + return responsesTuple.getValue1().get(0).getValue1(); + } +} diff --git a/aai-core/src/test/java/org/onap/aai/rest/db/HttpEntryTest.java b/aai-core/src/test/java/org/onap/aai/rest/db/HttpEntryTest.java index 39539988..2578eef4 100644 --- a/aai-core/src/test/java/org/onap/aai/rest/db/HttpEntryTest.java +++ b/aai-core/src/test/java/org/onap/aai/rest/db/HttpEntryTest.java @@ -24,15 +24,14 @@ import static org.onap.aai.edges.enums.AAIDirection.NONE; import static org.hamcrest.Matchers.containsString; - import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertEquals; - import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; - import static org.mockito.Mockito.doNothing; - import static org.mockito.Mockito.times; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -40,8 +39,6 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; - import com.google.gson.JsonObject; - import com.google.gson.JsonParser; import java.io.UnsupportedEncodingException; import java.net.URI; @@ -69,7 +66,6 @@ import org.json.JSONArray; import org.json.JSONObject; import org.junit.After; - import org.junit.Assert; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; @@ -84,7 +80,6 @@ import org.onap.aai.exceptions.AAIException; import org.onap.aai.introspection.Introspector; import org.onap.aai.introspection.Loader; - import org.onap.aai.introspection.ModelType; import org.onap.aai.parsers.query.QueryParser; import org.onap.aai.prevalidation.ValidationService; import org.onap.aai.query.builder.Pageable; @@ -95,8 +90,8 @@ import org.onap.aai.rest.db.responses.Relationship; import org.onap.aai.rest.db.responses.RelationshipWrapper; import org.onap.aai.rest.db.responses.ServiceException; - import org.onap.aai.rest.ueb.UEBNotification; - import org.onap.aai.restcore.HttpMethod; +import org.onap.aai.rest.notification.NotificationService; +import org.onap.aai.restcore.HttpMethod; import org.onap.aai.serialization.engines.QueryStyle; import org.onap.aai.serialization.engines.TransactionalGraphEngine; import org.onap.aai.util.AAIConfig; @@ -110,6 +105,7 @@ public class HttpEntryTest extends AAISetup { @MockBean ValidationService validationService; + @MockBean NotificationService notificationService; protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json"); @@ -213,7 +209,7 @@ JSONAssert.assertEquals(expectedResponseBody, actualResponseBody, JSONCompareMode.NON_EXTENSIBLE); assertEquals("Expected the pserver to be returned", 200, response.getStatus()); - verify(validationService, times(1)).validate(any()); + verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any()); } @Test @@ -249,7 +245,7 @@ JSONAssert.assertEquals(expectedResponseBody, actualResponseBody, JSONCompareMode.NON_EXTENSIBLE); assertEquals("Expected the pservers to be returned", 200, response.getStatus()); - verify(validationService, times(1)).validate(any()); + verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any()); } @Test @@ -283,7 +279,7 @@ assertNull(response.getHeaderString("total-results")); assertEquals(1, actualResponseBody.getJSONArray("pserver").length()); assertEquals("Expected the pservers to be returned", 200, response.getStatus()); - verify(validationService, times(1)).validate(any()); + verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any()); queryOptions = QueryOptions.builder().pageable(new Pageable(0,5).includeTotalCount()).build(); response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri, queryOptions); @@ -307,6 +303,7 @@ assertTrue( response.getEntity().toString().contains("Node Not Found:No Node of type pserver found at: /cloud-infrastructure/pservers")); assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatus()); + verify(notificationService, never()).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any()); } @@ -344,7 +341,7 @@ assertEquals(2, Integer.parseInt(totalPages)); assertEquals(1, actualResponseBody.getJSONArray("pserver").length()); assertEquals("Expected the pservers to be returned", 200, response.getStatus()); - verify(validationService, times(1)).validate(any()); + verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any()); queryOptions = QueryOptions.builder().pageable(new Pageable(0, 2)).build(); response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri, queryOptions); @@ -392,7 +389,6 @@ actualResponseBody = new JSONObject(response.getEntity().toString()); assertEquals("theEquipType2", actualResponseBody.getJSONArray("pserver").getJSONObject(0).getString("equip-type")); assertEquals("theEquipType", actualResponseBody.getJSONArray("pserver").getJSONObject(1).getString("equip-type")); - } @Test @@ -401,6 +397,7 @@ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri); assertEquals("The pserver is not found", 404, response.getStatus()); + verify(notificationService, never()).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any()); } @Test @@ -410,7 +407,7 @@ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, requestBody); assertEquals("Expecting the pserver to be created", 201, response.getStatus()); - verify(validationService, times(1)).validate(any()); + verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any()); } @Test @@ -428,6 +425,7 @@ assertEquals( "Resource version specified on create:resource-version passed for create of /cloud-infrastructure/pservers/pserver/theHostname", errorResponseEntity.getRequestError().getServiceException().getVariables().get(2)); + verify(notificationService, never()).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any()); } @Test @@ -449,7 +447,7 @@ assertEquals("Expecting the pserver to be updated", 200, response.getStatus()); assertTrue("That old properties are removed", traversal.V().has("hostname", "updatedHostname").hasNot("number-of-cpus").hasNext()); - verify(validationService, times(1)).validate(any()); + verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any()); } @Test @@ -473,6 +471,7 @@ assertEquals( "Precondition Failed:resource-version MISMATCH for update of /cloud-infrastructure/pservers/pserver/updatedHostname", errorResponseEntity.getRequestError().getServiceException().getVariables().get(2)); + verify(notificationService, never()).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any()); } @Test @@ -518,7 +517,7 @@ traversal.V().has("aai-node-type", "p-interface").has("aai-uri", uri).has("interface-name", "p1") .out("tosca.relationships.network.BindsTo").has("aai-node-type", "pserver") .has("hostname", "hostname").hasNext()); - verify(validationService, times(1)).validate(any()); + verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any()); } @Test @@ -538,7 +537,7 @@ assertTrue("object should be updated while keeping old properties", traversal.V().has("aai-node-type", "pserver").has("hostname", "new-hostname") .has("equip-type", "the-equip-type").hasNext()); - verify(validationService, times(1)).validate(any()); + verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any()); } @Test @@ -555,7 +554,7 @@ doDelete(resourceVersion, uri, "pserver").getStatus()); assertTrue("Expecting the pserver to be deleted", !traversal.V().has("aai-node-type", "pserver").has("hostname", "the-hostname").hasNext()); - verify(validationService, times(1)).validate(any()); + verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any()); } @Test @@ -605,7 +604,7 @@ .has(EdgeProperty.PREVENT_DELETE.toString(), "IN"); assertTrue("p-server has incoming edge from complex", vertexQuery.hasNext()); assertTrue("Created Edge has expected properties", edgeQuery.hasNext()); - verify(validationService, times(1)).validate(any()); + verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any()); } @Test @@ -724,7 +723,7 @@ assertEquals("Expected get to succeed", 200, response.getStatus()); assertThat(responseEntity, containsString("/cloud-infrastructure/pservers/pserver/pserver-1")); assertThat(responseEntity, containsString("/cloud-infrastructure/pservers/pserver/pserver-2")); - verify(validationService, times(1)).validate(any()); + verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any()); } @Test @@ -759,7 +758,7 @@ assertEquals("Expected the response to be successful", 200, response.getStatus()); assertThat("Related pserver is returned", response.getEntity().toString(), containsString("\"hostname\":\"related-to-pserver\"")); - verify(validationService, times(1)).validate(any()); + verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any()); } @@ -788,7 +787,7 @@ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri); assertThat("Related to pserver is returned.", response.getEntity().toString(), containsString("\"hostname\":\"abstract-pserver\"")); - verify(validationService, times(1)).validate(any()); + verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any()); } @Test @@ -833,7 +832,7 @@ relationships[0].getRelatedLink()); assertEquals("complex.physical-location-id", relationships[0].getRelationshipData()[0].getRelationshipKey()); assertEquals("related-to-complex", relationships[0].getRelationshipData()[0].getRelationshipValue()); - verify(validationService, times(1)).validate(any()); + verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any()); } @Test @@ -891,53 +890,7 @@ JSONAssert.assertEquals(expectedResponseBody, actualResponseBody, JSONCompareMode.NON_EXTENSIBLE); queryParameters.remove("format"); - verify(validationService, times(1)).validate(any()); - } - - @Test - public void notificationOnRelatedToTest() throws UnsupportedEncodingException, AAIException { - - Loader ld = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion()); - UEBNotification uebNotification = Mockito.spy(new UEBNotification(ld, loaderFactory, schemaVersions)); - traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), uebNotification); - - Loader loader = traversalHttpEntry.getLoader(); - TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine(); - // Put pserver - String uri = "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver"; - String content = "{\"hostname\":\"junit-edge-test-pserver\"}"; - doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, content); - // Put complex - uri = "/cloud-infrastructure/complexes/complex/junit-edge-test-complex"; - content = "{\"physical-location-id\":\"junit-edge-test-complex\",\"physical-location-type\":\"AAIDefault\",\"street1\":\"AAIDefault\",\"city\":\"AAIDefault\",\"state\":\"NJ\",\"postal-code\":\"07748\",\"country\":\"USA\",\"region\":\"US\"}"; - doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, content); - - // PutEdge - uri = "/cloud-infrastructure/complexes/complex/junit-edge-test-complex/relationship-list/relationship"; - content = "{\"related-to\":\"pserver\",\"related-link\":\"/aai/" + schemaVersions.getDefaultVersion().toString() - + "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver\",\"relationship-label\":\"org.onap.relationships.inventory.LocatedIn\"}"; - - doNothing().when(uebNotification).triggerEvents(); - Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT_EDGE, uri, content); - - assertEquals("Expected the pserver relationship to be deleted", 200, response.getStatus()); - assertEquals("Two notifications", 2, uebNotification.getEvents().size()); - assertEquals("Notification generated for PUT edge", "UPDATE", - uebNotification.getEvents().get(0).getEventHeader().getValue("action").toString()); - assertThat("Event body for the edge create has the related to", - uebNotification.getEvents().get(0).getObj().marshal(false), - containsString("cloud-infrastructure/pservers/pserver/junit-edge-test-pserver")); - - response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.DELETE_EDGE, uri, content); - assertEquals("Expected the pserver relationship to be deleted", 204, response.getStatus()); - assertEquals("Two notifications", 2, uebNotification.getEvents().size()); - assertEquals("Notification generated for DELETE edge", "UPDATE", - uebNotification.getEvents().get(0).getEventHeader().getValue("action").toString()); - assertThat("Event body for the edge delete does not have the related to", - uebNotification.getEvents().get(0).getObj().marshal(false), - not(containsString("cloud-infrastructure/pservers/pserver/junit-edge-test-pserver"))); - dbEngine.rollback(); - + verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any()); } private Response doRequest(HttpEntry httpEntry, Loader loader, TransactionalGraphEngine dbEngine, HttpMethod method, @@ -1035,6 +988,6 @@ JSONAssert.assertEquals(expectedResponseBody, actualResponseBody, JSONCompareMode.NON_EXTENSIBLE); assertEquals("Expected the pserver to be returned", 200, response.getStatus()); - verify(validationService, times(1)).validate(any()); + verify(notificationService, times(1)).generateEvents(any(), anyInt(), any(), any(), any(), any(), any(), any()); } } diff --git a/aai-core/src/test/java/org/onap/aai/rest/db/HttpEntryTransactionTest.java b/aai-core/src/test/java/org/onap/aai/rest/db/HttpEntryTransactionTest.java new file mode 100644 index 00000000..0c2b22ea --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/rest/db/HttpEntryTransactionTest.java @@ -0,0 +1,126 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2024 Deutsche Telekom. 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.aai.rest.db; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriInfo; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.janusgraph.core.JanusGraphException; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.onap.aai.AAISetup; +import org.onap.aai.config.SpringContextAware; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.parsers.query.QueryParser; +import org.onap.aai.restcore.HttpMethod; +import org.onap.aai.restcore.MediaType; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; + +import lombok.SneakyThrows; + +public class HttpEntryTransactionTest extends AAISetup { + + @Mock UriInfo uriInfoMock; + @Mock MultivaluedMap<String, String> queryParamsMock; + @Mock HttpHeaders headersMock; + + @Before + public void setup() { + when(uriInfoMock.getQueryParameters(anyBoolean())).thenReturn(queryParamsMock); + when(queryParamsMock.getFirst("depth")).thenReturn("0"); + when(headersMock.getRequestHeader("aai-request-context")).thenReturn(null); + } + + @Test + public void thatDBRequestsAreWritten() throws AAIException, UnsupportedEncodingException { + HttpEntry httpEntry = SpringContextAware.getBean("requestScopedTraversalUriHttpEntry", HttpEntry.class); + httpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion()); + TransactionalGraphEngine dbEngine = httpEntry.getDbEngine(); + Loader loader = httpEntry.getLoader(); + + List<String> hostnames = Arrays.asList("test1", "test2", "test3"); + List<DBRequest> dbRequests = createDbRequests(dbEngine, loader, hostnames); + + httpEntry.process(dbRequests, SERVICE_NAME); + + GraphTraversalSource source = dbEngine.startTransaction().traversal(); + Long pserverCount = source.V().has("aai-node-type","pserver").count().next(); + assertEquals(3, pserverCount.intValue()); + } + + @Test + // same test, only that JanusgraphException is thrown + public void thatDBRequestsAreRolledBack() throws AAIException, UnsupportedEncodingException { + HttpEntry httpEntry = SpringContextAware.getBean("requestScopedTraversalUriHttpEntry", HttpEntry.class); + httpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion()); + TransactionalGraphEngine dbEngine = httpEntry.getDbEngine(); + Loader loader = httpEntry.getLoader(); + + List<String> hostnames = Arrays.asList("test1", "test2", "test3"); + List<DBRequest> dbRequests = createDbRequests(dbEngine, loader, hostnames); + + DBRequest request2Spy = spy(dbRequests.get(1)); + QueryParser uriQuerySpy = spy(dbRequests.get(1).getParser()); + when(request2Spy.getParser()).thenReturn(uriQuerySpy); + dbRequests.set(1, request2Spy); + when(uriQuerySpy.getQueryBuilder()).thenThrow(new JanusGraphException("")); + + httpEntry.process(dbRequests, SERVICE_NAME); + + GraphTraversalSource source = dbEngine.startTransaction().traversal(); + Long pserverCount = source.V().has("aai-node-type","pserver").count().next(); + assertEquals(0, pserverCount.intValue()); + } + + @SneakyThrows + private List<DBRequest> createDbRequests(TransactionalGraphEngine dbEngine, Loader loader, List<String> hostnames) { + List<DBRequest> dbRequests = new ArrayList<>(); + + for(String hostname: hostnames) { + URI uriObject = UriBuilder.fromPath("/cloud-infrastructure/pservers/pserver/" + hostname).build(); + QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject); + String content = "{\"hostname\":\"" + hostname + "\"}"; + Introspector obj = loader.unmarshal(uriQuery.getResultType(), content,MediaType.APPLICATION_JSON_TYPE); + DBRequest request = new DBRequest.Builder(HttpMethod.PUT, uriObject, uriQuery, obj, headersMock, uriInfoMock, "someTransaction") + .rawRequestContent(content).build(); + dbRequests.add(request); + } + + return dbRequests; + } +} diff --git a/aai-core/src/test/java/org/onap/aai/rest/notification/EntityConverterTest.java b/aai-core/src/test/java/org/onap/aai/rest/notification/EntityConverterTest.java new file mode 100644 index 00000000..cbfedef7 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/rest/notification/EntityConverterTest.java @@ -0,0 +1,119 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2024 Deutsche Telekom. 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.aai.rest.notification; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.List; + + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.exceptions.AAIUnmarshallingException; +import org.onap.aai.parsers.uri.URIToObject; +import org.onap.aai.setup.SchemaVersion; + +public class EntityConverterTest { + + @Mock URIToObject parser; + @Mock Introspector introspector; + @Mock Loader loader; + @Mock List<Object> parentList; + + EntityConverter entityConverter; + + @BeforeEach + public void setUp() { + MockitoAnnotations.openMocks(this); + entityConverter = new EntityConverter(parser); + } + + @Test + public void testConvert_topEntitySameAsEntity() throws AAIUnmarshallingException { + when(parser.getParentList()).thenReturn(parentList); + when(parser.getTopEntity()).thenReturn(introspector); + when(parser.getEntity()).thenReturn(introspector); + + Introspector result = entityConverter.convert(introspector); + + assertEquals(introspector, result); + verify(parser.getParentList()).clear(); + } + + @Test + public void testConvert_topEntityDifferentFromEntity_withVersionMismatch() throws AAIUnmarshallingException { + Introspector topEntity = mock(Introspector.class); + Introspector childEntity = mock(Introspector.class); + String json = "{}"; + + when(parser.getParentList()).thenReturn(parentList); + when(parser.getTopEntity()).thenReturn(topEntity); + when(parser.getEntity()).thenReturn(childEntity); + when(childEntity.getName()).thenReturn("smth"); + when(parser.getLoader()).thenReturn(loader); + when(introspector.getVersion()).thenReturn(new SchemaVersion("v1")); + when(loader.getVersion()).thenReturn(new SchemaVersion("v2")); + when(introspector.marshal(false)).thenReturn(json); + when(loader.unmarshal(anyString(), eq(json))).thenReturn(childEntity); + + Introspector result = entityConverter.convert(introspector); + + assertEquals(topEntity, result); + } + + @Test + public void testConvert_topEntityDifferentFromEntity_withoutVersionMismatch() throws AAIUnmarshallingException { + Introspector topEntity = mock(Introspector.class); + Introspector childEntity = mock(Introspector.class); + + when(parser.getParentList()).thenReturn(parentList); + when(parser.getTopEntity()).thenReturn(topEntity); + when(parser.getEntity()).thenReturn(childEntity); + when(parser.getLoader()).thenReturn(loader); + when(introspector.getVersion()).thenReturn(new SchemaVersion("v1")); + when(loader.getVersion()).thenReturn(new SchemaVersion("v1")); + + Introspector result = entityConverter.convert(introspector); + + assertEquals(topEntity, result); + verify(parentList).add(any()); + } + + @Test + public void testGetTopEntityName() { + String topEntityName = "TopEntity"; + when(parser.getTopEntityName()).thenReturn(topEntityName); + + String result = entityConverter.getTopEntityName(); + + assertEquals(topEntityName, result); + } +} diff --git a/aai-core/src/test/java/org/onap/aai/rest/notification/NotificationServiceTest.java b/aai-core/src/test/java/org/onap/aai/rest/notification/NotificationServiceTest.java new file mode 100644 index 00000000..4fd21497 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/rest/notification/NotificationServiceTest.java @@ -0,0 +1,131 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2024 Deutsche Telekom. 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.aai.rest.notification; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import javax.ws.rs.core.Response.Status; + +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertex; +import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertexProperty; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aai.AAISetup; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.LoaderFactory; +import org.onap.aai.kafka.NotificationProducerService; +import org.onap.aai.prevalidation.ValidationService; +import org.onap.aai.serialization.db.DBSerializer; +import org.onap.aai.serialization.engines.query.QueryEngine; +import org.onap.aai.setup.SchemaVersion; +import org.onap.aai.setup.SchemaVersions; + +public class NotificationServiceTest extends AAISetup { + + @Mock LoaderFactory loaderFactory; + @Mock SchemaVersions schemaVersions; + @Mock UEBNotification uebNotification; + @Mock ValidationService validationService; + @Mock NotificationProducerService notificationProducerService; + @Mock DBSerializer dbSerializer; + @Mock QueryEngine queryEngine; + @Mock Introspector introspector; + + boolean isDeltaEventsEnabled = false; + String basePath = "/aai"; + NotificationService notificationService; + + @Before + public void setup() throws UnsupportedEncodingException, AAIException { + MockitoAnnotations.openMocks(this); + + when(dbSerializer.touchStandardVertexPropertiesForEdges()).thenReturn(Collections.emptySet()); + when(dbSerializer.getLatestVersionView(any(),anyInt())).thenReturn(introspector); + + notificationService = new NotificationService(validationService, loaderFactory, basePath, isDeltaEventsEnabled, notificationProducerService); + when(schemaVersions.getDefaultVersion()).thenReturn(new SchemaVersion("v29")); + doNothing().when(uebNotification).createNotificationEvent(any(),any(),any(),any(),any(),any(),any()); + doNothing().when(notificationProducerService).sendUEBNotification(any()); + } + + @Test + public void thatNotificationsCanBeCreatedWithoutEdges() throws AAIException, UnsupportedEncodingException { + + Map<String, Object> properties = new HashMap<>(); + properties.put(AAIProperties.NODE_TYPE, Collections.singletonList(new DetachedVertexProperty<String>("1", null, "pserver", new HashMap<>()))); + properties.put(AAIProperties.AAI_URI, Collections.singletonList(new DetachedVertexProperty<String>("1", null, "/pservers/pserver/hostname", new HashMap<>()))); + properties.put(AAIProperties.CREATED_TS, Collections.singletonList(new DetachedVertexProperty<String>("1", null, "12", new HashMap<>()))); + properties.put(AAIProperties.LAST_MOD_TS, Collections.singletonList(new DetachedVertexProperty<String>("1", null, "34", new HashMap<>()))); + + Vertex vertex = new DetachedVertex("1","label", properties); + Set<Vertex> mainVertexesToNotifyOn = new HashSet<>(); + mainVertexesToNotifyOn.add(vertex); + SchemaVersion schemaVersion = new SchemaVersion("v29"); + when(dbSerializer.getUpdatedVertexes()).thenReturn(Collections.emptyMap()); + + notificationService.generateEvents(uebNotification, AAIProperties.MINIMUM_DEPTH, "sourceOfTruth", dbSerializer, "transactionId", queryEngine, mainVertexesToNotifyOn, schemaVersion); + + verify(uebNotification, times(1)).createNotificationEvent(eq("transactionId"), eq("sourceOfTruth"), eq(Status.OK), eq(URI.create("/aai/v29/pservers/pserver/hostname")), eq(introspector), any(), eq("/aai")); + verify(validationService, times(1)).validate(anyList()); + verify(notificationProducerService, times(1)).sendUEBNotification(uebNotification); + } + + @Test + public void thatValidationCanBeDisabled() throws AAIException, UnsupportedEncodingException { + + Map<String, Object> properties = new HashMap<>(); + properties.put(AAIProperties.NODE_TYPE, Collections.singletonList(new DetachedVertexProperty<String>("1", null, "pserver", new HashMap<>()))); + properties.put(AAIProperties.AAI_URI, Collections.singletonList(new DetachedVertexProperty<String>("1", null, "/pservers/pserver/hostname", new HashMap<>()))); + properties.put(AAIProperties.CREATED_TS, Collections.singletonList(new DetachedVertexProperty<String>("1", null, "12", new HashMap<>()))); + properties.put(AAIProperties.LAST_MOD_TS, Collections.singletonList(new DetachedVertexProperty<String>("1", null, "34", new HashMap<>()))); + + Vertex vertex = new DetachedVertex("1","label", properties); + Set<Vertex> mainVertexesToNotifyOn = new HashSet<>(); + mainVertexesToNotifyOn.add(vertex); + SchemaVersion schemaVersion = new SchemaVersion("v29"); + when(dbSerializer.getUpdatedVertexes()).thenReturn(Collections.emptyMap()); + + notificationService = new NotificationService(null, loaderFactory, basePath, isDeltaEventsEnabled, notificationProducerService); + notificationService.generateEvents(uebNotification, AAIProperties.MINIMUM_DEPTH, "sourceOfTruth", dbSerializer, "transactionId", queryEngine, mainVertexesToNotifyOn, schemaVersion); + + verify(notificationProducerService, times(1)).sendUEBNotification(uebNotification); + } +} diff --git a/aai-core/src/test/java/org/onap/aai/rest/ueb/UEBNotificationTest.java b/aai-core/src/test/java/org/onap/aai/rest/notification/UEBNotificationTest.java index efa43250..e176f1cb 100644 --- a/aai-core/src/test/java/org/onap/aai/rest/ueb/UEBNotificationTest.java +++ b/aai-core/src/test/java/org/onap/aai/rest/notification/UEBNotificationTest.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.aai.rest.ueb; +package org.onap.aai.rest.notification; import static org.junit.Assert.assertEquals; @@ -71,14 +71,14 @@ public class UEBNotificationTest extends AAISetup { Introspector pserver = loader.introspectorFromName("pserver"); pserver.setValue("hostname", "hn"); URI uri = new URI("/cloud-infrastructure/pservers/pserver/hn"); - UEBNotification uebNotification = new UEBNotification(loader, loaderFactory, schemaVersions); + UEBNotification uebNotification = new UEBNotification(loaderFactory, schemaVersions); uebNotification.createNotificationEvent(UUID.randomUUID().toString(), "JUNIT-SOT", Response.Status.CREATED, uri, pserver, new HashMap<>(), BASE_PATH); assertEquals("One event created", 1, uebNotification.getEvents().size()); assertEquals("Uri is correct", BASE_PATH + "/" + schemaVersions.getDefaultVersion() + "/cloud-infrastructure/pservers/pserver/hn", - uebNotification.getEvents().get(0).getEventHeader().getValue("entity-link").toString()); + uebNotification.getEvents().get(0).getEventHeader().getEntityLink()); } @Test @@ -87,13 +87,13 @@ public class UEBNotificationTest extends AAISetup { Introspector pserver = loader.introspectorFromName("pserver"); pserver.setValue("hostname", "hn"); URI uri = new URI(BASE_PATH + "/v12/cloud-infrastructure/pservers/pserver/hn"); - UEBNotification uebNotification = new UEBNotification(loader, loaderFactory, schemaVersions); + UEBNotification uebNotification = new UEBNotification(loaderFactory, schemaVersions); uebNotification.createNotificationEvent(UUID.randomUUID().toString(), "JUNIT-SOT", Response.Status.CREATED, uri, pserver, new HashMap<>(), BASE_PATH); assertEquals("One event created", 1, uebNotification.getEvents().size()); assertEquals("Uri is correct", BASE_PATH + "/" + schemaVersions.getDefaultVersion() + "/cloud-infrastructure/pservers/pserver/hn", - uebNotification.getEvents().get(0).getEventHeader().getValue("entity-link").toString()); + uebNotification.getEvents().get(0).getEventHeader().getEntityLink()); } } diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializer_needsFakeRulesTest.java b/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializer_needsFakeRulesTest.java index ead83917..6db9e4fa 100644 --- a/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializer_needsFakeRulesTest.java +++ b/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializer_needsFakeRulesTest.java @@ -42,6 +42,7 @@ import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.onap.aai.config.ConfigConfiguration; import org.onap.aai.config.IntrospectionConfig; +import org.onap.aai.config.KafkaConfig; import org.onap.aai.config.SpringContextAware; import org.onap.aai.config.XmlFormatTransformerConfiguration; import org.onap.aai.db.props.AAIProperties; @@ -53,6 +54,7 @@ import org.onap.aai.introspection.LoaderFactory; import org.onap.aai.introspection.ModelType; import org.onap.aai.nodes.NodeIngestor; import org.onap.aai.parsers.query.QueryParser; +import org.onap.aai.rest.notification.NotificationService; import org.onap.aai.serialization.engines.JanusGraphDBEngine; import org.onap.aai.serialization.engines.QueryStyle; import org.onap.aai.serialization.engines.TransactionalGraphEngine; @@ -70,10 +72,11 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ContextConfiguration( classes = {ConfigConfiguration.class, AAICoreFakeEdgesConfigTranslator.class, NodeIngestor.class, EdgeIngestor.class, EdgeSerializer.class, SpringContextAware.class, IntrospectionConfig.class, - XmlFormatTransformerConfiguration.class}) + XmlFormatTransformerConfiguration.class, LoaderFactory.class, NotificationService.class, + KafkaConfig.class}) @TestPropertySource( properties = {"schema.translator.list = config", "schema.nodes.location=src/test/resources/onap/oxm", - "schema.edges.location=src/test/resources/onap/dbedgerules"}) + "schema.edges.location=src/test/resources/onap/dbedgerules","aai.notifications.enabled=false"}) public class DbSerializer_needsFakeRulesTest { // to use, set thrown.expect to whatever your test needs diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/EdgeRulesTest.java b/aai-core/src/test/java/org/onap/aai/serialization/db/EdgeRulesTest.java index 5dfa12b7..517a43a7 100644 --- a/aai-core/src/test/java/org/onap/aai/serialization/db/EdgeRulesTest.java +++ b/aai-core/src/test/java/org/onap/aai/serialization/db/EdgeRulesTest.java @@ -27,7 +27,9 @@ import static org.junit.Assert.assertEquals; import com.google.common.collect.Multimap; -import java.util.*; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; import org.apache.tinkerpop.gremlin.structure.Direction; import org.junit.Rule; diff --git a/aai-core/src/test/java/org/onap/aai/serialization/engines/query/GraphTraversalQueryEngineTest.java b/aai-core/src/test/java/org/onap/aai/serialization/engines/query/GraphTraversalQueryEngineTest.java index 738953d5..dff741ec 100644 --- a/aai-core/src/test/java/org/onap/aai/serialization/engines/query/GraphTraversalQueryEngineTest.java +++ b/aai-core/src/test/java/org/onap/aai/serialization/engines/query/GraphTraversalQueryEngineTest.java @@ -301,7 +301,7 @@ public class GraphTraversalQueryEngineTest extends AAISetup { /** * convenience helper method to make it easier to check the contents of the tree against * a list of expected results - * + * * @param tree - the tree whose contents you want in collection form * @return set of the contents of the tree */ diff --git a/aai-core/src/test/java/org/onap/aai/serialization/engines/query/GraphTraversalQueryEngine_needsFakeEdgeRulesTest.java b/aai-core/src/test/java/org/onap/aai/serialization/engines/query/GraphTraversalQueryEngine_needsFakeEdgeRulesTest.java index 6ae32f39..6a22aee1 100644 --- a/aai-core/src/test/java/org/onap/aai/serialization/engines/query/GraphTraversalQueryEngine_needsFakeEdgeRulesTest.java +++ b/aai-core/src/test/java/org/onap/aai/serialization/engines/query/GraphTraversalQueryEngine_needsFakeEdgeRulesTest.java @@ -20,7 +20,7 @@ package org.onap.aai.serialization.engines.query; -import static org.junit.Assert.*; +import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/FormatTest.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/FormatTest.java index 965e7157..78b8a5aa 100644 --- a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/FormatTest.java +++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/FormatTest.java @@ -20,7 +20,7 @@ package org.onap.aai.serialization.queryformats; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.Rule; import org.junit.Test; diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/PathedURLTest.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/PathedURLTest.java index 6ed42539..cd2c3af3 100644 --- a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/PathedURLTest.java +++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/PathedURLTest.java @@ -127,7 +127,7 @@ public class PathedURLTest extends AAISetup { when(urlBuilder.pathed(pserver)).thenReturn("/aai/v14/cloud-infrastructure/pservers/pserver/hostname-1"); Optional<JsonObject> jsonObjectOptional = pathedURL.getJsonFromVertex(pserver); - if (!jsonObjectOptional.isPresent()) { + if (jsonObjectOptional.isEmpty()) { fail("Expecting an json object returned from pathed url but returned none"); } @@ -150,7 +150,7 @@ public class PathedURLTest extends AAISetup { when(urlBuilder.pathed(pserver)).thenReturn("/aai/v14/cloud-infrastructure/pservers/pserver/hostname-1"); Optional<JsonObject> jsonObjectOptional = pathedURL.getJsonFromVertex(pserver); - if (!jsonObjectOptional.isPresent()) { + if (jsonObjectOptional.isEmpty()) { fail("Expecting an json object returned from pathed url but returned none"); } diff --git a/aai-core/src/test/java/org/onap/aai/util/PojoUtilsTest.java b/aai-core/src/test/java/org/onap/aai/util/PojoUtilsTest.java index 68f01962..a6a8c33d 100644 --- a/aai-core/src/test/java/org/onap/aai/util/PojoUtilsTest.java +++ b/aai-core/src/test/java/org/onap/aai/util/PojoUtilsTest.java @@ -100,18 +100,8 @@ public class PojoUtilsTest { LocalDateTime date = LocalDateTime.of(2017, Month.SEPTEMBER, 18, 10, 55, 0, 300); String res = pojoUtils.getJsonFromObject(date); - + assertEquals("\"2017-09-18T10:55:00.0000003\"", res); assertNotNull(res); - assertTrue(res.contains("\"dayOfMonth\" : 18")); - assertTrue(res.contains("\"dayOfWeek\" : \"MONDAY\"")); - assertTrue(res.contains("\"dayOfYear\" : 261")); - assertTrue(res.contains("\"hour\" : 10")); - assertTrue(res.contains("\"minute\" : 55")); - assertTrue(res.contains("\"month\" : \"SEPTEMBER\"")); - assertTrue(res.contains("\"monthValue\" : 9")); - assertTrue(res.contains("\"nano\" : 300")); - assertTrue(res.contains("\"second\" : 0")); - assertTrue(res.contains("\"year\" : 2017")); } @Test diff --git a/aai-core/src/test/java/org/onap/aai/util/StoreNotificationEventTest.java b/aai-core/src/test/java/org/onap/aai/util/StoreNotificationEventTest.java deleted file mode 100644 index a0c3f639..00000000 --- a/aai-core/src/test/java/org/onap/aai/util/StoreNotificationEventTest.java +++ /dev/null @@ -1,227 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. 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.aai.util; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import com.fasterxml.jackson.core.JsonGenerationException; -import com.fasterxml.jackson.databind.JsonMappingException; - -import java.io.IOException; - -import javax.json.Json; -import javax.json.JsonObject; - -import org.eclipse.persistence.dynamic.DynamicEntity; -import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.mockito.Mockito; -import org.onap.aai.AAISetup; -import org.onap.aai.domain.notificationEvent.NotificationEvent.EventHeader; -import org.onap.aai.exceptions.AAIException; -import org.onap.aai.introspection.Introspector; -import org.onap.aai.introspection.Loader; -import org.onap.aai.introspection.ModelType; -import org.onap.aai.kafka.AAIKafkaEventJMSProducer; - -public class StoreNotificationEventTest extends AAISetup { - - private static AAIKafkaEventJMSProducer producer; - private static StoreNotificationEvent sne; - - @BeforeClass - public static void setUp() { - producer = Mockito.mock(AAIKafkaEventJMSProducer.class); - // sne = new StoreNotificationEvent(producer, "transiationId", "sourceOfTruth"); - } - - @Before - public void setUpBefore() { - producer = Mockito.mock(AAIKafkaEventJMSProducer.class); - sne = new StoreNotificationEvent(producer, "transiationId", "sourceOfTruth"); - - } - - @Test(expected = AAIException.class) - public void testStoreEventNullObj() throws AAIException { - sne.storeEventAndSendToJms(new EventHeader(), null); - } - - @Test(expected = AAIException.class) - public void testStoreEventInvalidObjForPojoUtils() throws AAIException { - sne.storeEventAndSendToJms(new EventHeader(), new Object()); - } - - @Test - public void testStoreEventEmptyEventHeader() - throws AAIException, JsonGenerationException, JsonMappingException, IOException { - JsonObject object = Json.createObjectBuilder().add("hello", "world").build(); - String res = sne.storeEventAndSendToJms(new EventHeader(), object); - - assertNotNull(res); - assertTrue(res.contains("\"cambria.partition\" : \"" + AAIConstants.UEB_PUB_PARTITION_AAI + "\"")); - assertTrue(res.contains("\"event-header\"")); - assertTrue(res.contains("\"id\"")); - assertTrue(res.contains("\"timestamp\"")); - assertTrue(res - .contains("\"source-name\" : \"" + AAIConfig.get("aai.notificationEvent.default.sourceName") + "\"")); - assertTrue(res.contains("\"domain\" : \"" + AAIConfig.get("aai.notificationEvent.default.domain") + "\"")); - assertTrue(res.contains( - "\"sequence-number\" : \"" + AAIConfig.get("aai.notificationEvent.default.sequenceNumber") + "\"")); - assertTrue(res.contains("\"severity\" : \"" + AAIConfig.get("aai.notificationEvent.default.severity") + "\"")); - assertTrue( - res.contains("\"event-type\" : \"" + AAIConfig.get("aai.notificationEvent.default.eventType") + "\"")); - assertTrue(res.contains("\"version\" : \"" + AAIConfig.get("aai.notificationEvent.default.version") + "\"")); - assertTrue(res.contains("\"action\" : \"UNK\"")); - assertTrue(res.contains("\"entity-link\" : \"UNK\"")); - assertTrue(res.contains("\"entity\"")); - assertTrue(res.contains("\"hello\"")); - assertTrue(res.contains("\"chars\" : \"world\"")); - assertTrue(res.contains("\"string\" : \"world\"")); - assertTrue(res.contains("\"valueType\" : \"STRING\"")); - } - - @Test - public void testStoreEvent() throws AAIException, JsonGenerationException, JsonMappingException, IOException { - JsonObject object = Json.createObjectBuilder().add("hello", "world").build(); - EventHeader eh = new EventHeader(); - eh.setId("123"); - eh.setTimestamp("current-time"); - eh.setEntityLink("entity-link"); - eh.setAction("action!"); - eh.setEventType("surprise"); - eh.setDomain("PROD"); - eh.setSourceName("source"); - eh.setSequenceNumber("23"); - eh.setSeverity("ALERT"); - eh.setVersion("v12"); - - String res = sne.storeEventAndSendToJms(eh, object); - - assertNotNull(res); - assertTrue(res.contains("\"cambria.partition\" : \"" + AAIConstants.UEB_PUB_PARTITION_AAI + "\"")); - assertTrue(res.contains("\"event-header\"")); - assertTrue(res.contains("\"id\" : \"123\"")); - assertTrue(res.contains("\"timestamp\" : \"current-time\"")); - assertTrue(res.contains("\"source-name\" : \"source\"")); - assertTrue(res.contains("\"domain\" : \"PROD\"")); - assertTrue(res.contains("\"sequence-number\" : \"23\"")); - assertTrue(res.contains("\"severity\" : \"ALERT\"")); - assertTrue(res.contains("\"event-type\" : \"surprise\"")); - assertTrue(res.contains("\"version\" : \"v12\"")); - assertTrue(res.contains("\"action\" : \"action!\"")); - assertTrue(res.contains("\"entity-link\" : \"entity-link\"")); - assertTrue(res.contains("\"entity\"")); - assertTrue(res.contains("\"hello\"")); - assertTrue(res.contains("\"chars\" : \"world\"")); - assertTrue(res.contains("\"string\" : \"world\"")); - assertTrue(res.contains("\"valueType\" : \"STRING\"")); - } - - @Test(expected = AAIException.class) - public void testStoreDynamicEventNullObj() throws AAIException { - DynamicEntity eventHeader = Mockito.mock(DynamicEntity.class); - DynamicJAXBContext notificationJaxbContext = - nodeIngestor.getContextForVersion(schemaVersions.getEdgeLabelVersion()); - sne.storeDynamicEvent(notificationJaxbContext, "v12", eventHeader, null); - } - - @Test(expected = Exception.class) - public void testStoreDynamicEventAAIException() throws Exception { - - DynamicJAXBContext notificationJaxbContext = - nodeIngestor.getContextForVersion(schemaVersions.getEdgeLabelVersion()); - DynamicEntity obj = Mockito.mock(DynamicEntity.class); - DynamicEntity eventHeader = Mockito.mock(DynamicEntity.class); - sne.storeDynamicEvent(notificationJaxbContext, "v12", eventHeader, obj); - } - - @Test(expected = AAIException.class) - public void testStoreEventIntrospectorNullObj() throws Exception { - Loader loader = Mockito.mock(Loader.class); - sne.storeEventAndSendToJms(loader, null, null); - } - - @Ignore("Stopped working since the model driven story") - @Test - public void testStoreEvent1Introspector() throws Exception { - Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getEdgeLabelVersion()); - Introspector eventHeader = loader.introspectorFromName("notification-event-header"); - eventHeader.setValue("id", "123"); - eventHeader.setValue("timestamp", "current-time"); - eventHeader.setValue("entity-link", "entity-link"); - eventHeader.setValue("action", "action!"); - eventHeader.setValue("event-type", "surprise"); - eventHeader.setValue("domain", "PROD"); - eventHeader.setValue("source-name", "source"); - eventHeader.setValue("sequence-number", "23"); - eventHeader.setValue("severity", "ALERT"); - eventHeader.setValue("version", "v12"); - Introspector obj = loader.introspectorFromName("notification-event"); - String res = sne.storeEventAndSendToJms(loader, eventHeader, obj); - - assertNotNull(res); - assertTrue(res.contains("\"cambria.partition\":\"" + AAIConstants.UEB_PUB_PARTITION_AAI + "\"")); - assertTrue(res.contains("\"event-header\"")); - assertTrue(res.contains("\"id\":\"123\"")); - assertTrue(res.contains("\"timestamp\":\"current-time\"")); - assertTrue(res.contains("\"source-name\":\"source\"")); - assertTrue(res.contains("\"domain\":\"PROD\"")); - assertTrue(res.contains("\"sequence-number\":\"23\"")); - assertTrue(res.contains("\"severity\":\"ALERT\"")); - assertTrue(res.contains("\"event-type\":\"surprise\"")); - assertTrue(res.contains("\"version\":\"v12\"")); - assertTrue(res.contains("\"action\":\"action!\"")); - assertTrue(res.contains("\"entity-link\":\"entity-link\"")); - assertTrue(res.contains("\"notification-event\"")); - } - - @Ignore("Stopped working since the model driven story") - @Test - public void testStoreEventIntrospectorEmptyEventHeader() throws Exception { - Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getEdgeLabelVersion()); - Introspector eventHeader = loader.introspectorFromName("notification-event-header"); - Introspector obj = loader.introspectorFromName("notification-event"); - - String res = sne.storeEventAndSendToJms(loader, eventHeader, obj); - - assertNotNull(res); - assertTrue(res.contains("\"cambria.partition\":\"" + AAIConstants.UEB_PUB_PARTITION_AAI + "\"")); - assertTrue(res.contains("\"event-header\"")); - assertTrue(res.contains("\"id\"")); - assertTrue(res.contains("\"timestamp\"")); - assertTrue( - res.contains("\"source-name\":\"" + AAIConfig.get("aai.notificationEvent.default.sourceName") + "\"")); - assertTrue(res.contains("\"domain\":\"" + AAIConfig.get("aai.notificationEvent.default.domain") + "\"")); - assertTrue(res.contains( - "\"sequence-number\":\"" + AAIConfig.get("aai.notificationEvent.default.sequenceNumber") + "\"")); - assertTrue(res.contains("\"severity\":\"" + AAIConfig.get("aai.notificationEvent.default.severity") + "\"")); - assertTrue(res.contains("\"event-type\":\"" + AAIConfig.get("aai.notificationEvent.default.eventType") + "\"")); - assertTrue(res.contains("\"version\":\"" + AAIConfig.get("aai.notificationEvent.default.version") + "\"")); - assertTrue(res.contains("\"action\":\"UNK\"")); - assertTrue(res.contains("\"entity-link\":\"UNK\"")); - assertTrue(res.contains("\"notification-event\"")); - } -} |