diff options
author | Renu Kumari <renu.kumari@bell.ca> | 2021-05-27 23:16:32 -0400 |
---|---|---|
committer | Renu Kumari <renu.kumari@bell.ca> | 2021-07-07 06:54:13 -0400 |
commit | ff52b94907002d2d2910567e1ad5f55e66008eb8 (patch) | |
tree | b53ea7cf4587ec84db6db77b0d23f23327e538ad /cps-service/src/test/groovy/org | |
parent | 6658f50ddbfbd13469f24aefc8a6002d8807a7eb (diff) |
Sending Data Updated Event to kafka
Issue-ID: CPS-374
Signed-off-by: Renu Kumari <renu.kumari@bell.ca>
Change-Id: I05fedcace42b84575411df26c586788bffe6b846
Diffstat (limited to 'cps-service/src/test/groovy/org')
7 files changed, 422 insertions, 6 deletions
diff --git a/cps-service/src/test/groovy/org/onap/cps/api/impl/CpsDataServiceImplSpec.groovy b/cps-service/src/test/groovy/org/onap/cps/api/impl/CpsDataServiceImplSpec.groovy index 8001d6a9fe..bf94401c08 100644 --- a/cps-service/src/test/groovy/org/onap/cps/api/impl/CpsDataServiceImplSpec.groovy +++ b/cps-service/src/test/groovy/org/onap/cps/api/impl/CpsDataServiceImplSpec.groovy @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2021 Nordix Foundation * Modifications Copyright (C) 2021 Pantheon.tech + * Modifications Copyright (C) 2021 Bell Canada. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +24,7 @@ package org.onap.cps.api.impl import org.onap.cps.TestUtils import org.onap.cps.api.CpsAdminService import org.onap.cps.api.CpsModuleService +import org.onap.cps.notification.NotificationService import org.onap.cps.spi.CpsDataPersistenceService import org.onap.cps.spi.FetchDescendantsOption import org.onap.cps.spi.exceptions.DataValidationException @@ -37,6 +39,7 @@ class CpsDataServiceImplSpec extends Specification { def mockCpsAdminService = Mock(CpsAdminService) def mockCpsModuleService = Mock(CpsModuleService) def mockYangTextSchemaSourceSetCache = Mock(YangTextSchemaSourceSetCache) + def mockNotificationService = Mock(NotificationService) def objectUnderTest = new CpsDataServiceImpl() @@ -45,6 +48,7 @@ class CpsDataServiceImplSpec extends Specification { objectUnderTest.cpsAdminService = mockCpsAdminService objectUnderTest.cpsModuleService = mockCpsModuleService objectUnderTest.yangTextSchemaSourceSetCache = mockYangTextSchemaSourceSetCache + objectUnderTest.notificationService = mockNotificationService } def dataspaceName = 'some dataspace' @@ -60,6 +64,8 @@ class CpsDataServiceImplSpec extends Specification { then: 'the persistence service method is invoked with correct parameters' 1 * mockCpsDataPersistenceService.storeDataNode(dataspaceName, anchorName, { dataNode -> dataNode.xpath == '/test-tree' }) + and: 'data updated event is sent to notification service' + 1 * mockNotificationService.processDataUpdatedEvent(dataspaceName, anchorName) } def 'Saving child data fragment under existing node.'() { @@ -71,6 +77,8 @@ class CpsDataServiceImplSpec extends Specification { then: 'the persistence service method is invoked with correct parameters' 1 * mockCpsDataPersistenceService.addChildDataNode(dataspaceName, anchorName, '/test-tree', { dataNode -> dataNode.xpath == '/test-tree/branch[@name=\'New\']' }) + and: 'data updated event is sent to notification service' + 1 * mockNotificationService.processDataUpdatedEvent(dataspaceName, anchorName) } def 'Saving list-node data fragment under existing node.'() { @@ -89,6 +97,8 @@ class CpsDataServiceImplSpec extends Specification { } } ) + and: 'data updated event is sent to notification service' + 1 * mockNotificationService.processDataUpdatedEvent(dataspaceName, anchorName) } def 'Saving empty list-node data fragment.'() { @@ -119,6 +129,8 @@ class CpsDataServiceImplSpec extends Specification { objectUnderTest.updateNodeLeaves(dataspaceName, anchorName, parentNodeXpath, jsonData) then: 'the persistence service method is invoked with correct parameters' 1 * mockCpsDataPersistenceService.updateDataLeaves(dataspaceName, anchorName, expectedNodeXpath, leaves) + and: 'data updated event is sent to notification service' + 1 * mockNotificationService.processDataUpdatedEvent(dataspaceName, anchorName) where: 'following parameters were used' scenario | parentNodeXpath | jsonData || expectedNodeXpath | leaves 'top level node' | '/' | '{"test-tree": {"branch": []}}' || '/test-tree' | Collections.emptyMap() @@ -146,6 +158,8 @@ class CpsDataServiceImplSpec extends Specification { then: 'the persistence service method is invoked with correct parameters' 1 * mockCpsDataPersistenceService.replaceDataNodeTree(dataspaceName, anchorName, { dataNode -> dataNode.xpath == expectedNodeXpath }) + and: 'data updated event is sent to notification service' + 1 * mockNotificationService.processDataUpdatedEvent(dataspaceName, anchorName) where: 'following parameters were used' scenario | parentNodeXpath | jsonData || expectedNodeXpath 'top level node' | '/' | '{"test-tree": {"branch": []}}' || '/test-tree' @@ -168,6 +182,8 @@ class CpsDataServiceImplSpec extends Specification { } } ) + and: 'data updated event is sent to notification service' + 1 * mockNotificationService.processDataUpdatedEvent(dataspaceName, anchorName) } def 'Replace with empty list-node data fragment.'() { diff --git a/cps-service/src/test/groovy/org/onap/cps/api/impl/E2ENetworkSliceSpec.groovy b/cps-service/src/test/groovy/org/onap/cps/api/impl/E2ENetworkSliceSpec.groovy index aa54a9991e..b5ad42df01 100755 --- a/cps-service/src/test/groovy/org/onap/cps/api/impl/E2ENetworkSliceSpec.groovy +++ b/cps-service/src/test/groovy/org/onap/cps/api/impl/E2ENetworkSliceSpec.groovy @@ -23,6 +23,7 @@ package org.onap.cps.api.impl import org.onap.cps.TestUtils
import org.onap.cps.api.CpsAdminService
+import org.onap.cps.notification.NotificationService
import org.onap.cps.spi.CpsDataPersistenceService
import org.onap.cps.spi.CpsModulePersistenceService
import org.onap.cps.spi.model.Anchor
@@ -34,8 +35,9 @@ class E2ENetworkSliceSpec extends Specification { def mockModuleStoreService = Mock(CpsModulePersistenceService)
def mockDataStoreService = Mock(CpsDataPersistenceService)
def mockCpsAdminService = Mock(CpsAdminService)
+ def mockNotificationService = Mock(NotificationService)
def cpsModuleServiceImpl = new CpsModuleServiceImpl()
- def cpsDataServiceImple = new CpsDataServiceImpl()
+ def cpsDataServiceImpl = new CpsDataServiceImpl()
def mockYangTextSchemaSourceSetCache = Mock(YangTextSchemaSourceSetCache)
def dataspaceName = 'someDataspace'
@@ -43,9 +45,10 @@ class E2ENetworkSliceSpec extends Specification { def schemaSetName = 'someSchemaSet'
def setup() {
- cpsDataServiceImple.cpsDataPersistenceService = mockDataStoreService
- cpsDataServiceImple.cpsAdminService = mockCpsAdminService
- cpsDataServiceImple.yangTextSchemaSourceSetCache = mockYangTextSchemaSourceSetCache
+ cpsDataServiceImpl.cpsDataPersistenceService = mockDataStoreService
+ cpsDataServiceImpl.cpsAdminService = mockCpsAdminService
+ cpsDataServiceImpl.yangTextSchemaSourceSetCache = mockYangTextSchemaSourceSetCache
+ cpsDataServiceImpl.notificationService = mockNotificationService
cpsModuleServiceImpl.yangTextSchemaSourceSetCache = mockYangTextSchemaSourceSetCache
cpsModuleServiceImpl.cpsModulePersistenceService = mockModuleStoreService
}
@@ -88,7 +91,7 @@ class E2ENetworkSliceSpec extends Specification { YangTextSchemaSourceSetBuilder.of(yangResourcesNameToContentMap)
mockModuleStoreService.getYangSchemaResources(dataspaceName, schemaSetName) >> schemaContext
when: 'saveData method is invoked'
- cpsDataServiceImple.saveData(dataspaceName, anchorName, jsonData)
+ cpsDataServiceImpl.saveData(dataspaceName, anchorName, jsonData)
then: 'Parameters are validated and processing is delegated to persistence service'
1 * mockDataStoreService.storeDataNode('someDataspace', 'someAnchor', _) >>
{ args -> dataNodeStored = args[2]}
@@ -120,7 +123,7 @@ class E2ENetworkSliceSpec extends Specification { mockYangTextSchemaSourceSetCache.get('someDataspace', 'someSchemaSet') >> YangTextSchemaSourceSetBuilder.of(yangResourcesNameToContentMap)
mockModuleStoreService.getYangSchemaResources('someDataspace', 'someSchemaSet') >> schemaContext
when: 'saveData method is invoked'
- cpsDataServiceImple.saveData('someDataspace', 'someAnchor', jsonData)
+ cpsDataServiceImpl.saveData('someDataspace', 'someAnchor', jsonData)
then: 'parameters are validated and processing is delegated to persistence service'
1 * mockDataStoreService.storeDataNode('someDataspace', 'someAnchor', _) >>
{ args -> dataNodeStored = args[2]}
diff --git a/cps-service/src/test/groovy/org/onap/cps/notification/CpsDataUpdateEventFactorySpec.groovy b/cps-service/src/test/groovy/org/onap/cps/notification/CpsDataUpdateEventFactorySpec.groovy new file mode 100644 index 0000000000..aecc3f7ee0 --- /dev/null +++ b/cps-service/src/test/groovy/org/onap/cps/notification/CpsDataUpdateEventFactorySpec.groovy @@ -0,0 +1,86 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Bell Canada. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.cps.notification + +import org.onap.cps.api.CpsAdminService +import org.onap.cps.api.CpsDataService +import org.onap.cps.event.model.CpsDataUpdatedEvent +import org.onap.cps.event.model.Data +import org.onap.cps.spi.FetchDescendantsOption +import org.onap.cps.spi.model.Anchor +import org.onap.cps.spi.model.DataNodeBuilder +import org.springframework.util.StringUtils +import spock.lang.Specification + +import java.time.format.DateTimeFormatter + +class CpsDataUpdateEventFactorySpec extends Specification { + + def mockCpsDataService = Mock(CpsDataService) + def mockCpsAdminService = Mock(CpsAdminService) + + def objectUnderTest = new CpsDataUpdatedEventFactory(mockCpsDataService, mockCpsAdminService) + + def myDataspaceName = 'my-dataspace' + def myAnchorName = 'my-anchorname' + def mySchemasetName = 'my-schemaset-name' + def dateTimeFormat = 'yyyy-MM-dd\'T\'HH:mm:ss.SSSZ' + + def 'Create a CPS data updated event successfully.'() { + + given: 'cps admin service is able to return anchor details' + mockCpsAdminService.getAnchor(myDataspaceName, myAnchorName) >> + new Anchor(myAnchorName, myDataspaceName, mySchemasetName) + and: 'cps data service returns the data node details' + def xpath = '/' + def dataNode = new DataNodeBuilder().withXpath(xpath).withLeaves(['leafName': 'leafValue']).build() + mockCpsDataService.getDataNode( + myDataspaceName, myAnchorName, xpath, FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS) >> dataNode + + when: 'CPS data updated event is created' + def cpsDataUpdatedEvent = objectUnderTest.createCpsDataUpdatedEvent(myDataspaceName, myAnchorName) + + then: 'CPS data updated event is created with expected values' + with(cpsDataUpdatedEvent) { + type == 'org.onap.cps.data-updated-event' + source == new URI('urn:cps:org.onap.cps') + schema == CpsDataUpdatedEvent.Schema.URN_CPS_ORG_ONAP_CPS_DATA_UPDATED_EVENT_SCHEMA_1_1_0_SNAPSHOT + StringUtils.hasText(id) + content != null + } + with(cpsDataUpdatedEvent.content) { + assert isExpectedDateTimeFormat(observedTimestamp): "$observedTimestamp is not in $dateTimeFormat format" + anchorName == myAnchorName + dataspaceName == myDataspaceName + schemaSetName == mySchemasetName + data == new Data().withAdditionalProperty('leafName', 'leafValue') + } + } + + def isExpectedDateTimeFormat(String observedTimestamp) { + try { + DateTimeFormatter.ofPattern(dateTimeFormat).parse(observedTimestamp) + } catch (DateTimeParseException) { + return false + } + return true + } + +} diff --git a/cps-service/src/test/groovy/org/onap/cps/notification/KafkaPublisherSpecBase.groovy b/cps-service/src/test/groovy/org/onap/cps/notification/KafkaPublisherSpecBase.groovy new file mode 100644 index 0000000000..b60b38f054 --- /dev/null +++ b/cps-service/src/test/groovy/org/onap/cps/notification/KafkaPublisherSpecBase.groovy @@ -0,0 +1,93 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Bell Canada. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.cps.notification + +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration +import org.springframework.boot.test.context.SpringBootTest +import org.springframework.kafka.config.TopicBuilder +import org.springframework.kafka.core.ConsumerFactory +import org.springframework.kafka.core.KafkaAdmin +import org.springframework.kafka.core.KafkaTemplate +import org.springframework.kafka.listener.ConcurrentMessageListenerContainer +import org.springframework.kafka.listener.ContainerProperties +import org.springframework.kafka.listener.MessageListener +import org.springframework.kafka.test.utils.ContainerTestUtils +import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.DynamicPropertyRegistry +import org.springframework.test.context.DynamicPropertySource +import spock.lang.Shared +import spock.lang.Specification + +@ContextConfiguration(classes = [KafkaAutoConfiguration, KafkaProducerListener, NotificationErrorHandler]) +@SpringBootTest +class KafkaPublisherSpecBase extends Specification { + + @Autowired + KafkaTemplate kafkaTemplate + + @Autowired + KafkaAdmin kafkaAdmin + + @Autowired + ConsumerFactory consumerFactory + + @Shared volatile topicCreated = false + @Shared consumedMessages = new ArrayList<>() + + def cpsEventTopic = 'cps-events' + + @DynamicPropertySource + static void registerKafkaProperties(DynamicPropertyRegistry registry) { + registry.add("spring.kafka.bootstrap-servers", KafkaTestContainerConfig::getBootstrapServers) + } + + def setup() { + // Kafka listener and topic should be created only once for a test-suite. + // We are also dependent on sprint context to achieve it, and can not execute it in setupSpec + if (!topicCreated) { + kafkaAdmin.createOrModifyTopics(TopicBuilder.name(cpsEventTopic).partitions(1).replicas(1).build()) + startListeningToTopic() + topicCreated = true + } + /* kafka message listener stores the messages to consumedMessages. + It is important to clear the list before each test case so that test cases can fetch the message from index '0'. + */ + consumedMessages.clear() + } + + def startListeningToTopic() { + ContainerProperties containerProperties = new ContainerProperties(cpsEventTopic) + containerProperties.setMessageListener([ + onMessage: { + record -> + consumedMessages.add(record.value()) + }] as MessageListener) + + ConcurrentMessageListenerContainer container = + new ConcurrentMessageListenerContainer<>( + consumerFactory, + containerProperties) + + container.start() + ContainerTestUtils.waitForAssignment(container, 1) + } + +} diff --git a/cps-service/src/test/groovy/org/onap/cps/notification/KafkaTestContainerConfig.groovy b/cps-service/src/test/groovy/org/onap/cps/notification/KafkaTestContainerConfig.groovy new file mode 100644 index 0000000000..5124a519a7 --- /dev/null +++ b/cps-service/src/test/groovy/org/onap/cps/notification/KafkaTestContainerConfig.groovy @@ -0,0 +1,49 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Bell Canada. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.cps.notification + +import org.testcontainers.containers.KafkaContainer +import org.testcontainers.utility.DockerImageName + +class KafkaTestContainerConfig { + + private static KafkaContainer kafkaContainer + + static { + getKafkaContainer() + } + + // Not the best performance but it is good enough for test case + private static synchronized KafkaContainer getKafkaContainer() { + if (kafkaContainer == null) { + kafkaContainer = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:6.1.1")) + .withEnv("KAFKA_AUTO_CREATE_TOPICS_ENABLE", "false") + kafkaContainer.start() + Runtime.getRuntime().addShutdownHook(new Thread(kafkaContainer::stop)) + } + return kafkaContainer + } + + static String getBootstrapServers() { + getKafkaContainer() + return kafkaContainer.getBootstrapServers() + } + +} diff --git a/cps-service/src/test/groovy/org/onap/cps/notification/NotificationPublisherSpec.groovy b/cps-service/src/test/groovy/org/onap/cps/notification/NotificationPublisherSpec.groovy new file mode 100644 index 0000000000..f215c6dc09 --- /dev/null +++ b/cps-service/src/test/groovy/org/onap/cps/notification/NotificationPublisherSpec.groovy @@ -0,0 +1,91 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Bell Canada. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.cps.notification + +import org.apache.kafka.clients.producer.ProducerRecord +import org.apache.kafka.clients.producer.RecordMetadata +import org.onap.cps.event.model.Content +import org.onap.cps.event.model.CpsDataUpdatedEvent +import org.spockframework.spring.SpringBean +import org.springframework.kafka.KafkaException +import org.springframework.kafka.core.KafkaTemplate +import spock.util.concurrent.PollingConditions + +class NotificationPublisherSpec extends KafkaPublisherSpecBase { + + @SpringBean + NotificationErrorHandler spyNotificationErrorHandler = Spy(new NotificationErrorHandler()) + + @SpringBean + KafkaProducerListener spyKafkaProducerListener = Spy(new KafkaProducerListener<>(spyNotificationErrorHandler)) + + KafkaTemplate spyKafkaTemplate + NotificationPublisher objectUnderTest + + def myAnchorName = 'my-anchor' + def myDataspaceName = 'my-dataspace' + + def cpsDataUpdatedEvent = new CpsDataUpdatedEvent() + .withContent(new Content() + .withDataspaceName(myDataspaceName) + .withAnchorName(myAnchorName)) + + def setup() { + spyKafkaTemplate = Spy(kafkaTemplate) + objectUnderTest = new NotificationPublisher(spyKafkaTemplate, cpsEventTopic); + } + + def 'Sending event to message bus with correct message Key.'() { + + when: 'event is sent to publisher' + objectUnderTest.sendNotification(cpsDataUpdatedEvent) + kafkaTemplate.flush() + + then: 'event is sent to correct topic with the expected messageKey' + interaction { + def messageKey = myDataspaceName + "," + myAnchorName + 1 * spyKafkaTemplate.send(cpsEventTopic, messageKey, cpsDataUpdatedEvent) + } + and: 'received a successful response' + 1 * spyKafkaProducerListener.onSuccess(_ as ProducerRecord, _) + and: 'kafka consumer returns expected message' + def conditions = new PollingConditions(timeout: 60, initialDelay: 0, factor: 1) + conditions.eventually { + assert cpsDataUpdatedEvent == consumedMessages.get(0) + } + } + + def 'Handling of async errors from message bus.'() { + given: 'topic does not exist' + objectUnderTest.topicName = 'non-existing-topic' + + when: 'message to sent to a non-existing topic' + objectUnderTest.sendNotification(cpsDataUpdatedEvent) + kafkaTemplate.flush() + + then: 'error is thrown' + thrown KafkaException + and: 'error handler is called with exception details' + 1 * spyKafkaProducerListener.onError(_ as ProducerRecord, _, _ as Exception) + 1 * spyNotificationErrorHandler.onException(_ as String, _ as Exception, + _ as ProducerRecord, _) + } + +} diff --git a/cps-service/src/test/groovy/org/onap/cps/notification/NotificationServiceSpec.groovy b/cps-service/src/test/groovy/org/onap/cps/notification/NotificationServiceSpec.groovy new file mode 100644 index 0000000000..a74279548e --- /dev/null +++ b/cps-service/src/test/groovy/org/onap/cps/notification/NotificationServiceSpec.groovy @@ -0,0 +1,78 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Bell Canada. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.cps.notification + +import org.onap.cps.event.model.CpsDataUpdatedEvent +import spock.lang.Specification + +class NotificationServiceSpec extends Specification { + + def mockNotificationPublisher = Mock(NotificationPublisher) + def spyNotificationErrorHandler = Spy(new NotificationErrorHandler()) + def mockCpsDataUpdatedEventFactory = Mock(CpsDataUpdatedEventFactory) + + def objectUnderTest = new NotificationService(true, mockNotificationPublisher, + mockCpsDataUpdatedEventFactory, spyNotificationErrorHandler) + + def myDataspaceName = 'my-dataspace' + def myAnchorName = 'my-anchorname' + + def 'Skip sending notification when disabled.'() { + + given: 'notification is disabled' + objectUnderTest.dataUpdatedEventNotificationEnabled = false + + when: 'dataUpdatedEvent is received' + objectUnderTest.processDataUpdatedEvent(myDataspaceName, myAnchorName) + + then: 'the notification is not sent' + 0 * mockNotificationPublisher.sendNotification(_) + } + + def 'Send notification when enabled.'() { + + given: 'notification is enabled' + objectUnderTest.dataUpdatedEventNotificationEnabled = true + and: 'event factory can create event successfully' + def cpsDataUpdatedEvent = new CpsDataUpdatedEvent() + mockCpsDataUpdatedEventFactory.createCpsDataUpdatedEvent(myDataspaceName, myAnchorName) >> cpsDataUpdatedEvent + + when: 'dataUpdatedEvent is received' + objectUnderTest.processDataUpdatedEvent(myDataspaceName, myAnchorName) + + then: 'notification is sent with correct event' + 1 * mockNotificationPublisher.sendNotification(cpsDataUpdatedEvent) + } + + def 'Error handling in notification service.'(){ + given: 'event factory can not create event successfully' + mockCpsDataUpdatedEventFactory.createCpsDataUpdatedEvent(myDataspaceName, myAnchorName) >> + { throw new Exception("Could not create event") } + + when: 'event is sent for processing' + objectUnderTest.processDataUpdatedEvent(myDataspaceName, myAnchorName) + + then: 'error is handled and not thrown to caller' + notThrown Exception + 1 * spyNotificationErrorHandler.onException(_,_,_,_) + + } + +} |