0c91208319149aa4b53c9f9743ae9f05a7c09858
[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(_) >> 'someId'
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 cps data service with correct parameters'
219             1 * mockCpsDataService.updateNodeLeaves('NCMP-Admin', 'ncmp-dmi-registry', '/dmi-registry', _, _, ContentType.JSON) >>
220                     { args ->
221                         assert args[3].contains('alt-1')
222                     }
223         and: 'one successful registration response'
224             response.size() == 1
225         and: 'the response shows success for the given cm handle id'
226                 assert response[0].status == Status.SUCCESS
227                 assert response[0].cmHandle == cmHandleId
228     }
229
230     def 'Update with rejected alternate id.'() {
231         given: 'cm handles request'
232             def updatedNcmpServiceCmHandles = [new NcmpServiceCmHandle(cmHandleId: cmHandleId, alternateId: 'alt-1')]
233         and: 'a data node found'
234             def dataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': cmHandleId, 'alternate-id': 'alt-1'])
235             mockInventoryPersistence.getCmHandleDataNodeByCmHandleId(cmHandleId, INCLUDE_ALL_DESCENDANTS) >> [dataNode]
236         when: 'attempt to update the cm handle'
237             def response = objectUnderTest.updateCmHandleProperties(updatedNcmpServiceCmHandles)
238         then: 'the update is NOT delegated to cps data service'
239             0 * mockCpsDataService.updateNodeLeaves(*_)
240         and:  'the alternate id checker rejects the given cm handle (override default setup behavior)'
241             mockAlternateIdChecker.getIdsOfCmHandlesWithRejectedAlternateId(*_) >> [cmHandleId]
242         and: 'the response shows a failure for the given cm handle id'
243             assert response[0].status == Status.FAILURE
244             assert response[0].cmHandle == cmHandleId
245     }
246
247     def 'Update CM Handle data producer identifier from #scenario'() {
248         given: 'an existing cm handle with old data producer identifier'
249             DataNode existingCmHandleDataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': 'cmHandleId', 'data-producer-identifier': oldDataProducerIdentifier])
250         and: 'an update request with a new data producer identifier'
251             def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: 'cmHandleId', dataProducerIdentifier: 'New Data Producer Identifier')
252         and: 'the inventory persistence returns updated yang model'
253             1 * mockInventoryPersistence.getYangModelCmHandle('cmHandleId') >> createYangModelCmHandle('cmHandleId', 'New Data Producer Identifier')
254         when: 'data producer identifier is updated'
255             objectUnderTest.updateDataProducerIdentifier(existingCmHandleDataNode, ncmpServiceCmHandle)
256         then: 'the update node leaves method is invoked once with correct parameters'
257             1 * mockCpsDataService.updateNodeLeaves('NCMP-Admin', 'ncmp-dmi-registry', '/dmi-registry', _, _, ContentType.JSON) >> { args ->
258                 assert args[3].contains('New Data Producer Identifier')
259             }
260         and: 'LCM event is sent'
261             1 * mockLcmEventsHelper.sendLcmEventBatchAsynchronously({ cmHandleTransitionPairs ->
262                 assert cmHandleTransitionPairs[0].targetYangModelCmHandle.dataProducerIdentifier == 'New Data Producer Identifier'
263             })
264         where: 'the following scenarios are used'
265             scenario             | oldDataProducerIdentifier
266             'null to something'  | null
267             'blank to something' | ''
268     }
269
270     def 'Update CM Handle data producer identifier with same value'() {
271         given: 'an existing cm handle with existing data producer identifier'
272             DataNode existingCmHandleDataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': 'cmHandleId', 'data-producer-identifier': 'same-data-producer-id'])
273         and: 'an update request with the same data producer identifier'
274             def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: 'cmHandleId', dataProducerIdentifier: 'same-data-producer-id')
275         when: 'data producer identifier is updated'
276             objectUnderTest.updateDataProducerIdentifier(existingCmHandleDataNode, ncmpServiceCmHandle)
277         then: 'the update node leaves method is not invoked'
278             0 * mockCpsDataService.updateNodeLeaves(*_)
279         and: 'No LCM events are sent'
280             0 * mockLcmEventsHelper.sendLcmEventBatchAsynchronously(*_)
281         and: 'debug information is logged'
282             def loggingEvent = logger.list[0]
283             assert loggingEvent.level == Level.DEBUG
284             assert loggingEvent.formattedMessage.contains('dataProducerIdentifier for cmHandle cmHandleId is already set to same-data-producer-id')
285     }
286
287     def 'Update CM Handle data producer identifier from existing to new value'() {
288         given: 'an existing cm handle with a data producer identifier'
289             DataNode existingCmHandleDataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': 'cmHandleId', 'data-producer-identifier': 'oldDataProducerIdentifier'])
290         and: 'an update request with a new data producer identifier'
291             def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: 'cmHandleId', dataProducerIdentifier: 'newDataProducerIdentifier')
292         and: 'the inventory persistence returns updated yang model'
293             mockInventoryPersistence.getYangModelCmHandle('cmHandleId') >> createYangModelCmHandle('cmHandleId', 'newDataProducerIdentifier')
294         when: 'update data producer identifier is called'
295             objectUnderTest.updateDataProducerIdentifier(existingCmHandleDataNode, ncmpServiceCmHandle)
296         then: 'the update node leaves method is invoked once with correct parameters'
297             1 * mockCpsDataService.updateNodeLeaves('NCMP-Admin', 'ncmp-dmi-registry', '/dmi-registry', _, _, ContentType.JSON) >> { args ->
298                 assert args[3].contains('newDataProducerIdentifier')
299             }
300         and: 'LCM event is sent'
301             1 * mockLcmEventsHelper.sendLcmEventBatchAsynchronously( { cmHandleTransitionPairs ->
302                 assert cmHandleTransitionPairs[0].targetYangModelCmHandle.dataProducerIdentifier == 'newDataProducerIdentifier'
303                 assert cmHandleTransitionPairs[0].currentYangModelCmHandle.dataProducerIdentifier == 'oldDataProducerIdentifier'
304             })
305         and: 'correct information is logged'
306             def loggingEvent = logger.list[1]
307             assert loggingEvent.level == Level.DEBUG
308             assert loggingEvent.formattedMessage.contains('updated from oldDataProducerIdentifier to newDataProducerIdentifier')
309     }
310
311     def 'Update CM Handle data producer identifier with null or blank target identifier'() {
312         given: 'an existing cm handle'
313             DataNode existingCmHandleDataNode = new DataNode(xpath: cmHandleXpath, leaves: ['id': 'cmHandleId', 'data-producer-identifier': 'some existing id'])
314         and: 'an update request with null/blank data producer identifier'
315             def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: 'cmHandleId', dataProducerIdentifier: targetDataProducerIdentifier)
316         when: 'data producer identifier update is attempted'
317             objectUnderTest.updateDataProducerIdentifier(existingCmHandleDataNode, ncmpServiceCmHandle)
318         then: 'the update node leaves method is not invoked'
319             0 * mockCpsDataService.updateNodeLeaves(*_)
320         and: 'No LCM events are sent'
321             0 * mockLcmEventsHelper.sendLcmEventBatchAsynchronously(*_)
322         and: 'warning is logged'
323             def lastLoggingEvent = logger.list[0]
324             assert lastLoggingEvent.level == Level.WARN
325             assert lastLoggingEvent.formattedMessage.contains('Ignoring update for cmHandle cmHandleId: target dataProducerIdentifier is null or blank')
326         where: 'the following invalid scenarios are used'
327             scenario      | targetDataProducerIdentifier
328             'null value'  | null
329             'blank value' | ''
330     }
331
332     def convertToProperties(expectedPropertiesAfterUpdateAsMap) {
333         def properties = [].withDefault { [:] }
334         expectedPropertiesAfterUpdateAsMap.forEach(property ->
335             property.forEach((key, val) -> {
336                 properties.add(['name': key, 'value': val])
337             }))
338         return properties
339     }
340
341
342     def createYangModelCmHandle(cmHandleId, dataProducerIdentifier) {
343         new YangModelCmHandle(
344             id: cmHandleId,
345             dmiDataServiceName: 'some-dmi-plugin',
346             dataProducerIdentifier: dataProducerIdentifier,
347             additionalProperties: [],
348             publicProperties: []
349         )
350     }
351 }