bf8d8519c449e0371af8f4e48ec5de82878d7a6f
[cps.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2022-2025 OpenInfra Foundation Europe. All rights reserved.
4  * Modifications Copyright (C) 2022 Bell Canada
5  * Modifications Copyright (C) 2024 TechMahindra Ltd.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *       http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.cps.ncmp.impl.inventory
24
25 import ch.qos.logback.classic.Level
26 import ch.qos.logback.classic.Logger
27 import ch.qos.logback.classic.spi.ILoggingEvent
28 import ch.qos.logback.core.read.ListAppender
29 import com.fasterxml.jackson.databind.ObjectMapper
30 import com.hazelcast.map.IMap
31 import org.onap.cps.api.CpsDataService
32 import org.onap.cps.api.exceptions.DataNodeNotFoundException
33 import org.onap.cps.api.exceptions.DataValidationException
34 import org.onap.cps.api.model.DataNode
35 import org.onap.cps.impl.DataNodeBuilder
36 import org.onap.cps.ncmp.api.inventory.models.NcmpServiceCmHandle
37 import org.onap.cps.ncmp.impl.inventory.models.YangModelCmHandle
38 import org.onap.cps.ncmp.impl.inventory.sync.lcm.LcmEventsHelper
39 import org.onap.cps.utils.ContentType
40 import org.onap.cps.utils.JsonObjectMapper
41 import org.slf4j.LoggerFactory
42 import spock.lang.Specification
43
44 import static org.onap.cps.api.parameters.FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS
45 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLES_NOT_FOUND
46 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLE_INVALID_ID
47 import static org.onap.cps.ncmp.api.NcmpResponseStatus.UNKNOWN_ERROR
48 import static org.onap.cps.ncmp.api.inventory.models.CmHandleRegistrationResponse.Status
49 import static org.onap.cps.ncmp.impl.inventory.NcmpPersistence.NCMP_DATASPACE_NAME
50 import static org.onap.cps.ncmp.impl.inventory.NcmpPersistence.NCMP_DMI_REGISTRY_ANCHOR
51
52 class CmHandleRegistrationServicePropertyHandlerSpec extends Specification {
53
54     def mockInventoryPersistence = Mock(InventoryPersistence)
55     def mockCpsDataService = Mock(CpsDataService)
56     def jsonObjectMapper = new JsonObjectMapper(new ObjectMapper())
57     def mockAlternateIdChecker = Mock(AlternateIdChecker)
58     def mockCmHandleIdPerAlternateId = Mock(IMap)
59     def mockLcmEventsHelper = Mock(LcmEventsHelper)
60
61     def objectUnderTest = new CmHandleRegistrationServicePropertyHandler(mockInventoryPersistence, mockCpsDataService, jsonObjectMapper, mockAlternateIdChecker, mockCmHandleIdPerAlternateId, mockLcmEventsHelper)
62     def logger = Spy(ListAppender<ILoggingEvent>)
63
64     void setup() {
65         def setupLogger = ((Logger) LoggerFactory.getLogger(CmHandleRegistrationServicePropertyHandler.class))
66         setupLogger.addAppender(logger)
67         setupLogger.setLevel(Level.DEBUG)
68         logger.start()
69         // Always accept all alternate IDs
70         mockAlternateIdChecker.getIdsOfCmHandlesWithRejectedAlternateId(*_) >> []
71     }
72
73     void cleanup() {
74         ((Logger) LoggerFactory.getLogger(CmHandleRegistrationServicePropertyHandler.class)).detachAndStopAllAppenders()
75     }
76
77     def static cmHandleId = 'myHandle1'
78     def static cmHandleXpath = "/dmi-registry/cm-handles[@id='${cmHandleId}']"
79
80     def static propertyDataNodes = [new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/additional-properties[@name='additionalProp1']").withLeaves(['name': 'additionalProp1', 'value': 'additionalValue1']).build(),
81                                     new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/additional-properties[@name='additionalProp2']").withLeaves(['name': 'additionalProp2', 'value': 'additionalValue2']).build(),
82                                     new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/public-properties[@name='publicProp3']").withLeaves(['name': 'publicProp3', 'value': 'publicValue3']).build(),
83                                     new DataNodeBuilder().withXpath("/dmi-registry/cm-handles[@id='${cmHandleId}']/public-properties[@name='publicProp4']").withLeaves(['name': 'publicProp4', 'value': 'publicValue4']).build()]
84     def static cmHandleDataNodeAsCollection = [new DataNode(xpath: cmHandleXpath, childDataNodes: propertyDataNodes, leaves: ['id': cmHandleId])]
85
86     def 'Update CM Handle Public Properties: #scenario'() {
87         given: 'the CPS service return a CM handle'
88             mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(cmHandleId, INCLUDE_ALL_DESCENDANTS) >> cmHandleDataNodeAsCollection
89         and: 'an update cm handle request with public properties updates'
90             def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: updatedPublicProperties)]
91         when: 'update data node leaves is called with the update request'
92             objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
93         then: 'the replace list method is called with correct params'
94             1 * mockInventoryPersistence.replaceListContent(cmHandleXpath, _) >> { args ->
95                 {
96                     assert args[1].leaves.size() == expectedPropertiesAfterUpdate.size()
97                     assert args[1].leaves.containsAll(convertToProperties(expectedPropertiesAfterUpdate))
98                 }
99             }
100         where: 'following public properties updates are made'
101             scenario                          | updatedPublicProperties      || expectedPropertiesAfterUpdate
102             'property added'                  | ['newPubProp1': 'pub-val']   || [['publicProp3': 'publicValue3'], ['publicProp4': 'publicValue4'], ['newPubProp1': 'pub-val']]
103             'property updated'                | ['publicProp4': 'newPubVal'] || [['publicProp3': 'publicValue3'], ['publicProp4': 'newPubVal']]
104             'property removed'                | ['publicProp4': null]        || [['publicProp3': 'publicValue3']]
105             'property ignored(value is null)' | ['pub-prop': null]           || [['publicProp3': 'publicValue3'], ['publicProp4': 'publicValue4']]
106     }
107
108     def 'Update Additional Properties: #scenario'() {
109         given: 'the CPS service return a CM handle'
110             mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(cmHandleId, INCLUDE_ALL_DESCENDANTS) >> cmHandleDataNodeAsCollection
111         and: 'an update cm handle request with additional properties updates'
112             def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, additionalProperties: updatedAdditionalProperties)]
113         when: 'update data node leaves is called with the update request'
114             objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
115         then: 'replace list method should is called with correct params'
116             expectedCallsToReplaceMethod * mockInventoryPersistence.replaceListContent(cmHandleXpath, _) >> { args ->
117                 {
118                     assert args[1].leaves.size() == expectedPropertiesAfterUpdate.size()
119                     assert args[1].leaves.containsAll(convertToProperties(expectedPropertiesAfterUpdate))
120                 }
121             }
122         where: 'following additional properties updates are made'
123             scenario                          | updatedAdditionalProperties          || expectedPropertiesAfterUpdate                                                                                           | expectedCallsToReplaceMethod
124             'property added'                  | ['newAdditionalProp1': 'add-value'] || [['additionalProp1': 'additionalValue1'], ['additionalProp2': 'additionalValue2'], ['newAdditionalProp1': 'add-value']] | 1
125             'property updated'                | ['additionalProp1': 'newValue']     || [['additionalProp2': 'additionalValue2'], ['additionalProp1': 'newValue']]                                              | 1
126             'property removed'                | ['additionalProp1': null]           || [['additionalProp2': 'additionalValue2']]                                                                               | 1
127             'property ignored(value is null)' | ['new-prop': null]                  || [['additionalProp1': 'additionalValue1'], ['additionalProp2': 'additionalValue2']]                                      | 1
128             'no property changes'             | [:]                                 || [['additionalProp1': 'additionalValue1'], ['additionalProp2': 'additionalValue2']]                                      | 0
129     }
130
131     def 'Update CM Handle Properties, remove all public properties: #scenario'() {
132         given: 'the CPS service return a CM handle'
133             def cmHandleDataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': cmHandleId], childDataNodes: originalPropertyDataNodes)
134             mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(cmHandleId, INCLUDE_ALL_DESCENDANTS) >> [cmHandleDataNode]
135         and: 'an update cm handle request that removes all public properties(existing and non-existing)'
136             def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp3': null, 'publicProp4': null])]
137         when: 'update data node leaves is called with the update request'
138             objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
139         then: 'the replace list method is not called'
140             0 * mockInventoryPersistence.replaceListContent(*_)
141         then: 'delete data node will be called for any existing property'
142             expectedCallsToDeleteDataNode * mockInventoryPersistence.deleteDataNode(_) >> { arg ->
143                 {
144                     assert arg[0].contains("@name='publicProp")
145                 }
146             }
147         where: 'following public properties updates are made'
148             scenario                              | originalPropertyDataNodes || expectedCallsToDeleteDataNode
149             '2 original properties, both removed' | propertyDataNodes         || 2
150             'no original properties'              | []                        || 0
151     }
152
153     def '#scenario error leads to #exception when we try to update cmHandle'() {
154         given: 'cm handles request'
155             def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: [:], additionalProperties: [:])]
156         and: 'data node cannot be found'
157             mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(*_) >> { throw exception }
158         when: 'update data node leaves is called using correct parameters'
159             def response = objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
160         then: 'one failed registration response'
161             response.size() == 1
162         and: 'it has expected error details'
163             with(response.get(0)) {
164                 assert it.status == Status.FAILURE
165                 assert it.cmHandle == cmHandleId
166                 assert it.ncmpResponseStatus == expectedError
167                 assert it.errorText == expectedErrorText
168             }
169         where:
170             scenario                   | cmHandleId               | exception                                                                                           || expectedError        | expectedErrorText
171             'Cm Handle does not exist' | 'cmHandleId'             | new DataNodeNotFoundException(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR)                        || CM_HANDLES_NOT_FOUND | 'cm handle reference(s) not found'
172             'Unknown'                  | 'cmHandleId'             | new RuntimeException('Failed')                                                                      || UNKNOWN_ERROR        | 'Failed'
173             'Invalid cm handle id'     | 'cmHandleId with spaces' | new DataValidationException('Name Validation Error.', cmHandleId + 'contains an invalid character') || CM_HANDLE_INVALID_ID | 'cm handle reference has an invalid character(s) in id'
174     }
175
176     def 'Multiple update operations in a single request'() {
177         given: 'cm handles request'
178             def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp1': "value"], additionalProperties: [:]),
179                                          new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp1': "value"], additionalProperties: [:]),
180                                          new NcmpServiceCmHandle(cmHandleId: cmHandleId, publicProperties: ['publicProp1': "value"], additionalProperties: [:])]
181         and: 'data node can be found for 1st and 3rd cm-handle but not for 2nd cm-handle'
182             mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(*_) >> cmHandleDataNodeAsCollection >> {
183                 throw new DataNodeNotFoundException(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR) } >> cmHandleDataNodeAsCollection
184         when: 'update data node leaves is called using correct parameters'
185             def cmHandleResponseList = objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
186         then: 'response has 3 values'
187             cmHandleResponseList.size() == 3
188         and: 'the 1st and 3rd requests were processed successfully'
189             with(cmHandleResponseList.get(0)) {
190                 assert it.status == Status.SUCCESS
191                 assert it.cmHandle == cmHandleId
192             }
193             with(cmHandleResponseList.get(2)) {
194                 assert it.status == Status.SUCCESS
195                 assert it.cmHandle == cmHandleId
196             }
197         and: 'the 2nd request failed with correct error code'
198             with(cmHandleResponseList.get(1)) {
199                 assert it.status == Status.FAILURE
200                 assert it.cmHandle == cmHandleId
201                 assert it.ncmpResponseStatus == CM_HANDLES_NOT_FOUND
202                 assert it.errorText == 'cm handle reference(s) not found'
203             }
204         then: 'the replace list method is called twice'
205             2 * mockInventoryPersistence.replaceListContent(cmHandleXpath, _)
206     }
207
208     def 'Update alternate id of existing CM Handle.'() {
209         given: 'cm handles request'
210             def cmHandleUpdateRequest = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, alternateId: 'alt-1')]
211         and: 'the cm handle per alternate id cache returns a value'
212             mockCmHandleIdPerAlternateId.get(_) >> cmHandleId
213         and: 'a data node found'
214             def dataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': cmHandleId, 'alternate-id': 'alt-1'])
215             mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(cmHandleId, INCLUDE_ALL_DESCENDANTS) >> [dataNode]
216         when: 'cm handle properties is updated'
217             def response = objectUnderTest.updateCmHandleProperties(cmHandleUpdateRequest)
218         then: 'the update is delegated to inventory persistence with correct parameters'
219             1 * mockInventoryPersistence.updateCmHandleField(cmHandleId, 'alternate-id', 'alt-1')
220         and: 'one successful registration response'
221             response.size() == 1
222         and: 'the response shows success for the given cm handle id'
223                 assert response[0].status == Status.SUCCESS
224                 assert response[0].cmHandle == cmHandleId
225     }
226
227     def 'Update with rejected alternate id.'() {
228         given: 'cm handles request'
229             def updatedNcmpServiceCmHandles = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, alternateId: 'alt-1')]
230         and: 'a data node found'
231             def dataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': cmHandleId, 'alternate-id': 'alt-1'])
232             mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(cmHandleId, INCLUDE_ALL_DESCENDANTS) >> [dataNode]
233         when: 'attempt to update the cm handle'
234             def response = objectUnderTest.updateCmHandleProperties(updatedNcmpServiceCmHandles)
235         then: 'the update is NOT delegated to cps data service'
236             0 * mockCpsDataService.updateNodeLeaves(*_)
237         and:  'the alternate id checker rejects the given cm handle (override default setup behavior)'
238             mockAlternateIdChecker.getIdsOfCmHandlesWithRejectedAlternateId(*_) >> [cmHandleId]
239         and: 'the response shows a failure for the given cm handle id'
240             assert response[0].status == Status.FAILURE
241             assert response[0].cmHandle == cmHandleId
242     }
243
244     def 'Update CM Handle data producer identifier from #scenario'() {
245         given:  'an existing cm handle with old data producer identifier'
246             DataNode existingCmHandleDataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': 'cmHandleId', 'data-producer-identifier': oldDataProducerIdentifier])
247         and:    'an update request with a new data producer identifier'
248             def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: 'cmHandleId', dataProducerIdentifier: 'New Data Producer Identifier')
249         and:    'the inventory persistence returns updated yang model'
250             1 * mockInventoryPersistence.getYangModelCmHandle('cmHandleId') >> createYangModelCmHandle('cmHandleId', 'New Data Producer Identifier')
251         when:   'data producer identifier is updated'
252             objectUnderTest.updateDataProducerIdentifier(existingCmHandleDataNode, ncmpServiceCmHandle)
253         then:   'the update node leaves method is invoked once with correct parameters'
254             1 * mockInventoryPersistence.updateCmHandleField('cmHandleId', 'data-producer-identifier', 'New Data Producer Identifier')
255         and:    'LCM event is sent'
256             1 * mockLcmEventsHelper.sendLcmEventBatchAsynchronously({ cmHandleTransitionPairs ->
257                 assert cmHandleTransitionPairs[0].targetYangModelCmHandle.dataProducerIdentifier == 'New Data Producer Identifier'
258             })
259         where: 'the following scenarios are used'
260             scenario             | oldDataProducerIdentifier
261             'null to something'  | null
262             'blank to something' | ''
263     }
264
265     def 'Update CM Handle data producer identifier with same value'() {
266         given: 'an existing cm handle with existing data producer identifier'
267             DataNode existingCmHandleDataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': 'cmHandleId', 'data-producer-identifier': 'same-data-producer-id'])
268         and: 'an update request with the same data producer identifier'
269             def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: 'cmHandleId', dataProducerIdentifier: 'same-data-producer-id')
270         when: 'data producer identifier is updated'
271             objectUnderTest.updateDataProducerIdentifier(existingCmHandleDataNode, ncmpServiceCmHandle)
272         then: 'the update node leaves method is not invoked'
273             0 * mockCpsDataService.updateNodeLeaves(*_)
274         and: 'No LCM events are sent'
275             0 * mockLcmEventsHelper.sendLcmEventBatchAsynchronously(*_)
276         and: 'debug information is logged'
277             def loggingEvent = logger.list[0]
278             assert loggingEvent.level == Level.DEBUG
279             assert loggingEvent.formattedMessage.contains('dataProducerIdentifier for cmHandle cmHandleId is already set to same-data-producer-id')
280     }
281
282     def 'Update CM Handle data producer identifier from existing to new value'() {
283         given: 'an existing cm handle with a data producer identifier'
284             DataNode existingCmHandleDataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': 'cmHandleId', 'data-producer-identifier': 'oldDataProducerIdentifier'])
285         and: 'an update request with a new data producer identifier'
286             def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: 'cmHandleId', dataProducerIdentifier: 'newDataProducerIdentifier')
287         and: 'the inventory persistence returns updated yang model'
288             mockInventoryPersistence.getYangModelCmHandle('cmHandleId') >> createYangModelCmHandle('cmHandleId', 'newDataProducerIdentifier')
289         when: 'update data producer identifier is called'
290             objectUnderTest.updateDataProducerIdentifier(existingCmHandleDataNode, ncmpServiceCmHandle)
291         then: 'the update node leaves method is invoked once with correct parameters'
292             1 * mockInventoryPersistence.updateCmHandleField('cmHandleId', 'data-producer-identifier', 'newDataProducerIdentifier')
293         and: 'LCM event is sent'
294             1 * mockLcmEventsHelper.sendLcmEventBatchAsynchronously( { cmHandleTransitionPairs ->
295                 assert cmHandleTransitionPairs[0].targetYangModelCmHandle.dataProducerIdentifier == 'newDataProducerIdentifier'
296                 assert cmHandleTransitionPairs[0].currentYangModelCmHandle.dataProducerIdentifier == 'oldDataProducerIdentifier'
297             })
298     }
299
300     def 'Update CM Handle data producer identifier with null or blank target identifier'() {
301         given: 'an existing cm handle'
302             DataNode existingCmHandleDataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': 'cmHandleId', 'data-producer-identifier': 'some existing id'])
303         and: 'an update request with null/blank data producer identifier'
304             def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: 'cmHandleId', dataProducerIdentifier: targetDataProducerIdentifier)
305         when: 'data producer identifier update is attempted'
306             objectUnderTest.updateDataProducerIdentifier(existingCmHandleDataNode, ncmpServiceCmHandle)
307         then: 'the update node leaves method is not invoked'
308             0 * mockCpsDataService.updateNodeLeaves(*_)
309         and: 'No LCM events are sent'
310             0 * mockLcmEventsHelper.sendLcmEventBatchAsynchronously(*_)
311         and: 'warning is logged'
312             def lastLoggingEvent = logger.list[0]
313             assert lastLoggingEvent.level == Level.WARN
314             assert lastLoggingEvent.formattedMessage.contains('Ignoring update for cmHandle cmHandleId: target dataProducerIdentifier is null or blank')
315         where: 'the following invalid scenarios are used'
316             scenario      | targetDataProducerIdentifier
317             'null value'  | null
318             'blank value' | ''
319     }
320
321     def convertToProperties(expectedPropertiesAfterUpdateAsMap) {
322         def properties = [].withDefault { [:] }
323         expectedPropertiesAfterUpdateAsMap.forEach(property ->
324             property.forEach((key, val) -> {
325                 properties.add(['name': key, 'value': val])
326             }))
327         return properties
328     }
329
330
331     def createYangModelCmHandle(cmHandleId, dataProducerIdentifier) {
332         new YangModelCmHandle(
333             id: cmHandleId,
334             dmiDataServiceName: 'some-dmi-plugin',
335             dataProducerIdentifier: dataProducerIdentifier,
336             additionalProperties: [],
337             publicProperties: []
338         )
339     }
340 }