Normalize parent xpath when building datanodes in CpsDataService
[cps.git] / cps-ncmp-service / src / test / groovy / org / onap / cps / ncmp / api / impl / events / avcsubscription / SubscriptionEventForwarderSpec.groovy
1 /*
2  * ============LICENSE_START=======================================================
3  * Copyright (c) 2023 Nordix Foundation.
4  *  ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an 'AS IS' BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  *  SPDX-License-Identifier: Apache-2.0
18  *  ============LICENSE_END=========================================================
19  */
20
21 package org.onap.cps.ncmp.api.impl.events.avcsubscription
22
23 import com.fasterxml.jackson.databind.ObjectMapper
24 import com.hazelcast.map.IMap
25 import org.apache.kafka.clients.consumer.ConsumerRecord
26 import org.onap.cps.ncmp.api.impl.events.EventsPublisher
27 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle
28 import org.onap.cps.ncmp.api.inventory.InventoryPersistence
29 import org.onap.cps.ncmp.api.kafka.MessagingBaseSpec
30 import org.onap.cps.ncmp.event.model.SubscriptionEvent
31 import org.onap.cps.ncmp.utils.TestUtils
32 import org.onap.cps.spi.exceptions.OperationNotYetSupportedException
33 import org.onap.cps.utils.JsonObjectMapper
34 import org.spockframework.spring.SpringBean
35 import org.springframework.beans.factory.annotation.Autowired
36 import org.springframework.boot.test.context.SpringBootTest
37 import spock.util.concurrent.BlockingVariable
38
39 import java.util.concurrent.TimeUnit
40
41 @SpringBootTest(classes = [ObjectMapper, JsonObjectMapper, SubscriptionEventForwarder])
42 class SubscriptionEventForwarderSpec extends MessagingBaseSpec {
43
44     @Autowired
45     SubscriptionEventForwarder objectUnderTest
46
47     @SpringBean
48     InventoryPersistence mockInventoryPersistence = Mock(InventoryPersistence)
49     @SpringBean
50     EventsPublisher<SubscriptionEvent> mockSubscriptionEventPublisher = Mock(EventsPublisher<SubscriptionEvent>)
51     @SpringBean
52     IMap<String, Set<String>> mockForwardedSubscriptionEventCache = Mock(IMap<String, Set<String>>)
53     @SpringBean
54     SubscriptionEventResponseOutcome mockSubscriptionEventResponseOutcome = Mock(SubscriptionEventResponseOutcome)
55     @Autowired
56     JsonObjectMapper jsonObjectMapper
57
58     def 'Forward valid CM create subscription and simulate timeout where #scenario'() {
59         given: 'an event'
60             def jsonData = TestUtils.getResourceFileContent('avcSubscriptionCreationEvent.json')
61             def testEventSent = jsonObjectMapper.convertJsonString(jsonData, SubscriptionEvent.class)
62             def consumerRecord = new ConsumerRecord<String, SubscriptionEvent>('topic-name', 0, 0, 'event-key', testEventSent)
63         and: 'the InventoryPersistence returns private properties for the supplied CM Handles'
64             1 * mockInventoryPersistence.getYangModelCmHandles(["CMHandle1", "CMHandle2", "CMHandle3"]) >> [
65                 createYangModelCmHandleWithDmiProperty(1, 1,"shape","circle"),
66                 createYangModelCmHandleWithDmiProperty(2, 1,"shape","square"),
67                 createYangModelCmHandleWithDmiProperty(3, 2,"shape","triangle")
68             ]
69         and: 'the thread creation delay is reduced to 2 seconds for testing'
70             objectUnderTest.dmiResponseTimeoutInMs = 2000
71         and: 'a Blocking Variable is used for the Asynchronous call with a timeout of 5 seconds'
72             def block = new BlockingVariable<Object>(5)
73         when: 'the valid event is forwarded'
74             objectUnderTest.forwardCreateSubscriptionEvent(testEventSent, consumerRecord.headers())
75         then: 'An asynchronous call is made to the blocking variable'
76             block.get()
77         then: 'the event is added to the forwarded subscription event cache'
78             1 * mockForwardedSubscriptionEventCache.put("SCO-9989752cm-subscription-001", ["DMIName1", "DMIName2"] as Set, 600, TimeUnit.SECONDS)
79         and: 'the event is forwarded twice with the CMHandle private properties and provides a valid listenable future'
80             1 * mockSubscriptionEventPublisher.publishEvent("ncmp-dmi-cm-avc-subscription-DMIName1", "SCO-9989752-cm-subscription-001-DMIName1",
81                 consumerRecord.headers(), subscriptionEvent -> {
82                     Map targets = subscriptionEvent.getEvent().getPredicates().getTargets().get(0)
83                     targets["CMHandle1"] == ["shape":"circle"]
84                     targets["CMHandle2"] == ["shape":"square"]
85                 }
86             )
87             1 * mockSubscriptionEventPublisher.publishEvent("ncmp-dmi-cm-avc-subscription-DMIName2", "SCO-9989752-cm-subscription-001-DMIName2",
88                 consumerRecord.headers(), subscriptionEvent -> {
89                     Map targets = subscriptionEvent.getEvent().getPredicates().getTargets().get(0)
90                     targets["CMHandle3"] == ["shape":"triangle"]
91                 }
92             )
93         and: 'a separate thread has been created where the map is polled'
94             1 * mockForwardedSubscriptionEventCache.containsKey("SCO-9989752cm-subscription-001") >> true
95             1 * mockForwardedSubscriptionEventCache.get(_) >> DMINamesInMap
96             1 * mockSubscriptionEventResponseOutcome.sendResponse(*_)
97         and: 'the subscription id is removed from the event cache map returning the asynchronous blocking variable'
98             1 * mockForwardedSubscriptionEventCache.remove("SCO-9989752cm-subscription-001") >> {block.set(_)}
99         where:
100             scenario                                  | DMINamesInMap
101             'there are dmis which have not responded' | ["DMIName1", "DMIName2"] as Set
102             'all dmis have responded'                 | [] as Set
103     }
104
105     def 'Forward CM create subscription where target CM Handles are #scenario'() {
106         given: 'an event'
107             def jsonData = TestUtils.getResourceFileContent('avcSubscriptionCreationEvent.json')
108             def testEventSent = jsonObjectMapper.convertJsonString(jsonData, SubscriptionEvent.class)
109             def consumerRecord = new ConsumerRecord<String, SubscriptionEvent>('topic-name', 0, 0, 'event-key', testEventSent)
110         and: 'the target CMHandles are set to #scenario'
111             testEventSent.getEvent().getPredicates().setTargets(invalidTargets)
112         when: 'the event is forwarded'
113             objectUnderTest.forwardCreateSubscriptionEvent(testEventSent, consumerRecord.headers())
114         then: 'an operation not yet supported exception is thrown'
115             thrown(OperationNotYetSupportedException)
116         where:
117             scenario   | invalidTargets
118             'null'     | null
119             'empty'    | []
120             'wildcard' | ['CMHandle*']
121     }
122
123     def 'Forward valid CM create subscription where targets are not associated to any existing CMHandles'() {
124         given: 'an event'
125             def jsonData = TestUtils.getResourceFileContent('avcSubscriptionCreationEvent.json')
126             def testEventSent = jsonObjectMapper.convertJsonString(jsonData, SubscriptionEvent.class)
127             def consumerRecord = new ConsumerRecord<String, SubscriptionEvent>('topic-name', 0, 0, 'event-key', testEventSent)
128         and: 'the InventoryPersistence returns no private properties for the supplied CM Handles'
129             1 * mockInventoryPersistence.getYangModelCmHandles(["CMHandle1", "CMHandle2", "CMHandle3"]) >> []
130         and: 'the thread creation delay is reduced to 2 seconds for testing'
131             objectUnderTest.dmiResponseTimeoutInMs = 2000
132         and: 'a Blocking Variable is used for the Asynchronous call with a timeout of 5 seconds'
133             def block = new BlockingVariable<Object>(5)
134         when: 'the valid event is forwarded'
135             objectUnderTest.forwardCreateSubscriptionEvent(testEventSent, consumerRecord.headers())
136         then: 'the event is not added to the forwarded subscription event cache'
137             0 * mockForwardedSubscriptionEventCache.put("SCO-9989752cm-subscription-001", ["DMIName1", "DMIName2"] as Set)
138         and: 'the event is forwarded twice with the CMHandle private properties and provides a valid listenable future'
139             0 * mockSubscriptionEventPublisher.publishEvent("ncmp-dmi-cm-avc-subscription-DMIName1", "SCO-9989752-cm-subscription-001-DMIName1",
140                 consumerRecord.headers(),subscriptionEvent -> {
141                     Map targets = subscriptionEvent.getEvent().getPredicates().getTargets().get(0)
142                     targets["CMHandle1"] == ["shape":"circle"]
143                     targets["CMHandle2"] == ["shape":"square"]
144                 }
145             )
146             0 * mockSubscriptionEventPublisher.publishEvent("ncmp-dmi-cm-avc-subscription-DMIName2", "SCO-9989752-cm-subscription-001-DMIName2",
147                 consumerRecord.headers(),subscriptionEvent -> {
148                     Map targets = subscriptionEvent.getEvent().getPredicates().getTargets().get(0)
149                     targets["CMHandle3"] == ["shape":"triangle"]
150                 }
151             )
152         and: 'a separate thread has been created where the map is polled'
153             0 * mockForwardedSubscriptionEventCache.containsKey("SCO-9989752cm-subscription-001") >> true
154             0 * mockForwardedSubscriptionEventCache.get(_)
155         and: 'the subscription id is removed from the event cache map returning the asynchronous blocking variable'
156             0 * mockForwardedSubscriptionEventCache.remove("SCO-9989752cm-subscription-001") >> {block.set(_)}
157         and: 'subscription outcome has been sent'
158             1 * mockSubscriptionEventResponseOutcome.sendResponse('SCO-9989752', 'cm-subscription-001', true)
159     }
160
161     static def createYangModelCmHandleWithDmiProperty(id, dmiId,propertyName, propertyValue) {
162         return new YangModelCmHandle(id:"CMHandle" + id, dmiDataServiceName: "DMIName" + dmiId, dmiProperties: [new YangModelCmHandle.Property(propertyName,propertyValue)])
163     }
164
165 }