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