Use constants for magic numbers in perf 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.dmi_to_ncmp.Data
39 import org.onap.cps.ncmp.events.avcsubscription1_0_0.dmi_to_ncmp.SubscriptionEventResponse
40 import org.onap.cps.ncmp.events.avcsubscription1_0_0.ncmp_to_dmi.CmHandle;
41 import org.onap.cps.ncmp.utils.TestUtils
42 import org.onap.cps.spi.exceptions.OperationNotYetSupportedException
43 import org.onap.cps.utils.JsonObjectMapper
44 import org.spockframework.spring.SpringBean
45 import org.springframework.beans.factory.annotation.Autowired
46 import org.springframework.boot.test.context.SpringBootTest
47 import spock.util.concurrent.BlockingVariable
48
49 import java.util.concurrent.TimeUnit
50
51 @SpringBootTest(classes = [ObjectMapper, JsonObjectMapper, SubscriptionEventForwarder])
52 class SubscriptionEventForwarderSpec extends MessagingBaseSpec {
53
54     @Autowired
55     SubscriptionEventForwarder 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     SubscriptionEventResponseOutcome mockSubscriptionEventResponseOutcome = Mock(SubscriptionEventResponseOutcome)
65     @SpringBean
66     SubscriptionPersistence mockSubscriptionPersistence = Mock(SubscriptionPersistence)
67     @SpringBean
68     SubscriptionEventMapper subscriptionEventMapper = Mappers.getMapper(SubscriptionEventMapper)
69     @SpringBean
70     ClientSubscriptionEventMapper clientSubscriptionEventMapper = Mappers.getMapper(ClientSubscriptionEventMapper)
71     @Autowired
72     JsonObjectMapper jsonObjectMapper
73
74     def objectMapper = new ObjectMapper()
75
76     def 'Forward valid CM create subscription and simulate timeout'() {
77         given: 'an event'
78             def jsonData = TestUtils.getResourceFileContent('avcSubscriptionCreationEvent.json')
79             def testEventSent = jsonObjectMapper.convertJsonString(jsonData, SubscriptionEvent.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 = toSubscriptionEvent(cloudEvent).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 * mockSubscriptionEventResponseOutcome.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('avcSubscriptionCreationEvent.json')
114             def testEventSent = jsonObjectMapper.convertJsonString(jsonData, SubscriptionEvent.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 yet supported exception is thrown'
120             thrown(OperationNotYetSupportedException)
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('avcSubscriptionCreationEvent.json')
131             def testEventSent = jsonObjectMapper.convertJsonString(jsonData, SubscriptionEvent.class)
132         and: 'a subscription event response'
133             def emptySubscriptionEventResponse = new SubscriptionEventResponse().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 = subscriptionEventMapper.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 = toSubscriptionEvent(cloudEvent).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 = toSubscriptionEvent(cloudEvent).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 * mockSubscriptionEventResponseOutcome.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     def toSubscriptionEvent(cloudEvent) {
192         final PojoCloudEventData<org.onap.cps.ncmp.events.avcsubscription1_0_0.ncmp_to_dmi.SubscriptionEvent> deserializedCloudEvent = CloudEventUtils
193             .mapData(cloudEvent, PojoCloudEventDataMapper.from(objectMapper,
194                 org.onap.cps.ncmp.events.avcsubscription1_0_0.ncmp_to_dmi.SubscriptionEvent.class));
195         if (deserializedCloudEvent == null) {
196             return null;
197         } else {
198             return deserializedCloudEvent.getValue();
199         }
200     }
201
202 }