RTD change to document migration to Spring Boot 3.0
[cps.git] / cps-ncmp-service / src / test / groovy / org / onap / cps / ncmp / api / impl / events / cmsubscription / CmSubscriptionNcmpInEventForwarderSpec.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.cmsubscription
22
23 import com.fasterxml.jackson.databind.ObjectMapper
24 import com.hazelcast.map.IMap
25 import io.cloudevents.CloudEvent
26 import org.mapstruct.factory.Mappers
27 import org.onap.cps.ncmp.api.impl.events.EventsPublisher
28 import org.onap.cps.ncmp.api.impl.subscriptions.SubscriptionPersistence
29 import org.onap.cps.ncmp.api.impl.subscriptions.SubscriptionStatus
30 import org.onap.cps.ncmp.api.impl.utils.CmSubscriptionEventCloudMapper
31 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle
32 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelSubscriptionEvent.TargetCmHandle
33 import org.onap.cps.ncmp.api.inventory.InventoryPersistence
34 import org.onap.cps.ncmp.api.kafka.MessagingBaseSpec
35 import org.onap.cps.ncmp.api.models.CmSubscriptionEvent
36 import org.onap.cps.ncmp.events.cmsubscription1_0_0.client_to_ncmp.CmSubscriptionNcmpInEvent
37 import org.onap.cps.ncmp.events.cmsubscription1_0_0.dmi_to_ncmp.CmSubscriptionDmiOutEvent
38 import org.onap.cps.ncmp.events.cmsubscription1_0_0.dmi_to_ncmp.Data
39 import org.onap.cps.ncmp.events.cmsubscription1_0_0.ncmp_to_dmi.CmHandle
40 import org.onap.cps.ncmp.events.cmsubscription1_0_0.ncmp_to_dmi.CmSubscriptionDmiInEvent
41 import org.onap.cps.ncmp.utils.TestUtils
42 import org.onap.cps.utils.JsonObjectMapper
43 import org.spockframework.spring.SpringBean
44 import org.springframework.beans.factory.annotation.Autowired
45 import org.springframework.boot.test.context.SpringBootTest
46 import spock.util.concurrent.BlockingVariable
47 import java.util.concurrent.TimeUnit
48
49 import static org.onap.cps.ncmp.api.impl.events.mapper.CloudEventMapper.toTargetEvent
50
51 @SpringBootTest(classes = [ObjectMapper, JsonObjectMapper, CmSubscriptionNcmpInEventForwarder])
52 class CmSubscriptionNcmpInEventForwarderSpec extends MessagingBaseSpec {
53
54     @Autowired
55     CmSubscriptionNcmpInEventForwarder objectUnderTest
56     @SpringBean
57     InventoryPersistence mockInventoryPersistence = Mock(InventoryPersistence)
58     @SpringBean
59     EventsPublisher<CloudEvent> mockSubscriptionEventPublisher = Mock(EventsPublisher<CloudEvent>)
60     @SpringBean
61     IMap<String, Set<String>> mockForwardedSubscriptionEventCache = Mock(IMap<String, Set<String>>)
62     @SpringBean
63     CmSubscriptionEventCloudMapper subscriptionEventCloudMapper = new CmSubscriptionEventCloudMapper(new ObjectMapper())
64     @SpringBean
65     CmSubscriptionNcmpOutEventPublisher mockCmSubscriptionNcmpOutEventPublisher = Mock(CmSubscriptionNcmpOutEventPublisher)
66     @SpringBean
67     SubscriptionPersistence mockSubscriptionPersistence = Mock(SubscriptionPersistence)
68     @SpringBean
69     CmSubscriptionNcmpInEventMapper cmSubscriptionNcmpInEventMapper = Mappers.getMapper(CmSubscriptionNcmpInEventMapper)
70     @SpringBean
71     CmSubscriptionNcmpInEventToCmSubscriptionDmiInEventMapper cmSubscriptionNcmpInEventToCmSubscriptionDmiInEventMapper = Mappers.getMapper(CmSubscriptionNcmpInEventToCmSubscriptionDmiInEventMapper)
72     @Autowired
73     JsonObjectMapper jsonObjectMapper
74     @Autowired
75     ObjectMapper objectMapper
76
77     def 'Forward valid CM create subscription and simulate timeout'() {
78         given: 'a ncmp in event'
79             def ncmpInEventJsonData = TestUtils.getResourceFileContent('cmSubscriptionNcmpInEvent.json')
80             def ncmpInEventJson = jsonObjectMapper.convertJsonString(ncmpInEventJsonData, CmSubscriptionNcmpInEvent.class)
81         and: 'the InventoryPersistence returns private properties for the supplied CM Handles'
82             1 * mockInventoryPersistence.getYangModelCmHandles(["CMHandle1", "CMHandle2", "CMHandle3"]) >> [
83                 createYangModelCmHandleWithDmiProperty(1, 1,"shape","circle"),
84                 createYangModelCmHandleWithDmiProperty(2, 1,"shape","square"),
85                 createYangModelCmHandleWithDmiProperty(3, 2,"shape","triangle")
86             ]
87         and: 'the thread creation delay is reduced to 2 seconds for testing'
88             objectUnderTest.dmiResponseTimeoutInMs = 2000
89         and: 'a Blocking Variable is used for the Asynchronous call with a timeout of 5 seconds'
90             def block = new BlockingVariable<Object>(5)
91         when: 'the valid event is forwarded'
92             objectUnderTest.forwardCreateSubscriptionEvent(ncmpInEventJson, 'subscriptionCreated')
93         then: 'An asynchronous call is made to the blocking variable'
94             block.get()
95         then: 'the event is added to the forwarded subscription event cache'
96             1 * mockForwardedSubscriptionEventCache.put("SCO-9989752cm-subscription-001", ["DMIName1","DMIName2"] as Set, 600, TimeUnit.SECONDS)
97         and: 'the event is forwarded twice with the CMHandle private properties and provides a valid listenable future'
98             1 * mockSubscriptionEventPublisher.publishCloudEvent("ncmp-dmi-cm-avc-subscription-DMIName1", "SCO-9989752-cm-subscription-001-DMIName1",
99                 cloudEvent -> {
100                     def targets = toTargetEvent(cloudEvent, CmSubscriptionDmiInEvent.class).getData().getPredicates().getTargets()
101                     def cmHandle2 = createCmHandle('CMHandle2', ['shape': 'square'] as Map)
102                     def cmHandle1 = createCmHandle('CMHandle1', ['shape': 'circle'] as Map)
103                     targets == [cmHandle2, cmHandle1]
104                 }
105             )
106             1 * mockSubscriptionEventPublisher.publishCloudEvent("ncmp-dmi-cm-avc-subscription-DMIName2", "SCO-9989752-cm-subscription-001-DMIName2",
107                 cloudEvent -> {
108                     def targets = toTargetEvent(cloudEvent, CmSubscriptionDmiInEvent.class).getData().getPredicates().getTargets()
109                     def cmHandle3 = createCmHandle('CMHandle3', ['shape':'triangle'] as Map)
110                     targets == [cmHandle3]
111                 }
112             )
113         and: 'a separate thread has been created where the map is polled'
114             1 * mockForwardedSubscriptionEventCache.containsKey("SCO-9989752cm-subscription-001") >> true
115             1 * mockCmSubscriptionNcmpOutEventPublisher.sendResponse(*_)
116         and: 'the subscription id is removed from the event cache map returning the asynchronous blocking variable'
117             1 * mockForwardedSubscriptionEventCache.remove("SCO-9989752cm-subscription-001") >> { block.set(_) }
118     }
119
120     def 'Forward CM create subscription where target CM Handles are #scenario'() {
121         given: 'a ncmp in event'
122             def ncmpInEventJsonData = TestUtils.getResourceFileContent('cmSubscriptionNcmpInEvent.json')
123             def ncmpInEventJson = jsonObjectMapper.convertJsonString(ncmpInEventJsonData, CmSubscriptionNcmpInEvent.class)
124         and: 'the target CMHandles are set to #scenario'
125             ncmpInEventJson.getData().getPredicates().setTargets(invalidTargets)
126         when: 'the event is forwarded'
127             objectUnderTest.forwardCreateSubscriptionEvent(ncmpInEventJson, 'some-event-type')
128         then: 'an operation not supported exception is thrown'
129             thrown(UnsupportedOperationException)
130         where:
131             scenario   | invalidTargets
132             'null'     | null
133             'empty'    | []
134             'wildcard' | ['CMHandle*']
135     }
136
137     def 'Forward valid CM create subscription where targets are not associated to any existing CMHandles'() {
138         given: 'a ncmp in event'
139             def ncmpInEventJsonData = TestUtils.getResourceFileContent('cmSubscriptionNcmpInEvent.json')
140             def ncmpInEventJson = jsonObjectMapper.convertJsonString(ncmpInEventJsonData, CmSubscriptionNcmpInEvent.class)
141         and: 'the InventoryPersistence returns no private properties for the supplied CM Handles'
142             1 * mockInventoryPersistence.getYangModelCmHandles(["CMHandle1", "CMHandle2", "CMHandle3"]) >> []
143         and: 'some rejected cm handles'
144             def rejectedCmHandles = [new TargetCmHandle('CMHandle1', SubscriptionStatus.REJECTED, 'Cm handle does not exist'),
145                                      new TargetCmHandle('CMHandle2', SubscriptionStatus.REJECTED, 'Cm handle does not exist'),
146                                      new TargetCmHandle('CMHandle3', SubscriptionStatus.REJECTED, 'Cm handle does not exist')]
147         and: 'a yang model subscription event will be saved into the db with rejected cm handles'
148             def yangModelSubscriptionEvent = cmSubscriptionNcmpInEventMapper.toYangModelSubscriptionEvent(ncmpInEventJson)
149             yangModelSubscriptionEvent.getPredicates().setTargetCmHandles(rejectedCmHandles)
150         and: 'the thread creation delay is reduced to 2 seconds for testing'
151             objectUnderTest.dmiResponseTimeoutInMs = 2000
152         and: 'a Blocking Variable is used for the Asynchronous call with a timeout of 5 seconds'
153             def block = new BlockingVariable<Object>(5)
154         when: 'the valid event is forwarded'
155             objectUnderTest.forwardCreateSubscriptionEvent(ncmpInEventJson, 'subscriptionCreatedStatus')
156         then: 'the event is not added to the forwarded subscription event cache'
157             0 * mockForwardedSubscriptionEventCache.put("SCO-9989752cm-subscription-001", ["DMIName1", "DMIName2"] as Set)
158         and: 'the event is not being forwarded with the CMHandle private properties and does not provides a valid listenable future'
159             0 * mockSubscriptionEventPublisher.publishCloudEvent("ncmp-dmi-cm-avc-subscription-DMIName1", "SCO-9989752-cm-subscription-001-DMIName1",
160                 cloudEvent -> {
161                     def targets = toTargetEvent(cloudEvent, CmSubscriptionDmiInEvent.class).getData().getPredicates().getTargets()
162                     def cmHandle2 = createCmHandle('CMHandle2', ['shape': 'square'] as Map)
163                     def cmHandle1 = createCmHandle('CMHandle1', ['shape': 'circle'] as Map)
164                     targets == [cmHandle2, cmHandle1]
165                 }
166             )
167             0 * mockSubscriptionEventPublisher.publishCloudEvent("ncmp-dmi-cm-avc-subscription-DMIName2", "SCO-9989752-cm-subscription-001-DMIName2",
168                 cloudEvent -> {
169                     def targets = toTargetEvent(cloudEvent, CmSubscriptionDmiInEvent.class).getData().getPredicates().getTargets()
170                     def cmHandle3 = createCmHandle('CMHandle3', ['shape': 'triangle'] as Map)
171                     targets == [cmHandle3]
172                 }
173             )
174         and: 'a separate thread has been created where the map is polled'
175             0 * mockForwardedSubscriptionEventCache.containsKey("SCO-9989752cm-subscription-001") >> true
176             0 * mockForwardedSubscriptionEventCache.get(_)
177         and: 'the subscription id is removed from the event cache map returning the asynchronous blocking variable'
178             0 * mockForwardedSubscriptionEventCache.remove("SCO-9989752cm-subscription-001") >> {block.set(_)}
179         and: 'the persistence service save target cm handles of the yang model subscription event as rejected'
180             1 * mockSubscriptionPersistence.saveSubscriptionEvent(yangModelSubscriptionEvent)
181         and: 'subscription outcome has been sent'
182             1 * mockCmSubscriptionNcmpOutEventPublisher.sendResponse(_, 'subscriptionCreatedStatus')
183     }
184
185     static def createYangModelCmHandleWithDmiProperty(id, dmiId, propertyName, propertyValue) {
186         return new YangModelCmHandle(id: "CMHandle" + id, dmiDataServiceName: "DMIName" + dmiId, dmiProperties: [new YangModelCmHandle.Property(propertyName, propertyValue)])
187     }
188
189     static def createCmHandle(id, additionalProperties) {
190         def cmHandle = new CmHandle();
191         cmHandle.setId(id)
192         cmHandle.setAdditionalProperties(additionalProperties)
193         return cmHandle
194     }
195
196 }