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