[BUG] Dminame to valid topic suffix
[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 static org.onap.cps.ncmp.api.impl.events.mapper.CloudEventMapper.toTargetEvent
24
25 import com.fasterxml.jackson.databind.ObjectMapper
26 import com.hazelcast.map.IMap
27 import io.cloudevents.CloudEvent
28 import org.mapstruct.factory.Mappers
29 import org.onap.cps.ncmp.api.impl.events.EventsPublisher
30 import org.onap.cps.ncmp.api.impl.subscriptions.SubscriptionPersistence
31 import org.onap.cps.ncmp.api.impl.subscriptions.SubscriptionStatus
32 import org.onap.cps.ncmp.api.impl.utils.CmSubscriptionEventCloudMapper
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.impl.inventory.InventoryPersistence
36 import org.onap.cps.ncmp.api.kafka.MessagingBaseSpec
37 import org.onap.cps.ncmp.events.cmsubscription1_0_0.client_to_ncmp.CmSubscriptionNcmpInEvent
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 @SpringBootTest(classes = [ObjectMapper, JsonObjectMapper, CmSubscriptionNcmpInEventForwarder])
49 class CmSubscriptionNcmpInEventForwarderSpec extends MessagingBaseSpec {
50
51     @Autowired
52     CmSubscriptionNcmpInEventForwarder objectUnderTest
53     @SpringBean
54     InventoryPersistence mockInventoryPersistence = Mock(InventoryPersistence)
55     @SpringBean
56     EventsPublisher<CloudEvent> mockSubscriptionEventPublisher = Mock(EventsPublisher<CloudEvent>)
57     @SpringBean
58     IMap<String, Set<String>> mockForwardedSubscriptionEventCache = Mock(IMap<String, Set<String>>)
59     @SpringBean
60     CmSubscriptionEventCloudMapper subscriptionEventCloudMapper = new CmSubscriptionEventCloudMapper(new ObjectMapper())
61     @SpringBean
62     CmSubscriptionNcmpOutEventPublisher mockCmSubscriptionNcmpOutEventPublisher = Mock(CmSubscriptionNcmpOutEventPublisher)
63     @SpringBean
64     SubscriptionPersistence mockSubscriptionPersistence = Mock(SubscriptionPersistence)
65     @SpringBean
66     CmSubscriptionNcmpInEventMapper cmSubscriptionNcmpInEventMapper = Mappers.getMapper(CmSubscriptionNcmpInEventMapper)
67     @SpringBean
68     CmSubscriptionNcmpInEventToCmSubscriptionDmiInEventMapper cmSubscriptionNcmpInEventToCmSubscriptionDmiInEventMapper = Mappers.getMapper(CmSubscriptionNcmpInEventToCmSubscriptionDmiInEventMapper)
69     @Autowired
70     JsonObjectMapper jsonObjectMapper
71     @Autowired
72     ObjectMapper objectMapper
73
74     def 'Forward valid CM create subscription and simulate timeout'() {
75         given: 'a ncmp in event'
76             def ncmpInEventJsonData = TestUtils.getResourceFileContent('cmSubscriptionNcmpInEvent.json')
77             def ncmpInEventJson = jsonObjectMapper.convertJsonString(ncmpInEventJsonData, CmSubscriptionNcmpInEvent.class)
78         and: 'the InventoryPersistence returns private properties for the supplied CM Handles'
79             1 * mockInventoryPersistence.getYangModelCmHandles(["CMHandle1", "CMHandle2", "CMHandle3"]) >> [
80                 createYangModelCmHandleWithDmiProperty(1, 1,"shape","circle"),
81                 createYangModelCmHandleWithDmiProperty(2, 1,"shape","square"),
82                 createYangModelCmHandleWithDmiProperty(3, 2,"shape","triangle")
83             ]
84         and: 'the thread creation delay is reduced to 2 seconds for testing'
85             objectUnderTest.dmiResponseTimeoutInMs = 2000
86         and: 'a Blocking Variable is used for the Asynchronous call with a timeout of 5 seconds'
87             def block = new BlockingVariable<Object>(5)
88         when: 'the valid event is forwarded'
89             objectUnderTest.forwardCreateSubscriptionEvent(ncmpInEventJson, 'subscriptionCreated')
90         then: 'An asynchronous call is made to the blocking variable'
91             block.get()
92         then: 'the event is added to the forwarded subscription event cache'
93             1 * mockForwardedSubscriptionEventCache.put("SCO-9989752cm-subscription-001", ["DMIName1","DMIName2"] as Set, 600, TimeUnit.SECONDS)
94         and: 'the event is forwarded twice with the CMHandle private properties and provides a valid listenable future'
95             1 * mockSubscriptionEventPublisher.publishCloudEvent("ncmp-dmi-cm-avc-subscription-DMIName1", "SCO-9989752-cm-subscription-001-DMIName1",
96                 cloudEvent -> {
97                     def targets = toTargetEvent(cloudEvent, CmSubscriptionDmiInEvent.class).getData().getPredicates().getTargets()
98                     def cmHandle2 = createCmHandle('CMHandle2', ['shape': 'square'] as Map)
99                     def cmHandle1 = createCmHandle('CMHandle1', ['shape': 'circle'] as Map)
100                     targets == [cmHandle2, cmHandle1]
101                 }
102             )
103             1 * mockSubscriptionEventPublisher.publishCloudEvent("ncmp-dmi-cm-avc-subscription-DMIName2", "SCO-9989752-cm-subscription-001-DMIName2",
104                 cloudEvent -> {
105                     def targets = toTargetEvent(cloudEvent, CmSubscriptionDmiInEvent.class).getData().getPredicates().getTargets()
106                     def cmHandle3 = createCmHandle('CMHandle3', ['shape':'triangle'] as Map)
107                     targets == [cmHandle3]
108                 }
109             )
110         and: 'a separate thread has been created where the map is polled'
111             1 * mockForwardedSubscriptionEventCache.containsKey("SCO-9989752cm-subscription-001") >> true
112             1 * mockCmSubscriptionNcmpOutEventPublisher.sendResponse(*_)
113         and: 'the subscription id is removed from the event cache map returning the asynchronous blocking variable'
114             1 * mockForwardedSubscriptionEventCache.remove("SCO-9989752cm-subscription-001") >> { block.set(_) }
115     }
116
117     def 'Forward CM create subscription where target CM Handles are #scenario'() {
118         given: 'a ncmp in event'
119             def ncmpInEventJsonData = TestUtils.getResourceFileContent('cmSubscriptionNcmpInEvent.json')
120             def ncmpInEventJson = jsonObjectMapper.convertJsonString(ncmpInEventJsonData, CmSubscriptionNcmpInEvent.class)
121         and: 'the target CMHandles are set to #scenario'
122             ncmpInEventJson.getData().getPredicates().setTargets(invalidTargets)
123         when: 'the event is forwarded'
124             objectUnderTest.forwardCreateSubscriptionEvent(ncmpInEventJson, 'some-event-type')
125         then: 'an operation not supported exception is thrown'
126             thrown(UnsupportedOperationException)
127         where:
128             scenario   | invalidTargets
129             'null'     | null
130             'empty'    | []
131             'wildcard' | ['CMHandle*']
132     }
133
134     def 'Forward valid CM create subscription where targets are not associated to any existing CMHandles'() {
135         given: 'a ncmp in event'
136             def ncmpInEventJsonData = TestUtils.getResourceFileContent('cmSubscriptionNcmpInEvent.json')
137             def ncmpInEventJson = jsonObjectMapper.convertJsonString(ncmpInEventJsonData, CmSubscriptionNcmpInEvent.class)
138         and: 'the InventoryPersistence returns no private properties for the supplied CM Handles'
139             1 * mockInventoryPersistence.getYangModelCmHandles(["CMHandle1", "CMHandle2", "CMHandle3"]) >> []
140         and: 'some rejected cm handles'
141             def rejectedCmHandles = [new TargetCmHandle('CMHandle1', SubscriptionStatus.REJECTED, 'Cm handle does not exist'),
142                                      new TargetCmHandle('CMHandle2', SubscriptionStatus.REJECTED, 'Cm handle does not exist'),
143                                      new TargetCmHandle('CMHandle3', SubscriptionStatus.REJECTED, 'Cm handle does not exist')]
144         and: 'a yang model subscription event will be saved into the db with rejected cm handles'
145             def yangModelSubscriptionEvent = cmSubscriptionNcmpInEventMapper.toYangModelSubscriptionEvent(ncmpInEventJson)
146             yangModelSubscriptionEvent.getPredicates().setTargetCmHandles(rejectedCmHandles)
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(ncmpInEventJson, '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 = toTargetEvent(cloudEvent, CmSubscriptionDmiInEvent.class).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 = toTargetEvent(cloudEvent, CmSubscriptionDmiInEvent.class).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(_, 'subscriptionCreatedStatus')
180     }
181
182     def 'Extract domain name from URL for #scenario'() {
183         when: 'a valid dmi name is provided'
184             def domainName = objectUnderTest.toValidTopicSuffix(dmiName)
185         then: 'domain name is as expected with no port information'
186             assert domainName == expectedDomainName
187         where: ''
188             scenario                               | dmiName                            || expectedDomainName
189             'insecure http url with port'          | 'http://www.onap-dmi:8080/xyz=123' || 'onap-dmi'
190             'insecure http url without port'       | 'http://www.onap-dmi/xyz=123'      || 'onap-dmi'
191             'secure https url with port'           | 'https://127.0.0.1:8080/xyz=123'   || '127.0.0.1'
192             'secure https url without port'        | 'https://127.0.0.1/xyz=123'        || '127.0.0.1'
193             'servername without protocol and port' | 'dminame1'                         || 'dminame1'
194             'servername without protocol'          | 'www.onap-dmi:8080/xyz=123'        || 'www.onap-dmi:8080/xyz=123'
195
196     }
197
198     static def createYangModelCmHandleWithDmiProperty(id, dmiId, propertyName, propertyValue) {
199         return new YangModelCmHandle(id: "CMHandle" + id, dmiDataServiceName: "DMIName" + dmiId, dmiProperties: [new YangModelCmHandle.Property(propertyName, propertyValue)])
200     }
201
202     static def createCmHandle(id, additionalProperties) {
203         def cmHandle = new CmHandle();
204         cmHandle.setId(id)
205         cmHandle.setAdditionalProperties(additionalProperties)
206         return cmHandle
207     }
208
209 }