Improve 32K limit tests
[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 io.cloudevents.CloudEvent
26 import io.cloudevents.core.CloudEventUtils
27 import io.cloudevents.core.data.PojoCloudEventData
28 import io.cloudevents.jackson.PojoCloudEventDataMapper
29 import org.mapstruct.factory.Mappers
30 import org.onap.cps.ncmp.api.impl.events.EventsPublisher
31 import org.onap.cps.ncmp.api.impl.subscriptions.SubscriptionPersistence
32 import org.onap.cps.ncmp.api.impl.subscriptions.SubscriptionStatus
33 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle
34 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelSubscriptionEvent.TargetCmHandle
35 import org.onap.cps.ncmp.api.inventory.InventoryPersistence
36 import org.onap.cps.ncmp.api.kafka.MessagingBaseSpec
37 import org.onap.cps.ncmp.events.avcsubscription1_0_0.client_to_ncmp.SubscriptionEvent
38 import org.onap.cps.ncmp.events.avcsubscription1_0_0.ncmp_to_dmi.CmHandle;
39 import org.onap.cps.ncmp.utils.TestUtils
40 import org.onap.cps.spi.exceptions.OperationNotYetSupportedException
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
47 import java.util.concurrent.TimeUnit
48
49 @SpringBootTest(classes = [ObjectMapper, JsonObjectMapper, SubscriptionEventForwarder])
50 class SubscriptionEventForwarderSpec extends MessagingBaseSpec {
51
52     @Autowired
53     SubscriptionEventForwarder objectUnderTest
54
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     SubscriptionEventResponseOutcome mockSubscriptionEventResponseOutcome = Mock(SubscriptionEventResponseOutcome)
63     @SpringBean
64     SubscriptionPersistence mockSubscriptionPersistence = Mock(SubscriptionPersistence)
65     @SpringBean
66     SubscriptionEventMapper subscriptionEventMapper = Mappers.getMapper(SubscriptionEventMapper)
67     @SpringBean
68     ClientSubscriptionEventMapper clientSubscriptionEventMapper = Mappers.getMapper(ClientSubscriptionEventMapper)
69     @Autowired
70     JsonObjectMapper jsonObjectMapper
71
72     def objectMapper = new ObjectMapper()
73
74     def 'Forward valid CM create subscription and simulate timeout'() {
75         given: 'an event'
76             def jsonData = TestUtils.getResourceFileContent('avcSubscriptionCreationEvent.json')
77             def testEventSent = jsonObjectMapper.convertJsonString(jsonData, SubscriptionEvent.class)
78         and: 'the some of the cm handles will be accepted and some of rejected'
79             def cmHandlesToBeSavedInDb = [new TargetCmHandle('CMHandle1', SubscriptionStatus.ACCEPTED),
80                                      new TargetCmHandle('CMHandle2',SubscriptionStatus.ACCEPTED),
81                                      new TargetCmHandle('CMHandle3',SubscriptionStatus.REJECTED)]
82         and: 'a yang model subscription event will be saved into the db'
83             def yangModelSubscriptionEventWithAcceptedAndRejectedCmHandles = subscriptionEventMapper.toYangModelSubscriptionEvent(testEventSent)
84             yangModelSubscriptionEventWithAcceptedAndRejectedCmHandles.getPredicates().setTargetCmHandles(cmHandlesToBeSavedInDb)
85         and: 'the InventoryPersistence returns private properties for the supplied CM Handles'
86             1 * mockInventoryPersistence.getYangModelCmHandles(["CMHandle1", "CMHandle2", "CMHandle3"]) >> [
87                 createYangModelCmHandleWithDmiProperty(1, 1,"shape","circle"),
88                 createYangModelCmHandleWithDmiProperty(2, 1,"shape","square")
89             ]
90         and: 'the thread creation delay is reduced to 2 seconds for testing'
91             objectUnderTest.dmiResponseTimeoutInMs = 2000
92         and: 'a Blocking Variable is used for the Asynchronous call with a timeout of 5 seconds'
93             def block = new BlockingVariable<Object>(5)
94         when: 'the valid event is forwarded'
95             objectUnderTest.forwardCreateSubscriptionEvent(testEventSent)
96         then: 'An asynchronous call is made to the blocking variable'
97             block.get()
98         then: 'the event is added to the forwarded subscription event cache'
99             1 * mockForwardedSubscriptionEventCache.put("SCO-9989752cm-subscription-001", ["DMIName1"] as Set, 600, TimeUnit.SECONDS)
100         and: 'the event is forwarded twice with the CMHandle private properties and provides a valid listenable future'
101             1 * mockSubscriptionEventPublisher.publishCloudEvent("ncmp-dmi-cm-avc-subscription-DMIName1", "SCO-9989752-cm-subscription-001-DMIName1",
102                 cloudEvent -> {
103                     def targets = toSubscriptionEvent(cloudEvent).getData().getPredicates().getTargets()
104                     def cmHandle2 = createCmHandle('CMHandle2', ['shape':'square'] as Map)
105                     def cmHandle1 = createCmHandle('CMHandle1', ['shape':'circle'] as Map)
106                     targets == [cmHandle2, cmHandle1]
107                 }
108             )
109         and: 'the persistence service save the yang model subscription event'
110             1 * mockSubscriptionPersistence.saveSubscriptionEvent(yangModelSubscriptionEventWithAcceptedAndRejectedCmHandles)
111         and: 'a separate thread has been created where the map is polled'
112             1 * mockForwardedSubscriptionEventCache.containsKey("SCO-9989752cm-subscription-001") >> true
113             1 * mockSubscriptionEventResponseOutcome.sendResponse(*_)
114         and: 'the subscription id is removed from the event cache map returning the asynchronous blocking variable'
115             1 * mockForwardedSubscriptionEventCache.remove("SCO-9989752cm-subscription-001") >> {block.set(_)}
116     }
117
118     def 'Forward CM create subscription where target CM Handles are #scenario'() {
119         given: 'an event'
120             def jsonData = TestUtils.getResourceFileContent('avcSubscriptionCreationEvent.json')
121             def testEventSent = jsonObjectMapper.convertJsonString(jsonData, SubscriptionEvent.class)
122         and: 'the target CMHandles are set to #scenario'
123             testEventSent.getData().getPredicates().setTargets(invalidTargets)
124         when: 'the event is forwarded'
125             objectUnderTest.forwardCreateSubscriptionEvent(testEventSent)
126         then: 'an operation not yet supported exception is thrown'
127             thrown(OperationNotYetSupportedException)
128         where:
129             scenario   | invalidTargets
130             'null'     | null
131             'empty'    | []
132             'wildcard' | ['CMHandle*']
133     }
134
135     def 'Forward valid CM create subscription where targets are not associated to any existing CMHandles'() {
136         given: 'an event'
137             def jsonData = TestUtils.getResourceFileContent('avcSubscriptionCreationEvent.json')
138             def testEventSent = jsonObjectMapper.convertJsonString(jsonData, SubscriptionEvent.class)
139         and: 'the cm handles will be rejected'
140             def rejectedCmHandles = [new TargetCmHandle('CMHandle1', SubscriptionStatus.REJECTED),
141                                      new TargetCmHandle('CMHandle2',SubscriptionStatus.REJECTED),
142                                      new TargetCmHandle('CMHandle3',SubscriptionStatus.REJECTED)]
143         and: 'a yang model subscription event will be saved into the db with rejected cm handles'
144             def yangModelSubscriptionEventWithRejectedCmHandles = subscriptionEventMapper.toYangModelSubscriptionEvent(testEventSent)
145             yangModelSubscriptionEventWithRejectedCmHandles.getPredicates().setTargetCmHandles(rejectedCmHandles)
146         and: 'the InventoryPersistence returns no private properties for the supplied CM Handles'
147             1 * mockInventoryPersistence.getYangModelCmHandles(["CMHandle1", "CMHandle2", "CMHandle3"]) >> []
148         and: 'the thread creation delay is reduced to 2 seconds for testing'
149             objectUnderTest.dmiResponseTimeoutInMs = 2000
150         and: 'a Blocking Variable is used for the Asynchronous call with a timeout of 5 seconds'
151             def block = new BlockingVariable<Object>(5)
152         when: 'the valid event is forwarded'
153             objectUnderTest.forwardCreateSubscriptionEvent(testEventSent)
154         then: 'the event is not added to the forwarded subscription event cache'
155             0 * mockForwardedSubscriptionEventCache.put("SCO-9989752cm-subscription-001", ["DMIName1", "DMIName2"] as Set)
156         and: 'the event is not being forwarded with the CMHandle private properties and does not provides a valid listenable future'
157             0 * mockSubscriptionEventPublisher.publishCloudEvent("ncmp-dmi-cm-avc-subscription-DMIName1", "SCO-9989752-cm-subscription-001-DMIName1",
158                 cloudEvent -> {
159                     def targets = toSubscriptionEvent(cloudEvent).getData().getPredicates().getTargets()
160                     def cmHandle2 = createCmHandle('CMHandle2', ['shape':'square'] as Map)
161                     def cmHandle1 = createCmHandle('CMHandle1', ['shape':'circle'] as Map)
162                     targets == [cmHandle2, cmHandle1]
163                 }
164             )
165             0 * mockSubscriptionEventPublisher.publishCloudEvent("ncmp-dmi-cm-avc-subscription-DMIName2", "SCO-9989752-cm-subscription-001-DMIName2",
166                 cloudEvent -> {
167                     def targets = toSubscriptionEvent(cloudEvent).getData().getPredicates().getTargets()
168                     def cmHandle3 = createCmHandle('CMHandle3', ['shape':'triangle'] as Map)
169                     targets == [cmHandle3]
170                 }
171             )
172         and: 'a separate thread has been created where the map is polled'
173             0 * mockForwardedSubscriptionEventCache.containsKey("SCO-9989752cm-subscription-001") >> true
174             0 * mockForwardedSubscriptionEventCache.get(_)
175         and: 'the subscription id is removed from the event cache map returning the asynchronous blocking variable'
176             0 * mockForwardedSubscriptionEventCache.remove("SCO-9989752cm-subscription-001") >> {block.set(_)}
177         and: 'the persistence service save target cm handles of the yang model subscription event as rejected '
178             1 * mockSubscriptionPersistence.saveSubscriptionEvent(yangModelSubscriptionEventWithRejectedCmHandles)
179         and: 'subscription outcome has been sent'
180             1 * mockSubscriptionEventResponseOutcome.sendResponse('SCO-9989752', 'cm-subscription-001')
181     }
182
183     static def createYangModelCmHandleWithDmiProperty(id, dmiId,propertyName, propertyValue) {
184         return new YangModelCmHandle(id:"CMHandle" + id, dmiDataServiceName: "DMIName" + dmiId, dmiProperties: [new YangModelCmHandle.Property(propertyName,propertyValue)])
185     }
186
187     static def createCmHandle(id, additionalProperties) {
188         def cmHandle = new CmHandle();
189         cmHandle.setId(id)
190         cmHandle.setAdditionalProperties(additionalProperties)
191         return cmHandle
192     }
193
194     def toSubscriptionEvent(cloudEvent) {
195         final PojoCloudEventData<org.onap.cps.ncmp.events.avcsubscription1_0_0.ncmp_to_dmi.SubscriptionEvent> deserializedCloudEvent = CloudEventUtils
196             .mapData(cloudEvent, PojoCloudEventDataMapper.from(objectMapper,
197                 org.onap.cps.ncmp.events.avcsubscription1_0_0.ncmp_to_dmi.SubscriptionEvent.class));
198         if (deserializedCloudEvent == null) {
199             return null;
200         } else {
201             return deserializedCloudEvent.getValue();
202         }
203     }
204
205 }